1 /* -*- Mode: C; tab-width: 4 -*-
   2  *
   3  * Copyright (c) 2003-2004, Apple Computer, Inc. All rights reserved.
   4  *
   5  * Redistribution and use in source and binary forms, with or without
   6  * modification, are permitted provided that the following conditions are met:
   7  *
   8  * 1.  Redistributions of source code must retain the above copyright notice,
   9  *     this list of conditions and the following disclaimer.
  10  * 2.  Redistributions in binary form must reproduce the above copyright notice,
  11  *     this list of conditions and the following disclaimer in the documentation
  12  *     and/or other materials provided with the distribution.
  13  * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of its
  14  *     contributors may be used to endorse or promote products derived from this
  15  *     software without specific prior written permission.
  16  *
  17  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
  18  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  19  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  20  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
  21  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  22  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  23  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  24  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  26  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  27  */
  28 
  29 #include <errno.h>
  30 #include <stdlib.h>
  31 #include <fcntl.h>
  32 
  33 #if APPLE_OSX_mDNSResponder
  34 #include <mach-o/dyld.h>
  35 #include <uuid/uuid.h>
  36 #include <TargetConditionals.h>
  37 #endif
  38 
  39 #include "dnssd_ipc.h"
  40 
  41 #if defined(_WIN32)
  42 
  43     #define _SSIZE_T
  44     #include <CommonServices.h>
  45     #include <DebugServices.h>
  46     #include <winsock2.h>
  47     #include <ws2tcpip.h>
  48     #include <windows.h>
  49     #include <stdarg.h>
  50     #include <stdio.h>
  51 
  52     #define sockaddr_mdns sockaddr_in
  53     #define AF_MDNS AF_INET
  54 
  55 // Disable warning: "'type cast' : from data pointer 'void *' to function pointer"
  56     #pragma warning(disable:4055)
  57 
  58 // Disable warning: "nonstandard extension, function/data pointer conversion in expression"
  59     #pragma warning(disable:4152)
  60 
  61 extern BOOL IsSystemServiceDisabled();
  62 
  63     #define sleep(X) Sleep((X) * 1000)
  64 
  65 static int g_initWinsock = 0;
  66     #define LOG_WARNING kDebugLevelWarning
  67     #define LOG_INFO kDebugLevelInfo
  68 static void syslog( int priority, const char * message, ...)
  69 {
  70     va_list args;
  71     int len;
  72     char * buffer;
  73     DWORD err = WSAGetLastError();
  74     (void) priority;
  75     va_start( args, message );
  76     len = _vscprintf( message, args ) + 1;
  77     buffer = malloc( len * sizeof(char) );
  78     if ( buffer ) { vsprintf( buffer, message, args ); OutputDebugString( buffer ); free( buffer ); }
  79     WSASetLastError( err );
  80 }
  81 #else
  82 
  83     #include <sys/fcntl.h>      // For O_RDWR etc.
  84     #include <sys/time.h>
  85     #include <sys/socket.h>
  86     #include <syslog.h>
  87 
  88     #define sockaddr_mdns sockaddr_un
  89     #define AF_MDNS AF_LOCAL
  90 
  91 #endif
  92 
  93 // <rdar://problem/4096913> Specifies how many times we'll try and connect to the server.
  94 
  95 #define DNSSD_CLIENT_MAXTRIES 4
  96 
  97 // Uncomment the line below to use the old error return mechanism of creating a temporary named socket (e.g. in /var/tmp)
  98 //#define USE_NAMED_ERROR_RETURN_SOCKET 1
  99 
 100 // If the UDS client has not received a response from the daemon in 60 secs, it is unlikely to get one
 101 // Note: Timeout of 3 secs should be sufficient in normal scenarios, but 60 secs is chosen as a safeguard since
 102 // some clients may come up before mDNSResponder itself after a BOOT and on rare ocassions IOPM/Keychain/D2D calls
 103 // in mDNSResponder's INIT may take a much longer time to return
 104 #define DNSSD_CLIENT_TIMEOUT 60
 105 
 106 #ifndef CTL_PATH_PREFIX
 107 #define CTL_PATH_PREFIX "/var/tmp/dnssd_result_socket."
 108 #endif
 109 
 110 typedef struct
 111 {
 112     ipc_msg_hdr ipc_hdr;
 113     DNSServiceFlags cb_flags;
 114     uint32_t cb_interface;
 115     DNSServiceErrorType cb_err;
 116 } CallbackHeader;
 117 
 118 typedef struct _DNSServiceRef_t DNSServiceOp;
 119 typedef struct _DNSRecordRef_t DNSRecord;
 120 
 121 #if !defined(_WIN32)
 122 typedef struct
 123 {
 124     void             *AppCallback;      // Client callback function and context
 125     void             *AppContext;
 126 } SleepKAContext;
 127 #endif
 128 
 129 // client stub callback to process message from server and deliver results to client application
 130 typedef void (*ProcessReplyFn)(DNSServiceOp *const sdr, const CallbackHeader *const cbh, const char *msg, const char *const end);
 131 
 132 #define ValidatorBits 0x12345678
 133 #define DNSServiceRefValid(X) (dnssd_SocketValid((X)->sockfd) && (((X)->sockfd ^ (X)->validator) == ValidatorBits))
 134 
 135 // When using kDNSServiceFlagsShareConnection, there is one primary _DNSServiceOp_t, and zero or more subordinates
 136 // For the primary, the 'next' field points to the first subordinate, and its 'next' field points to the next, and so on.
 137 // For the primary, the 'primary' field is NULL; for subordinates the 'primary' field points back to the associated primary
 138 //
 139 // _DNS_SD_LIBDISPATCH is defined where libdispatch/GCD is available. This does not mean that the application will use the
 140 // DNSServiceSetDispatchQueue API. Hence any new code guarded with _DNS_SD_LIBDISPATCH should still be backwards compatible.
 141 struct _DNSServiceRef_t
 142 {
 143     DNSServiceOp     *next;             // For shared connection
 144     DNSServiceOp     *primary;          // For shared connection
 145     dnssd_sock_t sockfd;                // Connected socket between client and daemon
 146     dnssd_sock_t validator;             // Used to detect memory corruption, double disposals, etc.
 147     client_context_t uid;               // For shared connection requests, each subordinate DNSServiceRef has its own ID,
 148                                         // unique within the scope of the same shared parent DNSServiceRef
 149     uint32_t op;                        // request_op_t or reply_op_t
 150     uint32_t max_index;                 // Largest assigned record index - 0 if no additional records registered
 151     uint32_t logcounter;                // Counter used to control number of syslog messages we write
 152     int              *moreptr;          // Set while DNSServiceProcessResult working on this particular DNSServiceRef
 153     ProcessReplyFn ProcessReply;        // Function pointer to the code to handle received messages
 154     void             *AppCallback;      // Client callback function and context
 155     void             *AppContext;
 156     DNSRecord        *rec;
 157 #if _DNS_SD_LIBDISPATCH
 158     dispatch_source_t disp_source;
 159     dispatch_queue_t disp_queue;
 160 #endif
 161     void             *kacontext;
 162 };
 163 
 164 struct _DNSRecordRef_t
 165 {
 166     DNSRecord       *recnext;
 167     void *AppContext;
 168     DNSServiceRegisterRecordReply AppCallback;
 169     DNSRecordRef recref;
 170     uint32_t record_index;  // index is unique to the ServiceDiscoveryRef
 171     client_context_t uid;  // For demultiplexing multiple DNSServiceRegisterRecord calls
 172     DNSServiceOp *sdr;
 173 };
 174 
 175 // Write len bytes. Return 0 on success, -1 on error
 176 static int write_all(dnssd_sock_t sd, char *buf, size_t len)
 177 {
 178     // Don't use "MSG_WAITALL"; it returns "Invalid argument" on some Linux versions; use an explicit while() loop instead.
 179     //if (send(sd, buf, len, MSG_WAITALL) != len) return -1;
 180     while (len)
 181     {
 182         ssize_t num_written = send(sd, buf, (long)len, 0);
 183         if (num_written < 0 || (size_t)num_written > len)
 184         {
 185             // Should never happen. If it does, it indicates some OS bug,
 186             // or that the mDNSResponder daemon crashed (which should never happen).
 187             #if !defined(__ppc__) && defined(SO_ISDEFUNCT)
 188             int defunct;
 189             socklen_t dlen = sizeof (defunct);
 190             if (getsockopt(sd, SOL_SOCKET, SO_ISDEFUNCT, &defunct, &dlen) < 0)
 191                 syslog(LOG_WARNING, "dnssd_clientstub write_all: SO_ISDEFUNCT failed %d %s", dnssd_errno, dnssd_strerror(dnssd_errno));
 192             if (!defunct)
 193                 syslog(LOG_WARNING, "dnssd_clientstub write_all(%d) failed %ld/%ld %d %s", sd,
 194                        (long)num_written, (long)len,
 195                        (num_written < 0) ? dnssd_errno                 : 0,
 196                        (num_written < 0) ? dnssd_strerror(dnssd_errno) : "");
 197             else
 198                 syslog(LOG_INFO, "dnssd_clientstub write_all(%d) DEFUNCT", sd);
 199             #else
 200             syslog(LOG_WARNING, "dnssd_clientstub write_all(%d) failed %ld/%ld %d %s", sd,
 201                    (long)num_written, (long)len,
 202                    (num_written < 0) ? dnssd_errno                 : 0,
 203                    (num_written < 0) ? dnssd_strerror(dnssd_errno) : "");
 204             #endif
 205             return -1;
 206         }
 207         buf += num_written;
 208         len -= num_written;
 209     }
 210     return 0;
 211 }
 212 
 213 enum { read_all_success = 0, read_all_fail = -1, read_all_wouldblock = -2 };
 214 
 215 // Read len bytes. Return 0 on success, read_all_fail on error, or read_all_wouldblock for
 216 static int read_all(dnssd_sock_t sd, char *buf, int len)
 217 {
 218     // Don't use "MSG_WAITALL"; it returns "Invalid argument" on some Linux versions; use an explicit while() loop instead.
 219     //if (recv(sd, buf, len, MSG_WAITALL) != len) return -1;
 220 
 221     while (len)
 222     {
 223         ssize_t num_read = recv(sd, buf, len, 0);
 224         // It is valid to get an interrupted system call error e.g., somebody attaching
 225         // in a debugger, retry without failing
 226         if ((num_read < 0) && (errno == EINTR)) 
 227         { 
 228             syslog(LOG_INFO, "dnssd_clientstub read_all: EINTR continue"); 
 229             continue; 
 230         }
 231         if ((num_read == 0) || (num_read < 0) || (num_read > len))
 232         {
 233             int printWarn = 0;
 234             int defunct = 0;
 235             // Should never happen. If it does, it indicates some OS bug,
 236             // or that the mDNSResponder daemon crashed (which should never happen).
 237 #if defined(WIN32)
 238             // <rdar://problem/7481776> Suppress logs for "A non-blocking socket operation
 239             //                          could not be completed immediately"
 240             if (WSAGetLastError() != WSAEWOULDBLOCK)
 241                 printWarn = 1;
 242 #endif
 243 #if !defined(__ppc__) && defined(SO_ISDEFUNCT)
 244             {
 245                 socklen_t dlen = sizeof (defunct);
 246                 if (getsockopt(sd, SOL_SOCKET, SO_ISDEFUNCT, &defunct, &dlen) < 0)
 247                     syslog(LOG_WARNING, "dnssd_clientstub read_all: SO_ISDEFUNCT failed %d %s", dnssd_errno, dnssd_strerror(dnssd_errno));
 248             }
 249             if (!defunct)
 250                 printWarn = 1;
 251 #endif
 252             if (printWarn)
 253                 syslog(LOG_WARNING, "dnssd_clientstub read_all(%d) failed %ld/%ld %d %s", sd,
 254                        (long)num_read, (long)len,
 255                        (num_read < 0) ? dnssd_errno                 : 0,
 256                        (num_read < 0) ? dnssd_strerror(dnssd_errno) : "");
 257             else if (defunct)
 258                 syslog(LOG_INFO, "dnssd_clientstub read_all(%d) DEFUNCT", sd);
 259             return (num_read < 0 && dnssd_errno == dnssd_EWOULDBLOCK) ? read_all_wouldblock : read_all_fail;
 260         }
 261         buf += num_read;
 262         len -= num_read;
 263     }
 264     return read_all_success;
 265 }
 266 
 267 // Returns 1 if more bytes remain to be read on socket descriptor sd, 0 otherwise
 268 static int more_bytes(dnssd_sock_t sd)
 269 {
 270     struct timeval tv = { 0, 0 };
 271     fd_set readfds;
 272     fd_set *fs;
 273     int ret;
 274 
 275     if (sd < FD_SETSIZE)
 276     {
 277         fs = &readfds;
 278         FD_ZERO(fs);
 279     }
 280     else
 281     {
 282         // Compute the number of integers needed for storing "sd". Internally fd_set is stored
 283         // as an array of ints with one bit for each fd and hence we need to compute
 284         // the number of ints needed rather than the number of bytes. If "sd" is 32, we need
 285         // two ints and not just one.
 286         int nfdbits = sizeof (int) * 8;
 287         int nints = (sd/nfdbits) + 1;
 288         fs = (fd_set *)calloc(nints, sizeof(int));
 289         if (fs == NULL) 
 290         { 
 291             syslog(LOG_WARNING, "dnssd_clientstub more_bytes: malloc failed"); 
 292             return 0; 
 293         }
 294     }
 295     FD_SET(sd, fs);
 296     ret = select((int)sd+1, fs, (fd_set*)NULL, (fd_set*)NULL, &tv);
 297     if (fs != &readfds) 
 298         free(fs);
 299     return (ret > 0);
 300 }
 301 
 302 // set_waitlimit() implements a timeout using select. It is called from deliver_request() before recv() OR accept()
 303 // to ensure the UDS clients are not blocked in these system calls indefinitely.
 304 // Note: Ideally one should never be blocked here, because it indicates either mDNSResponder daemon is not yet up/hung/
 305 // superbusy/crashed or some other OS bug. For eg: On Windows which suffers from 3rd party software 
 306 // (primarily 3rd party firewall software) interfering with proper functioning of the TCP protocol stack it is possible 
 307 // the next operation on this socket(recv/accept) is blocked since we depend on TCP to communicate with the system service.
 308 static int set_waitlimit(dnssd_sock_t sock, int timeout)
 309 {
 310     int gDaemonErr = kDNSServiceErr_NoError;
 311 
 312     // To prevent stack corruption since select does not work with timeout if fds > FD_SETSIZE(1024)
 313     if (!gDaemonErr && sock < FD_SETSIZE)
 314     {
 315         struct timeval tv;
 316         fd_set set;
 317 
 318         FD_ZERO(&set);
 319         FD_SET(sock, &set);
 320         tv.tv_sec = timeout;
 321         tv.tv_usec = 0;
 322         if (!select((int)(sock + 1), &set, NULL, NULL, &tv))
 323         {
 324             // Ideally one should never hit this case: See comments before set_waitlimit()
 325             syslog(LOG_WARNING, "dnssd_clientstub set_waitlimit:_daemon timed out (%d secs) without any response: Socket %d", timeout, sock);
 326             gDaemonErr = kDNSServiceErr_Timeout;
 327         }
 328     }
 329     return gDaemonErr;
 330 }
 331 
 332 /* create_hdr
 333  *
 334  * allocate and initialize an ipc message header. Value of len should initially be the
 335  * length of the data, and is set to the value of the data plus the header. data_start
 336  * is set to point to the beginning of the data section. SeparateReturnSocket should be
 337  * non-zero for calls that can't receive an immediate error return value on their primary
 338  * socket, and therefore require a separate return path for the error code result.
 339  * if zero, the path to a control socket is appended at the beginning of the message buffer.
 340  * data_start is set past this string.
 341  */
 342 static ipc_msg_hdr *create_hdr(uint32_t op, size_t *len, char **data_start, int SeparateReturnSocket, DNSServiceOp *ref)
 343 {
 344     char *msg = NULL;
 345     ipc_msg_hdr *hdr;
 346     int datalen;
 347 #if !defined(USE_TCP_LOOPBACK)
 348     char ctrl_path[64] = "";    // "/var/tmp/dnssd_result_socket.xxxxxxxxxx-xxx-xxxxxx"
 349 #endif
 350 
 351     if (SeparateReturnSocket)
 352     {
 353 #if defined(USE_TCP_LOOPBACK)
 354         *len += 2;  // Allocate space for two-byte port number
 355 #elif defined(USE_NAMED_ERROR_RETURN_SOCKET)
 356         struct timeval tv;
 357         if (gettimeofday(&tv, NULL) < 0)
 358         { syslog(LOG_WARNING, "dnssd_clientstub create_hdr: gettimeofday failed %d %s", dnssd_errno, dnssd_strerror(dnssd_errno)); return NULL; }
 359         sprintf(ctrl_path, "%s%d-%.3lx-%.6lu", CTL_PATH_PREFIX, (int)getpid(),
 360                 (unsigned long)(tv.tv_sec & 0xFFF), (unsigned long)(tv.tv_usec));
 361         *len += strlen(ctrl_path) + 1;
 362 #else
 363         *len += 1;      // Allocate space for single zero byte (empty C string)
 364 #endif
 365     }
 366 
 367     datalen = (int) *len;
 368     *len += sizeof(ipc_msg_hdr);
 369 
 370     // Write message to buffer
 371     msg = malloc(*len);
 372     if (!msg) { syslog(LOG_WARNING, "dnssd_clientstub create_hdr: malloc failed"); return NULL; }
 373 
 374     memset(msg, 0, *len);
 375     hdr = (ipc_msg_hdr *)msg;
 376     hdr->version                = VERSION;
 377     hdr->datalen                = datalen;
 378     hdr->ipc_flags              = 0;
 379     hdr->op                     = op;
 380     hdr->client_context         = ref->uid;
 381     hdr->reg_index              = 0;
 382     *data_start = msg + sizeof(ipc_msg_hdr);
 383 #if defined(USE_TCP_LOOPBACK)
 384     // Put dummy data in for the port, since we don't know what it is yet.
 385     // The data will get filled in before we send the message. This happens in deliver_request().
 386     if (SeparateReturnSocket) put_uint16(0, data_start);
 387 #else
 388     if (SeparateReturnSocket) put_string(ctrl_path, data_start);
 389 #endif
 390     return hdr;
 391 }
 392 
 393 static void FreeDNSRecords(DNSServiceOp *sdRef)
 394 {
 395     DNSRecord *rec = sdRef->rec;
 396     while (rec)
 397     {
 398         DNSRecord *next = rec->recnext;
 399         free(rec);
 400         rec = next;
 401     }
 402 }
 403 
 404 static void FreeDNSServiceOp(DNSServiceOp *x)
 405 {
 406     // We don't use our DNSServiceRefValid macro here because if we're cleaning up after a socket() call failed
 407     // then sockfd could legitimately contain a failing value (e.g. dnssd_InvalidSocket)
 408     if ((x->sockfd ^ x->validator) != ValidatorBits)
 409         syslog(LOG_WARNING, "dnssd_clientstub attempt to dispose invalid DNSServiceRef %p %08X %08X", x, x->sockfd, x->validator);
 410     else
 411     {
 412         x->next         = NULL;
 413         x->primary      = NULL;
 414         x->sockfd       = dnssd_InvalidSocket;
 415         x->validator    = 0xDDDDDDDD;
 416         x->op           = request_op_none;
 417         x->max_index    = 0;
 418         x->logcounter   = 0;
 419         x->moreptr      = NULL;
 420         x->ProcessReply = NULL;
 421         x->AppCallback  = NULL;
 422         x->AppContext   = NULL;
 423 #if _DNS_SD_LIBDISPATCH
 424         if (x->disp_source) dispatch_release(x->disp_source);
 425         x->disp_source  = NULL;
 426         x->disp_queue   = NULL;
 427 #endif
 428         // DNSRecords may have been added to subordinate sdRef e.g., DNSServiceRegister/DNSServiceAddRecord
 429         // or on the main sdRef e.g., DNSServiceCreateConnection/DNSServiveRegisterRecord. DNSRecords may have
 430         // been freed if the application called DNSRemoveRecord
 431         FreeDNSRecords(x);
 432         if (x->kacontext)
 433         {
 434             free(x->kacontext);
 435             x->kacontext = NULL;
 436         }
 437         free(x);
 438     }
 439 }
 440 
 441 // Return a connected service ref (deallocate with DNSServiceRefDeallocate)
 442 static DNSServiceErrorType ConnectToServer(DNSServiceRef *ref, DNSServiceFlags flags, uint32_t op, ProcessReplyFn ProcessReply, void *AppCallback, void *AppContext)
 443 {
 444     int NumTries = 0;
 445 
 446     dnssd_sockaddr_t saddr;
 447     DNSServiceOp *sdr;
 448 
 449     if (!ref) 
 450     { 
 451         syslog(LOG_WARNING, "dnssd_clientstub DNSService operation with NULL DNSServiceRef"); 
 452         return kDNSServiceErr_BadParam; 
 453     }
 454 
 455     if (flags & kDNSServiceFlagsShareConnection)
 456     {
 457         if (!*ref)
 458         {
 459             syslog(LOG_WARNING, "dnssd_clientstub kDNSServiceFlagsShareConnection used with NULL DNSServiceRef");
 460             return kDNSServiceErr_BadParam;
 461         }
 462         if (!DNSServiceRefValid(*ref) || ((*ref)->op != connection_request && (*ref)->op != connection_delegate_request) || (*ref)->primary)
 463         {
 464             syslog(LOG_WARNING, "dnssd_clientstub kDNSServiceFlagsShareConnection used with invalid DNSServiceRef %p %08X %08X op %d",
 465                    (*ref), (*ref)->sockfd, (*ref)->validator, (*ref)->op);
 466             *ref = NULL;
 467             return kDNSServiceErr_BadReference;
 468         }
 469     }
 470 
 471     #if defined(_WIN32)
 472     if (!g_initWinsock)
 473     {
 474         WSADATA wsaData;
 475         g_initWinsock = 1;
 476         if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) { *ref = NULL; return kDNSServiceErr_ServiceNotRunning; }
 477     }
 478     // <rdar://problem/4096913> If the system service is disabled, we only want to try to connect once
 479     if (IsSystemServiceDisabled()) 
 480         NumTries = DNSSD_CLIENT_MAXTRIES;
 481     #endif
 482 
 483     sdr = malloc(sizeof(DNSServiceOp));
 484     if (!sdr) 
 485     { 
 486         syslog(LOG_WARNING, "dnssd_clientstub ConnectToServer: malloc failed"); 
 487         *ref = NULL; 
 488         return kDNSServiceErr_NoMemory; 
 489     }
 490     sdr->next          = NULL;
 491     sdr->primary       = NULL;
 492     sdr->sockfd        = dnssd_InvalidSocket;
 493     sdr->validator     = sdr->sockfd ^ ValidatorBits;
 494     sdr->op            = op;
 495     sdr->max_index     = 0;
 496     sdr->logcounter    = 0;
 497     sdr->moreptr       = NULL;
 498     sdr->uid.u32[0]    = 0;
 499     sdr->uid.u32[1]    = 0;
 500     sdr->ProcessReply  = ProcessReply;
 501     sdr->AppCallback   = AppCallback;
 502     sdr->AppContext    = AppContext;
 503     sdr->rec           = NULL;
 504 #if _DNS_SD_LIBDISPATCH
 505     sdr->disp_source   = NULL;
 506     sdr->disp_queue    = NULL;
 507 #endif
 508     sdr->kacontext     = NULL;
 509 
 510     if (flags & kDNSServiceFlagsShareConnection)
 511     {
 512         DNSServiceOp **p = &(*ref)->next;       // Append ourselves to end of primary's list
 513         while (*p) 
 514             p = &(*p)->next;
 515         *p = sdr;
 516         // Preincrement counter before we use it -- it helps with debugging if we know the all-zeroes ID should never appear
 517         if (++(*ref)->uid.u32[0] == 0) 
 518             ++(*ref)->uid.u32[1];               // In parent DNSServiceOp increment UID counter
 519         sdr->primary    = *ref;                 // Set our primary pointer
 520         sdr->sockfd     = (*ref)->sockfd;       // Inherit primary's socket
 521         sdr->validator  = (*ref)->validator;
 522         sdr->uid        = (*ref)->uid;
 523         //printf("ConnectToServer sharing socket %d\n", sdr->sockfd);
 524     }
 525     else
 526     {
 527         #ifdef SO_NOSIGPIPE
 528         const unsigned long optval = 1;
 529         #endif
 530         #ifndef USE_TCP_LOOPBACK
 531         char* uds_serverpath = getenv(MDNS_UDS_SERVERPATH_ENVVAR);
 532         if (uds_serverpath == NULL)
 533             uds_serverpath = MDNS_UDS_SERVERPATH;
 534         #endif
 535         *ref = NULL;
 536         sdr->sockfd    = socket(AF_DNSSD, SOCK_STREAM, 0);
 537         sdr->validator = sdr->sockfd ^ ValidatorBits;
 538         if (!dnssd_SocketValid(sdr->sockfd))
 539         {
 540             syslog(LOG_WARNING, "dnssd_clientstub ConnectToServer: socket failed %d %s", dnssd_errno, dnssd_strerror(dnssd_errno));
 541             FreeDNSServiceOp(sdr);
 542             return kDNSServiceErr_NoMemory;
 543         }
 544         #ifdef SO_NOSIGPIPE
 545         // Some environments (e.g. OS X) support turning off SIGPIPE for a socket
 546         if (setsockopt(sdr->sockfd, SOL_SOCKET, SO_NOSIGPIPE, &optval, sizeof(optval)) < 0)
 547             syslog(LOG_WARNING, "dnssd_clientstub ConnectToServer: SO_NOSIGPIPE failed %d %s", dnssd_errno, dnssd_strerror(dnssd_errno));
 548         #endif
 549         #if defined(USE_TCP_LOOPBACK)
 550         saddr.sin_family      = AF_INET;
 551         saddr.sin_addr.s_addr = inet_addr(MDNS_TCP_SERVERADDR);
 552         saddr.sin_port        = htons(MDNS_TCP_SERVERPORT);
 553         #else
 554         saddr.sun_family      = AF_LOCAL;
 555         strcpy(saddr.sun_path, uds_serverpath);
 556         #if !defined(__ppc__) && defined(SO_DEFUNCTOK)
 557         {
 558             int defunct = 1;
 559             if (setsockopt(sdr->sockfd, SOL_SOCKET, SO_DEFUNCTOK, &defunct, sizeof(defunct)) < 0)
 560                 syslog(LOG_WARNING, "dnssd_clientstub ConnectToServer: SO_DEFUNCTOK failed %d %s", dnssd_errno, dnssd_strerror(dnssd_errno));
 561         }
 562         #endif
 563         #endif
 564         
 565         while (1)
 566         {
 567             int err = connect(sdr->sockfd, (struct sockaddr *) &saddr, sizeof(saddr));
 568             if (!err)
 569                 break; // If we succeeded, return sdr
 570             // If we failed, then it may be because the daemon is still launching.
 571             // This can happen for processes that launch early in the boot process, while the
 572             // daemon is still coming up. Rather than fail here, we wait 1 sec and try again.
 573             // If, after DNSSD_CLIENT_MAXTRIES, we still can't connect to the daemon,
 574             // then we give up and return a failure code.
 575             if (++NumTries < DNSSD_CLIENT_MAXTRIES)
 576             {
 577                 syslog(LOG_WARNING, "dnssd_clientstub ConnectToServer: connect()-> No of tries: %d", NumTries);  
 578                 sleep(1); // Sleep a bit, then try again
 579             }
 580             else 
 581             {
 582                 syslog(LOG_WARNING, "dnssd_clientstub ConnectToServer: connect() failed path:%s Socket:%d Err:%d Errno:%d %s", 
 583                        uds_serverpath, sdr->sockfd, err, dnssd_errno, dnssd_strerror(dnssd_errno));
 584                 dnssd_close(sdr->sockfd); 
 585                 FreeDNSServiceOp(sdr); 
 586                 return kDNSServiceErr_ServiceNotRunning; 
 587             }
 588         }
 589         //printf("ConnectToServer opened socket %d\n", sdr->sockfd);
 590     }
 591 
 592     *ref = sdr;
 593     return kDNSServiceErr_NoError;
 594 }
 595 
 596 #define deliver_request_bailout(MSG) \
 597     syslog(LOG_WARNING, "dnssd_clientstub deliver_request: %s failed %d (%s)", (MSG), dnssd_errno, dnssd_strerror(dnssd_errno)); goto cleanup
 598 
 599 static DNSServiceErrorType deliver_request(ipc_msg_hdr *hdr, DNSServiceOp *sdr)
 600 {
 601     uint32_t datalen = hdr->datalen;    // We take a copy here because we're going to convert hdr->datalen to network byte order
 602     #if defined(USE_TCP_LOOPBACK) || defined(USE_NAMED_ERROR_RETURN_SOCKET)
 603     char *const data = (char *)hdr + sizeof(ipc_msg_hdr);
 604     #endif
 605     dnssd_sock_t listenfd = dnssd_InvalidSocket, errsd = dnssd_InvalidSocket;
 606     DNSServiceErrorType err = kDNSServiceErr_Unknown;   // Default for the "goto cleanup" cases
 607     int MakeSeparateReturnSocket = 0;
 608 
 609     // Note: need to check hdr->op, not sdr->op.
 610     // hdr->op contains the code for the specific operation we're currently doing, whereas sdr->op
 611     // contains the original parent DNSServiceOp (e.g. for an add_record_request, hdr->op will be
 612     // add_record_request but the parent sdr->op will be connection_request or reg_service_request)
 613     if (sdr->primary ||
 614         hdr->op == reg_record_request || hdr->op == add_record_request || hdr->op == update_record_request || hdr->op == remove_record_request)
 615         MakeSeparateReturnSocket = 1;
 616 
 617     if (!DNSServiceRefValid(sdr))
 618     {
 619         if (hdr)
 620             free(hdr);
 621         syslog(LOG_WARNING, "dnssd_clientstub deliver_request: invalid DNSServiceRef %p %08X %08X", sdr, sdr->sockfd, sdr->validator);
 622         return kDNSServiceErr_BadReference;
 623     }
 624 
 625     if (!hdr) 
 626     { 
 627         syslog(LOG_WARNING, "dnssd_clientstub deliver_request: !hdr"); 
 628         return kDNSServiceErr_Unknown;  
 629     }
 630 
 631     if (MakeSeparateReturnSocket)
 632     {
 633         #if defined(USE_TCP_LOOPBACK)
 634         {
 635             union { uint16_t s; u_char b[2]; } port;
 636             dnssd_sockaddr_t caddr;
 637             dnssd_socklen_t len = (dnssd_socklen_t) sizeof(caddr);
 638             listenfd = socket(AF_DNSSD, SOCK_STREAM, 0);
 639             if (!dnssd_SocketValid(listenfd)) {
 640                                 deliver_request_bailout("TCP socket");
 641                         }
 642 
 643             caddr.sin_family      = AF_INET;
 644             caddr.sin_port        = 0;
 645             caddr.sin_addr.s_addr = inet_addr(MDNS_TCP_SERVERADDR);
 646             if (bind(listenfd, (struct sockaddr*) &caddr, sizeof(caddr)) < 0) {
 647                                 deliver_request_bailout("TCP bind");
 648                         }
 649             if (getsockname(listenfd, (struct sockaddr*) &caddr, &len)   < 0) {
 650                                 deliver_request_bailout("TCP getsockname");
 651                         }
 652                         if (listen(listenfd, 1)                                      < 0) {
 653                                 deliver_request_bailout("TCP listen");
 654                         }
 655             port.s = caddr.sin_port;
 656             data[0] = port.b[0];  // don't switch the byte order, as the
 657             data[1] = port.b[1];  // daemon expects it in network byte order
 658         }
 659         #elif defined(USE_NAMED_ERROR_RETURN_SOCKET)
 660         {
 661             mode_t mask;
 662             int bindresult;
 663             dnssd_sockaddr_t caddr;
 664             listenfd = socket(AF_DNSSD, SOCK_STREAM, 0);
 665             if (!dnssd_SocketValid(listenfd)) {
 666                                 deliver_request_bailout("USE_NAMED_ERROR_RETURN_SOCKET socket");
 667                         }
 668 
 669             caddr.sun_family = AF_LOCAL;
 670             // According to Stevens (section 3.2), there is no portable way to
 671             // determine whether sa_len is defined on a particular platform.
 672             #ifndef NOT_HAVE_SA_LEN
 673             caddr.sun_len = sizeof(struct sockaddr_un);
 674             #endif
 675             strcpy(caddr.sun_path, data);
 676             mask = umask(0);
 677             bindresult = bind(listenfd, (struct sockaddr *)&caddr, sizeof(caddr));
 678             umask(mask);
 679             if (bindresult          < 0) {
 680                                 deliver_request_bailout("USE_NAMED_ERROR_RETURN_SOCKET bind");
 681                         }
 682             if (listen(listenfd, 1) < 0) {
 683                                 deliver_request_bailout("USE_NAMED_ERROR_RETURN_SOCKET listen");
 684                         }
 685         }
 686         #else
 687         {
 688             dnssd_sock_t sp[2];
 689             if (socketpair(AF_DNSSD, SOCK_STREAM, 0, sp) < 0) {
 690                                 deliver_request_bailout("socketpair");
 691                         }
 692             else
 693             {
 694                 errsd    = sp[0];   // We'll read our four-byte error code from sp[0]
 695                 listenfd = sp[1];   // We'll send sp[1] to the daemon
 696                 #if !defined(__ppc__) && defined(SO_DEFUNCTOK)
 697                 {
 698                     int defunct = 1;
 699                     if (setsockopt(errsd, SOL_SOCKET, SO_DEFUNCTOK, &defunct, sizeof(defunct)) < 0)
 700                         syslog(LOG_WARNING, "dnssd_clientstub ConnectToServer: SO_DEFUNCTOK failed %d %s", dnssd_errno, dnssd_strerror(dnssd_errno));
 701                 }
 702                 #endif
 703             }
 704         }
 705         #endif
 706     }
 707 
 708 #if !defined(USE_TCP_LOOPBACK) && !defined(USE_NAMED_ERROR_RETURN_SOCKET)
 709     // If we're going to make a separate error return socket, and pass it to the daemon
 710     // using sendmsg, then we'll hold back one data byte to go with it.
 711     // On some versions of Unix (including Leopard) sending a control message without
 712     // any associated data does not work reliably -- e.g. one particular issue we ran
 713     // into is that if the receiving program is in a kqueue loop waiting to be notified
 714     // of the received message, it doesn't get woken up when the control message arrives.
 715     if (MakeSeparateReturnSocket || sdr->op == send_bpf) 
 716         datalen--;     // Okay to use sdr->op when checking for op == send_bpf
 717 #endif
 718 
 719     // At this point, our listening socket is set up and waiting, if necessary, for the daemon to connect back to
 720     ConvertHeaderBytes(hdr);
 721     //syslog(LOG_WARNING, "dnssd_clientstub deliver_request writing %lu bytes", (unsigned long)(datalen + sizeof(ipc_msg_hdr)));
 722     //if (MakeSeparateReturnSocket) syslog(LOG_WARNING, "dnssd_clientstub deliver_request name is %s", data);
 723 #if TEST_SENDING_ONE_BYTE_AT_A_TIME
 724     unsigned int i;
 725     for (i=0; i<datalen + sizeof(ipc_msg_hdr); i++)
 726     {
 727         syslog(LOG_WARNING, "dnssd_clientstub deliver_request writing %d", i);
 728         if (write_all(sdr->sockfd, ((char *)hdr)+i, 1) < 0)
 729         { syslog(LOG_WARNING, "write_all (byte %u) failed", i); goto cleanup; }
 730         usleep(10000);
 731     }
 732 #else
 733     if (write_all(sdr->sockfd, (char *)hdr, datalen + sizeof(ipc_msg_hdr)) < 0)
 734     {
 735         // write_all already prints an error message if there is an error writing to
 736         // the socket except for DEFUNCT. Logging here is unnecessary and also wrong
 737         // in the case of DEFUNCT sockets
 738         syslog(LOG_INFO, "dnssd_clientstub deliver_request ERROR: write_all(%d, %lu bytes) failed",
 739                sdr->sockfd, (unsigned long)(datalen + sizeof(ipc_msg_hdr)));
 740         goto cleanup;
 741     }
 742 #endif
 743 
 744     if (!MakeSeparateReturnSocket) 
 745         errsd = sdr->sockfd;
 746     if (MakeSeparateReturnSocket || sdr->op == send_bpf)    // Okay to use sdr->op when checking for op == send_bpf
 747     {
 748 #if defined(USE_TCP_LOOPBACK) || defined(USE_NAMED_ERROR_RETURN_SOCKET)
 749         // At this point we may wait in accept for a few milliseconds waiting for the daemon to connect back to us,
 750         // but that's okay -- the daemon should not take more than a few milliseconds to respond.
 751         // set_waitlimit() ensures we do not block indefinitely just in case something is wrong
 752         dnssd_sockaddr_t daddr;
 753         dnssd_socklen_t len = sizeof(daddr);
 754         if ((err = set_waitlimit(listenfd, DNSSD_CLIENT_TIMEOUT)) != kDNSServiceErr_NoError) 
 755             goto cleanup;
 756         errsd = accept(listenfd, (struct sockaddr *)&daddr, &len);
 757         if (!dnssd_SocketValid(errsd)) {
 758             deliver_request_bailout("accept");
 759                 }
 760 #else
 761 
 762         struct iovec vec = { ((char *)hdr) + sizeof(ipc_msg_hdr) + datalen, 1 }; // Send the last byte along with the SCM_RIGHTS
 763         struct msghdr msg;
 764         struct cmsghdr *cmsg;
 765         char cbuf[CMSG_SPACE(4 * sizeof(dnssd_sock_t))];
 766 
 767         msg.msg_name       = 0;
 768         msg.msg_namelen    = 0;
 769         msg.msg_iov        = &vec;
 770         msg.msg_iovlen     = 1;
 771         msg.msg_flags      = 0;
 772         if (MakeSeparateReturnSocket || sdr->op == send_bpf)    // Okay to use sdr->op when checking for op == send_bpf
 773         {
 774             if (sdr->op == send_bpf)
 775             {
 776                 int i;
 777                 char p[12];     // Room for "/dev/bpf999" with terminating null
 778                 for (i=0; i<100; i++)
 779                 {
 780                     snprintf(p, sizeof(p), "/dev/bpf%d", i);
 781                     listenfd = open(p, O_RDWR, 0);
 782                     //if (dnssd_SocketValid(listenfd)) syslog(LOG_WARNING, "Sending fd %d for %s", listenfd, p);
 783                     if (!dnssd_SocketValid(listenfd) && dnssd_errno != EBUSY)
 784                         syslog(LOG_WARNING, "Error opening %s %d (%s)", p, dnssd_errno, dnssd_strerror(dnssd_errno));
 785                     if (dnssd_SocketValid(listenfd) || dnssd_errno != EBUSY) break;
 786                 }
 787             }
 788             msg.msg_control    = cbuf;
 789             msg.msg_controllen = CMSG_LEN(sizeof(dnssd_sock_t));
 790 
 791             cmsg = CMSG_FIRSTHDR(&msg);
 792             cmsg->cmsg_len     = CMSG_LEN(sizeof(dnssd_sock_t));
 793             cmsg->cmsg_level   = SOL_SOCKET;
 794             cmsg->cmsg_type    = SCM_RIGHTS;
 795             *((dnssd_sock_t *)CMSG_DATA(cmsg)) = listenfd;
 796         }
 797 
 798 #if TEST_KQUEUE_CONTROL_MESSAGE_BUG
 799         sleep(1);
 800 #endif
 801 
 802 #if DEBUG_64BIT_SCM_RIGHTS
 803         syslog(LOG_WARNING, "dnssd_clientstub sendmsg read sd=%d write sd=%d %ld %ld %ld/%ld/%ld/%ld",
 804                errsd, listenfd, sizeof(dnssd_sock_t), sizeof(void*),
 805                sizeof(struct cmsghdr) + sizeof(dnssd_sock_t),
 806                CMSG_LEN(sizeof(dnssd_sock_t)), (long)CMSG_SPACE(sizeof(dnssd_sock_t)),
 807                (long)((char*)CMSG_DATA(cmsg) + 4 - cbuf));
 808 #endif // DEBUG_64BIT_SCM_RIGHTS
 809 
 810         if (sendmsg(sdr->sockfd, &msg, 0) < 0)
 811         {
 812             syslog(LOG_WARNING, "dnssd_clientstub deliver_request ERROR: sendmsg failed read sd=%d write sd=%d errno %d (%s)",
 813                    errsd, listenfd, dnssd_errno, dnssd_strerror(dnssd_errno));
 814             err = kDNSServiceErr_Incompatible;
 815             goto cleanup;
 816         }
 817 
 818 #if DEBUG_64BIT_SCM_RIGHTS
 819         syslog(LOG_WARNING, "dnssd_clientstub sendmsg read sd=%d write sd=%d okay", errsd, listenfd);
 820 #endif // DEBUG_64BIT_SCM_RIGHTS
 821 
 822 #endif
 823         // Close our end of the socketpair *before* calling read_all() to get the four-byte error code.
 824         // Otherwise, if the daemon closes our socket (or crashes), we will have to wait for a timeout
 825         // in read_all() because the socket is not closed (we still have an open reference to it)
 826         // Note: listenfd is overwritten in the case of send_bpf above and that will be closed here
 827         // for send_bpf operation.
 828         dnssd_close(listenfd);
 829         listenfd = dnssd_InvalidSocket; // Make sure we don't close it a second time in the cleanup handling below
 830     }
 831 
 832     // At this point we may wait in read_all for a few milliseconds waiting for the daemon to send us the error code,
 833     // but that's okay -- the daemon should not take more than a few milliseconds to respond.
 834     // set_waitlimit() ensures we do not block indefinitely just in case something is wrong
 835     if (sdr->op == send_bpf)    // Okay to use sdr->op when checking for op == send_bpf
 836         err = kDNSServiceErr_NoError;
 837     else if ((err = set_waitlimit(errsd, DNSSD_CLIENT_TIMEOUT)) == kDNSServiceErr_NoError)
 838     {
 839         if (read_all(errsd, (char*)&err, (int)sizeof(err)) < 0)
 840             err = kDNSServiceErr_ServiceNotRunning; // On failure read_all will have written a message to syslog for us
 841         else
 842             err = ntohl(err);
 843     }
 844     //syslog(LOG_WARNING, "dnssd_clientstub deliver_request: retrieved error code %d", err);
 845 
 846 cleanup:
 847     if (MakeSeparateReturnSocket)
 848     {
 849         if (dnssd_SocketValid(listenfd)) dnssd_close(listenfd);
 850         if (dnssd_SocketValid(errsd)) dnssd_close(errsd);
 851 #if defined(USE_NAMED_ERROR_RETURN_SOCKET)
 852         // syslog(LOG_WARNING, "dnssd_clientstub deliver_request: removing UDS: %s", data);
 853         if (unlink(data) != 0)
 854             syslog(LOG_WARNING, "dnssd_clientstub WARNING: unlink(\"%s\") failed errno %d (%s)", data, dnssd_errno, dnssd_strerror(dnssd_errno));
 855         // else syslog(LOG_WARNING, "dnssd_clientstub deliver_request: removed UDS: %s", data);
 856 #endif
 857     }
 858 
 859     free(hdr);
 860     return err;
 861 }
 862 
 863 int DNSSD_API DNSServiceRefSockFD(DNSServiceRef sdRef)
 864 {
 865     if (!sdRef) { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRefSockFD called with NULL DNSServiceRef"); return dnssd_InvalidSocket; }
 866 
 867     if (!DNSServiceRefValid(sdRef))
 868     {
 869         syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRefSockFD called with invalid DNSServiceRef %p %08X %08X",
 870                sdRef, sdRef->sockfd, sdRef->validator);
 871         return dnssd_InvalidSocket;
 872     }
 873 
 874     if (sdRef->primary)
 875     {
 876         syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRefSockFD undefined for kDNSServiceFlagsShareConnection subordinate DNSServiceRef %p", sdRef);
 877         return dnssd_InvalidSocket;
 878     }
 879 
 880     return (int) sdRef->sockfd;
 881 }
 882 
 883 #if _DNS_SD_LIBDISPATCH
 884 static void CallbackWithError(DNSServiceRef sdRef, DNSServiceErrorType error)
 885 {
 886     DNSServiceOp *sdr = sdRef;
 887     DNSServiceOp *sdrNext;
 888     DNSRecord *rec;
 889     DNSRecord *recnext;
 890     int morebytes;
 891 
 892     while (sdr)
 893     {
 894         // We can't touch the sdr after the callback as it can be deallocated in the callback
 895         sdrNext = sdr->next;
 896         morebytes = 1;
 897         sdr->moreptr = &morebytes;
 898         switch (sdr->op)
 899         {
 900         case resolve_request:
 901             if (sdr->AppCallback) ((DNSServiceResolveReply)    sdr->AppCallback)(sdr, 0, 0, error, NULL, 0, 0, 0, NULL,    sdr->AppContext);
 902             break;
 903         case query_request:
 904             if (sdr->AppCallback) ((DNSServiceQueryRecordReply)sdr->AppCallback)(sdr, 0, 0, error, NULL, 0, 0, 0, NULL, 0, sdr->AppContext);
 905             break;
 906         case addrinfo_request:
 907             if (sdr->AppCallback) ((DNSServiceGetAddrInfoReply)sdr->AppCallback)(sdr, 0, 0, error, NULL, NULL, 0,          sdr->AppContext);
 908             break;
 909         case browse_request:
 910             if (sdr->AppCallback) ((DNSServiceBrowseReply)     sdr->AppCallback)(sdr, 0, 0, error, NULL, 0, NULL,          sdr->AppContext);
 911             break;
 912         case reg_service_request:
 913             if (sdr->AppCallback) ((DNSServiceRegisterReply)   sdr->AppCallback)(sdr, 0,    error, NULL, 0, NULL,          sdr->AppContext);
 914             break;
 915         case enumeration_request:
 916             if (sdr->AppCallback) ((DNSServiceDomainEnumReply) sdr->AppCallback)(sdr, 0, 0, error, NULL,                   sdr->AppContext);
 917             break;
 918         case connection_request:
 919         case connection_delegate_request:
 920             // This means Register Record, walk the list of DNSRecords to do the callback
 921             rec = sdr->rec;
 922             while (rec)
 923             {
 924                 recnext = rec->recnext;
 925                 if (rec->AppCallback) ((DNSServiceRegisterRecordReply)rec->AppCallback)(sdr, 0, 0, error, rec->AppContext);
 926                 // The Callback can call DNSServiceRefDeallocate which in turn frees sdr and all the records.
 927                 // Detect that and return early
 928                 if (!morebytes) {syslog(LOG_WARNING, "dnssdclientstub:Record: CallbackwithError morebytes zero"); return;}
 929                 rec = recnext;
 930             }
 931             break;
 932         case port_mapping_request:
 933             if (sdr->AppCallback) ((DNSServiceNATPortMappingReply)sdr->AppCallback)(sdr, 0, 0, error, 0, 0, 0, 0, 0, sdr->AppContext);
 934             break;
 935         default:
 936             syslog(LOG_WARNING, "dnssd_clientstub CallbackWithError called with bad op %d", sdr->op);
 937         }
 938         // If DNSServiceRefDeallocate was called in the callback, morebytes will be zero. As the sdRef
 939         // (and its subordinates) have been freed, we should not proceed further. Note that when we
 940         // call the callback with a subordinate sdRef the application can call DNSServiceRefDeallocate
 941         // on the main sdRef and DNSServiceRefDeallocate handles this case by walking all the sdRefs and
 942         // clears the moreptr so that we can terminate here.
 943         //
 944         // If DNSServiceRefDeallocate was not called in the callback, then set moreptr to NULL so that
 945         // we don't access the stack variable after we return from this function.
 946         if (!morebytes) {syslog(LOG_WARNING, "dnssdclientstub:sdRef: CallbackwithError morebytes zero sdr %p", sdr); return;}
 947         else {sdr->moreptr = NULL;}
 948         sdr = sdrNext;
 949     }
 950 }
 951 #endif // _DNS_SD_LIBDISPATCH
 952 
 953 // Handle reply from server, calling application client callback. If there is no reply
 954 // from the daemon on the socket contained in sdRef, the call will block.
 955 DNSServiceErrorType DNSSD_API DNSServiceProcessResult(DNSServiceRef sdRef)
 956 {
 957     int morebytes = 0;
 958 
 959     if (!sdRef) { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceProcessResult called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam; }
 960 
 961     if (!DNSServiceRefValid(sdRef))
 962     {
 963         syslog(LOG_WARNING, "dnssd_clientstub DNSServiceProcessResult called with invalid DNSServiceRef %p %08X %08X", sdRef, sdRef->sockfd, sdRef->validator);
 964         return kDNSServiceErr_BadReference;
 965     }
 966 
 967     if (sdRef->primary)
 968     {
 969         syslog(LOG_WARNING, "dnssd_clientstub DNSServiceProcessResult undefined for kDNSServiceFlagsShareConnection subordinate DNSServiceRef %p", sdRef);
 970         return kDNSServiceErr_BadReference;
 971     }
 972 
 973     if (!sdRef->ProcessReply)
 974     {
 975         static int num_logs = 0;
 976         if (num_logs < 10) syslog(LOG_WARNING, "dnssd_clientstub DNSServiceProcessResult called with DNSServiceRef with no ProcessReply function");
 977         if (num_logs < 1000) num_logs++;else sleep(1);
 978         return kDNSServiceErr_BadReference;
 979     }
 980 
 981     do
 982     {
 983         CallbackHeader cbh;
 984         char *data;
 985 
 986         // return NoError on EWOULDBLOCK. This will handle the case
 987         // where a non-blocking socket is told there is data, but it was a false positive.
 988         // On error, read_all will write a message to syslog for us, so don't need to duplicate that here
 989         // Note: If we want to properly support using non-blocking sockets in the future
 990         int result = read_all(sdRef->sockfd, (void *)&cbh.ipc_hdr, sizeof(cbh.ipc_hdr));
 991         if (result == read_all_fail)
 992         {
 993             // Set the ProcessReply to NULL before callback as the sdRef can get deallocated
 994             // in the callback.
 995             sdRef->ProcessReply = NULL;
 996 #if _DNS_SD_LIBDISPATCH
 997             // Call the callbacks with an error if using the dispatch API, as DNSServiceProcessResult
 998             // is not called by the application and hence need to communicate the error. Cancel the
 999             // source so that we don't get any more events
1000             // Note: read_all fails if we could not read from the daemon which can happen if the
1001             // daemon dies or the file descriptor is disconnected (defunct).
1002             if (sdRef->disp_source)
1003             {
1004                 dispatch_source_cancel(sdRef->disp_source);
1005                 dispatch_release(sdRef->disp_source);
1006                 sdRef->disp_source = NULL;
1007                 CallbackWithError(sdRef, kDNSServiceErr_ServiceNotRunning);
1008             }
1009 #endif
1010             // Don't touch sdRef anymore as it might have been deallocated
1011             return kDNSServiceErr_ServiceNotRunning;
1012         }
1013         else if (result == read_all_wouldblock)
1014         {
1015             if (morebytes && sdRef->logcounter < 100)
1016             {
1017                 sdRef->logcounter++;
1018                 syslog(LOG_WARNING, "dnssd_clientstub DNSServiceProcessResult error: select indicated data was waiting but read_all returned EWOULDBLOCK");
1019             }
1020             return kDNSServiceErr_NoError;
1021         }
1022 
1023         ConvertHeaderBytes(&cbh.ipc_hdr);
1024         if (cbh.ipc_hdr.version != VERSION)
1025         {
1026             syslog(LOG_WARNING, "dnssd_clientstub DNSServiceProcessResult daemon version %d does not match client version %d", cbh.ipc_hdr.version, VERSION);
1027             sdRef->ProcessReply = NULL;
1028             return kDNSServiceErr_Incompatible;
1029         }
1030 
1031         data = malloc(cbh.ipc_hdr.datalen);
1032         if (!data) return kDNSServiceErr_NoMemory;
1033         if (read_all(sdRef->sockfd, data, cbh.ipc_hdr.datalen) < 0) // On error, read_all will write a message to syslog for us
1034         {
1035             // Set the ProcessReply to NULL before callback as the sdRef can get deallocated
1036             // in the callback.
1037             sdRef->ProcessReply = NULL;
1038 #if _DNS_SD_LIBDISPATCH
1039             // Call the callbacks with an error if using the dispatch API, as DNSServiceProcessResult
1040             // is not called by the application and hence need to communicate the error. Cancel the
1041             // source so that we don't get any more events
1042             if (sdRef->disp_source)
1043             {
1044                 dispatch_source_cancel(sdRef->disp_source);
1045                 dispatch_release(sdRef->disp_source);
1046                 sdRef->disp_source = NULL;
1047                 CallbackWithError(sdRef, kDNSServiceErr_ServiceNotRunning);
1048             }
1049 #endif
1050             // Don't touch sdRef anymore as it might have been deallocated
1051             free(data);
1052             return kDNSServiceErr_ServiceNotRunning;
1053         }
1054         else
1055         {
1056             const char *ptr = data;
1057             cbh.cb_flags     = get_flags     (&ptr, data + cbh.ipc_hdr.datalen);
1058             cbh.cb_interface = get_uint32    (&ptr, data + cbh.ipc_hdr.datalen);
1059             cbh.cb_err       = get_error_code(&ptr, data + cbh.ipc_hdr.datalen);
1060 
1061             // CAUTION: We have to handle the case where the client calls DNSServiceRefDeallocate from within the callback function.
1062             // To do this we set moreptr to point to morebytes. If the client does call DNSServiceRefDeallocate(),
1063             // then that routine will clear morebytes for us, and cause us to exit our loop.
1064             morebytes = more_bytes(sdRef->sockfd);
1065             if (morebytes)
1066             {
1067                 cbh.cb_flags |= kDNSServiceFlagsMoreComing;
1068                 sdRef->moreptr = &morebytes;
1069             }
1070             if (ptr) sdRef->ProcessReply(sdRef, &cbh, ptr, data + cbh.ipc_hdr.datalen);
1071             // Careful code here:
1072             // If morebytes is non-zero, that means we set sdRef->moreptr above, and the operation was not
1073             // cancelled out from under us, so now we need to clear sdRef->moreptr so we don't leave a stray
1074             // dangling pointer pointing to a long-gone stack variable.
1075             // If morebytes is zero, then one of two thing happened:
1076             // (a) morebytes was 0 above, so we didn't set sdRef->moreptr, so we don't need to clear it
1077             // (b) morebytes was 1 above, and we set sdRef->moreptr, but the operation was cancelled (with DNSServiceRefDeallocate()),
1078             //     so we MUST NOT try to dereference our stale sdRef pointer.
1079             if (morebytes) sdRef->moreptr = NULL;
1080         }
1081         free(data);
1082     } while (morebytes);
1083 
1084     return kDNSServiceErr_NoError;
1085 }
1086 
1087 void DNSSD_API DNSServiceRefDeallocate(DNSServiceRef sdRef)
1088 {
1089     if (!sdRef) { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRefDeallocate called with NULL DNSServiceRef"); return; }
1090 
1091     if (!DNSServiceRefValid(sdRef))     // Also verifies dnssd_SocketValid(sdRef->sockfd) for us too
1092     {
1093         syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRefDeallocate called with invalid DNSServiceRef %p %08X %08X", sdRef, sdRef->sockfd, sdRef->validator);
1094         return;
1095     }
1096 
1097     // If we're in the middle of a DNSServiceProcessResult() invocation for this DNSServiceRef, clear its morebytes flag to break it out of its while loop
1098     if (sdRef->moreptr) *(sdRef->moreptr) = 0;
1099 
1100     if (sdRef->primary)     // If this is a subordinate DNSServiceOp, just send a 'stop' command
1101     {
1102         DNSServiceOp **p = &sdRef->primary->next;
1103         while (*p && *p != sdRef) p = &(*p)->next;
1104         if (*p)
1105         {
1106             char *ptr;
1107             size_t len = 0;
1108             ipc_msg_hdr *hdr = create_hdr(cancel_request, &len, &ptr, 0, sdRef);
1109             if (hdr)
1110             {
1111                 ConvertHeaderBytes(hdr);
1112                 write_all(sdRef->sockfd, (char *)hdr, len);
1113                 free(hdr);
1114             }
1115             *p = sdRef->next;
1116             FreeDNSServiceOp(sdRef);
1117         }
1118     }
1119     else                    // else, make sure to terminate all subordinates as well
1120     {
1121 #if _DNS_SD_LIBDISPATCH
1122         // The cancel handler will close the fd if a dispatch source has been set
1123         if (sdRef->disp_source)
1124         {
1125             // By setting the ProcessReply to NULL, we make sure that we never call
1126             // the application callbacks ever, after returning from this function. We
1127             // assume that DNSServiceRefDeallocate is called from the serial queue
1128             // that was passed to DNSServiceSetDispatchQueue. Hence, dispatch_source_cancel
1129             // should cancel all the blocks on the queue and hence there should be no more
1130             // callbacks when we return from this function. Setting ProcessReply to NULL
1131             // provides extra protection.
1132             sdRef->ProcessReply = NULL;
1133             shutdown(sdRef->sockfd, SHUT_WR);
1134             dispatch_source_cancel(sdRef->disp_source);
1135             dispatch_release(sdRef->disp_source);
1136             sdRef->disp_source = NULL;
1137         }
1138         // if disp_queue is set, it means it used the DNSServiceSetDispatchQueue API. In that case,
1139         // when the source was cancelled, the fd was closed in the handler. Currently the source
1140         // is cancelled only when the mDNSResponder daemon dies
1141         else if (!sdRef->disp_queue) dnssd_close(sdRef->sockfd);
1142 #else
1143         dnssd_close(sdRef->sockfd);
1144 #endif
1145         // Free DNSRecords added in DNSRegisterRecord if they have not
1146         // been freed in DNSRemoveRecord
1147         while (sdRef)
1148         {
1149             DNSServiceOp *p = sdRef;
1150             sdRef = sdRef->next;
1151             // When there is an error reading from the daemon e.g., bad fd, CallbackWithError
1152             // is called which sets moreptr. It might set the moreptr on a subordinate sdRef
1153             // but the application might call DNSServiceRefDeallocate with the main sdRef from
1154             // the callback. Hence, when we loop through the subordinate sdRefs, we need
1155             // to clear the moreptr so that CallbackWithError can terminate itself instead of
1156             // walking through the freed sdRefs.
1157             if (p->moreptr) *(p->moreptr) = 0;
1158             FreeDNSServiceOp(p);
1159         }
1160     }
1161 }
1162 
1163 DNSServiceErrorType DNSSD_API DNSServiceGetProperty(const char *property, void *result, uint32_t *size)
1164 {
1165     char *ptr;
1166     size_t len = strlen(property) + 1;
1167     ipc_msg_hdr *hdr;
1168     DNSServiceOp *tmp;
1169     uint32_t actualsize;
1170 
1171     DNSServiceErrorType err = ConnectToServer(&tmp, 0, getproperty_request, NULL, NULL, NULL);
1172     if (err) return err;
1173 
1174     hdr = create_hdr(getproperty_request, &len, &ptr, 0, tmp);
1175     if (!hdr) { DNSServiceRefDeallocate(tmp); return kDNSServiceErr_NoMemory; }
1176 
1177     put_string(property, &ptr);
1178     err = deliver_request(hdr, tmp);        // Will free hdr for us
1179     if (read_all(tmp->sockfd, (char*)&actualsize, (int)sizeof(actualsize)) < 0)
1180     { DNSServiceRefDeallocate(tmp); return kDNSServiceErr_ServiceNotRunning; }
1181 
1182     actualsize = ntohl(actualsize);
1183     if (read_all(tmp->sockfd, (char*)result, actualsize < *size ? actualsize : *size) < 0)
1184     { DNSServiceRefDeallocate(tmp); return kDNSServiceErr_ServiceNotRunning; }
1185     DNSServiceRefDeallocate(tmp);
1186 
1187     // Swap version result back to local process byte order
1188     if (!strcmp(property, kDNSServiceProperty_DaemonVersion) && *size >= 4)
1189         *(uint32_t*)result = ntohl(*(uint32_t*)result);
1190 
1191     *size = actualsize;
1192     return kDNSServiceErr_NoError;
1193 }
1194 
1195 DNSServiceErrorType DNSSD_API DNSServiceGetPID(const uint16_t srcport, int32_t *pid)
1196 {
1197     char *ptr;
1198     ipc_msg_hdr *hdr;
1199     DNSServiceOp *tmp;
1200     size_t len = sizeof(int32_t);
1201 
1202     DNSServiceErrorType err = ConnectToServer(&tmp, 0, getpid_request, NULL, NULL, NULL);
1203     if (err)
1204         return err;
1205 
1206     hdr = create_hdr(getpid_request, &len, &ptr, 0, tmp);
1207     if (!hdr)
1208     {
1209         DNSServiceRefDeallocate(tmp);
1210         return kDNSServiceErr_NoMemory;
1211     }
1212 
1213     put_uint16(srcport, &ptr);
1214     err = deliver_request(hdr, tmp);        // Will free hdr for us
1215 
1216     if (read_all(tmp->sockfd, (char*)pid, sizeof(int32_t)) < 0)
1217     {
1218         DNSServiceRefDeallocate(tmp);
1219         return kDNSServiceErr_ServiceNotRunning;
1220     }
1221 
1222     DNSServiceRefDeallocate(tmp);
1223     return kDNSServiceErr_NoError;
1224 }
1225 
1226 static void handle_resolve_response(DNSServiceOp *const sdr, const CallbackHeader *const cbh, const char *data, const char *end)
1227 {
1228     char fullname[kDNSServiceMaxDomainName];
1229     char target[kDNSServiceMaxDomainName];
1230     uint16_t txtlen;
1231     union { uint16_t s; u_char b[2]; } port;
1232     unsigned char *txtrecord;
1233 
1234     get_string(&data, end, fullname, kDNSServiceMaxDomainName);
1235     get_string(&data, end, target,   kDNSServiceMaxDomainName);
1236     if (!data || data + 2 > end) goto fail;
1237 
1238     port.b[0] = *data++;
1239     port.b[1] = *data++;
1240     txtlen = get_uint16(&data, end);
1241     txtrecord = (unsigned char *)get_rdata(&data, end, txtlen);
1242 
1243     if (!data) goto fail;
1244     ((DNSServiceResolveReply)sdr->AppCallback)(sdr, cbh->cb_flags, cbh->cb_interface, cbh->cb_err, fullname, target, port.s, txtlen, txtrecord, sdr->AppContext);
1245     return;
1246     // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1247 fail:
1248     syslog(LOG_WARNING, "dnssd_clientstub handle_resolve_response: error reading result from daemon");
1249 }
1250 
1251 #if TARGET_OS_EMBEDDED
1252 
1253 static int32_t libSystemVersion = 0;
1254 
1255 // Return true if the iOS application linked against a version of libsystem where P2P
1256 // interfaces were included by default when using kDNSServiceInterfaceIndexAny.
1257 // Using 160.0.0 == 0xa00000 as the version threshold.
1258 static int includeP2PWithIndexAny()
1259 {
1260     if (libSystemVersion == 0)
1261         libSystemVersion = NSVersionOfLinkTimeLibrary("System");
1262 
1263     if (libSystemVersion < 0xa00000)
1264         return 1;
1265     else
1266         return 0;
1267 }
1268 
1269 #else   // TARGET_OS_EMBEDDED
1270 
1271 // always return false for non iOS platforms
1272 static int includeP2PWithIndexAny()
1273 {
1274     return 0;
1275 }
1276 
1277 #endif  // TARGET_OS_EMBEDDED
1278 
1279 DNSServiceErrorType DNSSD_API DNSServiceResolve
1280 (
1281     DNSServiceRef                 *sdRef,
1282     DNSServiceFlags flags,
1283     uint32_t interfaceIndex,
1284     const char                    *name,
1285     const char                    *regtype,
1286     const char                    *domain,
1287     DNSServiceResolveReply callBack,
1288     void                          *context
1289 )
1290 {
1291     char *ptr;
1292     size_t len;
1293     ipc_msg_hdr *hdr;
1294     DNSServiceErrorType err;
1295 
1296     if (!name || !regtype || !domain || !callBack) return kDNSServiceErr_BadParam;
1297 
1298     // Need a real InterfaceID for WakeOnResolve
1299     if ((flags & kDNSServiceFlagsWakeOnResolve) != 0 &&
1300         ((interfaceIndex == kDNSServiceInterfaceIndexAny) ||
1301          (interfaceIndex == kDNSServiceInterfaceIndexLocalOnly) ||
1302          (interfaceIndex == kDNSServiceInterfaceIndexUnicast) ||
1303          (interfaceIndex == kDNSServiceInterfaceIndexP2P)))
1304     {
1305         return kDNSServiceErr_BadParam;
1306     }
1307 
1308     if ((interfaceIndex == kDNSServiceInterfaceIndexAny) && includeP2PWithIndexAny())
1309         flags |= kDNSServiceFlagsIncludeP2P;
1310 
1311     err = ConnectToServer(sdRef, flags, resolve_request, handle_resolve_response, (void *)callBack, context);
1312     if (err) return err;    // On error ConnectToServer leaves *sdRef set to NULL
1313 
1314     // Calculate total message length
1315     len = sizeof(flags);
1316     len += sizeof(interfaceIndex);
1317     len += strlen(name) + 1;
1318     len += strlen(regtype) + 1;
1319     len += strlen(domain) + 1;
1320 
1321     hdr = create_hdr(resolve_request, &len, &ptr, (*sdRef)->primary ? 1 : 0, *sdRef);
1322     if (!hdr) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; return kDNSServiceErr_NoMemory; }
1323 
1324     put_flags(flags, &ptr);
1325     put_uint32(interfaceIndex, &ptr);
1326     put_string(name, &ptr);
1327     put_string(regtype, &ptr);
1328     put_string(domain, &ptr);
1329 
1330     err = deliver_request(hdr, *sdRef);     // Will free hdr for us
1331     if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
1332     return err;
1333 }
1334 
1335 static void handle_query_response(DNSServiceOp *const sdr, const CallbackHeader *const cbh, const char *data, const char *const end)
1336 {
1337     uint32_t ttl;
1338     char name[kDNSServiceMaxDomainName];
1339     uint16_t rrtype, rrclass, rdlen;
1340     const char *rdata;
1341 
1342     get_string(&data, end, name, kDNSServiceMaxDomainName);
1343     rrtype  = get_uint16(&data, end);
1344     rrclass = get_uint16(&data, end);
1345     rdlen   = get_uint16(&data, end);
1346     rdata   = get_rdata(&data, end, rdlen);
1347     ttl     = get_uint32(&data, end);
1348 
1349     if (!data) syslog(LOG_WARNING, "dnssd_clientstub handle_query_response: error reading result from daemon");
1350     else ((DNSServiceQueryRecordReply)sdr->AppCallback)(sdr, cbh->cb_flags, cbh->cb_interface, cbh->cb_err, name, rrtype, rrclass, rdlen, rdata, ttl, sdr->AppContext);
1351     // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1352 }
1353 
1354 DNSServiceErrorType DNSSD_API DNSServiceQueryRecord
1355 (
1356     DNSServiceRef              *sdRef,
1357     DNSServiceFlags flags,
1358     uint32_t interfaceIndex,
1359     const char                 *name,
1360     uint16_t rrtype,
1361     uint16_t rrclass,
1362     DNSServiceQueryRecordReply callBack,
1363     void                       *context
1364 )
1365 {
1366     char *ptr;
1367     size_t len;
1368     ipc_msg_hdr *hdr;
1369     DNSServiceErrorType err;
1370 
1371     if ((interfaceIndex == kDNSServiceInterfaceIndexAny) && includeP2PWithIndexAny())
1372         flags |= kDNSServiceFlagsIncludeP2P;
1373 
1374     err = ConnectToServer(sdRef, flags, query_request, handle_query_response, (void *)callBack, context);
1375     if (err) return err;    // On error ConnectToServer leaves *sdRef set to NULL
1376 
1377     if (!name) name = "\0";
1378 
1379     // Calculate total message length
1380     len = sizeof(flags);
1381     len += sizeof(uint32_t);  // interfaceIndex
1382     len += strlen(name) + 1;
1383     len += 2 * sizeof(uint16_t);  // rrtype, rrclass
1384 
1385     hdr = create_hdr(query_request, &len, &ptr, (*sdRef)->primary ? 1 : 0, *sdRef);
1386     if (!hdr) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; return kDNSServiceErr_NoMemory; }
1387 
1388     put_flags(flags, &ptr);
1389     put_uint32(interfaceIndex, &ptr);
1390     put_string(name, &ptr);
1391     put_uint16(rrtype, &ptr);
1392     put_uint16(rrclass, &ptr);
1393 
1394     err = deliver_request(hdr, *sdRef);     // Will free hdr for us
1395     if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
1396     return err;
1397 }
1398 
1399 static void handle_addrinfo_response(DNSServiceOp *const sdr, const CallbackHeader *const cbh, const char *data, const char *const end)
1400 {
1401     char hostname[kDNSServiceMaxDomainName];
1402     uint16_t rrtype, rdlen;
1403     const char *rdata;
1404     uint32_t ttl;
1405 
1406     get_string(&data, end, hostname, kDNSServiceMaxDomainName);
1407     rrtype  = get_uint16(&data, end);
1408     (void) get_uint16(&data, end);  /* class is not used */
1409     rdlen   = get_uint16(&data, end);
1410     rdata   = get_rdata (&data, end, rdlen);
1411     ttl     = get_uint32(&data, end);
1412 
1413     // We only generate client callbacks for A and AAAA results (including NXDOMAIN results for
1414     // those types, if the client has requested those with the kDNSServiceFlagsReturnIntermediates).
1415     // Other result types, specifically CNAME referrals, are not communicated to the client, because
1416     // the DNSServiceGetAddrInfoReply interface doesn't have any meaningful way to communiate CNAME referrals.
1417     if (!data) syslog(LOG_WARNING, "dnssd_clientstub handle_addrinfo_response: error reading result from daemon");
1418     else if (rrtype == kDNSServiceType_A || rrtype == kDNSServiceType_AAAA)
1419     {
1420         struct sockaddr_in sa4;
1421         struct sockaddr_in6 sa6;
1422         const struct sockaddr *const sa = (rrtype == kDNSServiceType_A) ? (struct sockaddr*)&sa4 : (struct sockaddr*)&sa6;
1423         if (rrtype == kDNSServiceType_A)
1424         {
1425             memset(&sa4, 0, sizeof(sa4));
1426             #ifndef NOT_HAVE_SA_LEN
1427             sa4.sin_len = sizeof(struct sockaddr_in);
1428             #endif
1429             sa4.sin_family = AF_INET;
1430             //  sin_port   = 0;
1431             if (!cbh->cb_err) memcpy(&sa4.sin_addr, rdata, rdlen);
1432         }
1433         else
1434         {
1435             memset(&sa6, 0, sizeof(sa6));
1436             #ifndef NOT_HAVE_SA_LEN
1437             sa6.sin6_len = sizeof(struct sockaddr_in6);
1438             #endif
1439             sa6.sin6_family     = AF_INET6;
1440             //  sin6_port     = 0;
1441             //  sin6_flowinfo = 0;
1442             //  sin6_scope_id = 0;
1443             if (!cbh->cb_err)
1444             {
1445                 memcpy(&sa6.sin6_addr, rdata, rdlen);
1446                 if (IN6_IS_ADDR_LINKLOCAL(&sa6.sin6_addr)) sa6.sin6_scope_id = cbh->cb_interface;
1447             }
1448         }
1449         // Validation results are always delivered separately from the actual results of the
1450         // DNSServiceGetAddrInfo. Set the "addr" to NULL as per the documentation.
1451         //
1452         // Note: If we deliver validation results along with the "addr" in the future, we need
1453         // a way to differentiate the negative response from validation-only response as both
1454         // has zero address.
1455         if (!(cbh->cb_flags & kDNSServiceFlagsValidate))
1456             ((DNSServiceGetAddrInfoReply)sdr->AppCallback)(sdr, cbh->cb_flags, cbh->cb_interface, cbh->cb_err, hostname, sa, ttl, sdr->AppContext);
1457         else
1458             ((DNSServiceGetAddrInfoReply)sdr->AppCallback)(sdr, cbh->cb_flags, cbh->cb_interface, cbh->cb_err, hostname, NULL, 0, sdr->AppContext);
1459         // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1460     }
1461 }
1462 
1463 DNSServiceErrorType DNSSD_API DNSServiceGetAddrInfo
1464 (
1465     DNSServiceRef                    *sdRef,
1466     DNSServiceFlags flags,
1467     uint32_t interfaceIndex,
1468     uint32_t protocol,
1469     const char                       *hostname,
1470     DNSServiceGetAddrInfoReply callBack,
1471     void                             *context          /* may be NULL */
1472 )
1473 {
1474     char *ptr;
1475     size_t len;
1476     ipc_msg_hdr *hdr;
1477     DNSServiceErrorType err;
1478 
1479     if (!hostname) return kDNSServiceErr_BadParam;
1480 
1481     err = ConnectToServer(sdRef, flags, addrinfo_request, handle_addrinfo_response, (void *)callBack, context);
1482     if (err)
1483     {
1484          return err;    // On error ConnectToServer leaves *sdRef set to NULL
1485     }
1486 
1487     // Calculate total message length
1488     len = sizeof(flags);
1489     len += sizeof(uint32_t);      // interfaceIndex
1490     len += sizeof(uint32_t);      // protocol
1491     len += strlen(hostname) + 1;
1492 
1493     hdr = create_hdr(addrinfo_request, &len, &ptr, (*sdRef)->primary ? 1 : 0, *sdRef);
1494     if (!hdr) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; return kDNSServiceErr_NoMemory; }
1495 
1496     put_flags(flags, &ptr);
1497     put_uint32(interfaceIndex, &ptr);
1498     put_uint32(protocol, &ptr);
1499     put_string(hostname, &ptr);
1500 
1501     err = deliver_request(hdr, *sdRef);     // Will free hdr for us
1502     if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
1503     return err;
1504 }
1505 
1506 static void handle_browse_response(DNSServiceOp *const sdr, const CallbackHeader *const cbh, const char *data, const char *const end)
1507 {
1508     char replyName[256], replyType[kDNSServiceMaxDomainName], replyDomain[kDNSServiceMaxDomainName];
1509     get_string(&data, end, replyName, 256);
1510     get_string(&data, end, replyType, kDNSServiceMaxDomainName);
1511     get_string(&data, end, replyDomain, kDNSServiceMaxDomainName);
1512     if (!data) syslog(LOG_WARNING, "dnssd_clientstub handle_browse_response: error reading result from daemon");
1513     else ((DNSServiceBrowseReply)sdr->AppCallback)(sdr, cbh->cb_flags, cbh->cb_interface, cbh->cb_err, replyName, replyType, replyDomain, sdr->AppContext);
1514     // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1515 }
1516 
1517 DNSServiceErrorType DNSSD_API DNSServiceBrowse
1518 (
1519     DNSServiceRef         *sdRef,
1520     DNSServiceFlags flags,
1521     uint32_t interfaceIndex,
1522     const char            *regtype,
1523     const char            *domain,
1524     DNSServiceBrowseReply callBack,
1525     void                  *context
1526 )
1527 {
1528     char *ptr;
1529     size_t len;
1530     ipc_msg_hdr *hdr;
1531     DNSServiceErrorType err;
1532 
1533     if ((interfaceIndex == kDNSServiceInterfaceIndexAny) && includeP2PWithIndexAny())
1534         flags |= kDNSServiceFlagsIncludeP2P;
1535 
1536     err = ConnectToServer(sdRef, flags, browse_request, handle_browse_response, (void *)callBack, context);
1537     if (err) return err;    // On error ConnectToServer leaves *sdRef set to NULL
1538 
1539     if (!domain) domain = "";
1540     len = sizeof(flags);
1541     len += sizeof(interfaceIndex);
1542     len += strlen(regtype) + 1;
1543     len += strlen(domain) + 1;
1544 
1545     hdr = create_hdr(browse_request, &len, &ptr, (*sdRef)->primary ? 1 : 0, *sdRef);
1546     if (!hdr) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; return kDNSServiceErr_NoMemory; }
1547 
1548     put_flags(flags, &ptr);
1549     put_uint32(interfaceIndex, &ptr);
1550     put_string(regtype, &ptr);
1551     put_string(domain, &ptr);
1552 
1553     err = deliver_request(hdr, *sdRef);     // Will free hdr for us
1554     if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
1555     return err;
1556 }
1557 
1558 DNSServiceErrorType DNSSD_API DNSServiceSetDefaultDomainForUser(DNSServiceFlags flags, const char *domain);
1559 DNSServiceErrorType DNSSD_API DNSServiceSetDefaultDomainForUser(DNSServiceFlags flags, const char *domain)
1560 {
1561     DNSServiceOp *tmp;
1562     char *ptr;
1563     size_t len = sizeof(flags) + strlen(domain) + 1;
1564     ipc_msg_hdr *hdr;
1565     DNSServiceErrorType err = ConnectToServer(&tmp, 0, setdomain_request, NULL, NULL, NULL);
1566     if (err) return err;
1567 
1568     hdr = create_hdr(setdomain_request, &len, &ptr, 0, tmp);
1569     if (!hdr) { DNSServiceRefDeallocate(tmp); return kDNSServiceErr_NoMemory; }
1570 
1571     put_flags(flags, &ptr);
1572     put_string(domain, &ptr);
1573     err = deliver_request(hdr, tmp);        // Will free hdr for us
1574     DNSServiceRefDeallocate(tmp);
1575     return err;
1576 }
1577 
1578 static void handle_regservice_response(DNSServiceOp *const sdr, const CallbackHeader *const cbh, const char *data, const char *const end)
1579 {
1580     char name[256], regtype[kDNSServiceMaxDomainName], domain[kDNSServiceMaxDomainName];
1581     get_string(&data, end, name, 256);
1582     get_string(&data, end, regtype, kDNSServiceMaxDomainName);
1583     get_string(&data, end, domain,  kDNSServiceMaxDomainName);
1584     if (!data) syslog(LOG_WARNING, "dnssd_clientstub handle_regservice_response: error reading result from daemon");
1585     else ((DNSServiceRegisterReply)sdr->AppCallback)(sdr, cbh->cb_flags, cbh->cb_err, name, regtype, domain, sdr->AppContext);
1586     // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1587 }
1588 
1589 DNSServiceErrorType DNSSD_API DNSServiceRegister
1590 (
1591     DNSServiceRef                       *sdRef,
1592     DNSServiceFlags flags,
1593     uint32_t interfaceIndex,
1594     const char                          *name,
1595     const char                          *regtype,
1596     const char                          *domain,
1597     const char                          *host,
1598     uint16_t PortInNetworkByteOrder,
1599     uint16_t txtLen,
1600     const void                          *txtRecord,
1601     DNSServiceRegisterReply callBack,
1602     void                                *context
1603 )
1604 {
1605     char *ptr;
1606     size_t len;
1607     ipc_msg_hdr *hdr;
1608     DNSServiceErrorType err;
1609     union { uint16_t s; u_char b[2]; } port = { PortInNetworkByteOrder };
1610 
1611     if (!name) name = "";
1612     if (!regtype) return kDNSServiceErr_BadParam;
1613     if (!domain) domain = "";
1614     if (!host) host = "";
1615     if (!txtRecord) txtRecord = (void*)"";
1616 
1617     // No callback must have auto-rename
1618     if (!callBack && (flags & kDNSServiceFlagsNoAutoRename)) return kDNSServiceErr_BadParam;
1619 
1620     if ((interfaceIndex == kDNSServiceInterfaceIndexAny) && includeP2PWithIndexAny())
1621         flags |= kDNSServiceFlagsIncludeP2P;
1622 
1623     err = ConnectToServer(sdRef, flags, reg_service_request, callBack ? handle_regservice_response : NULL, (void *)callBack, context);
1624     if (err) return err;    // On error ConnectToServer leaves *sdRef set to NULL
1625 
1626     len = sizeof(DNSServiceFlags);
1627     len += sizeof(uint32_t);  // interfaceIndex
1628     len += strlen(name) + strlen(regtype) + strlen(domain) + strlen(host) + 4;
1629     len += 2 * sizeof(uint16_t);  // port, txtLen
1630     len += txtLen;
1631 
1632     hdr = create_hdr(reg_service_request, &len, &ptr, (*sdRef)->primary ? 1 : 0, *sdRef);
1633     if (!hdr) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; return kDNSServiceErr_NoMemory; }
1634 
1635     // If it is going over a shared connection, then don't set the IPC_FLAGS_NOREPLY
1636     // as it affects all the operations over the shared connection. This is not
1637     // a normal case and hence receiving the response back from the daemon and
1638     // discarding it in ConnectionResponse is okay.
1639 
1640     if (!(flags & kDNSServiceFlagsShareConnection) && !callBack) hdr->ipc_flags |= IPC_FLAGS_NOREPLY;
1641 
1642     put_flags(flags, &ptr);
1643     put_uint32(interfaceIndex, &ptr);
1644     put_string(name, &ptr);
1645     put_string(regtype, &ptr);
1646     put_string(domain, &ptr);
1647     put_string(host, &ptr);
1648     *ptr++ = port.b[0];
1649     *ptr++ = port.b[1];
1650     put_uint16(txtLen, &ptr);
1651     put_rdata(txtLen, txtRecord, &ptr);
1652 
1653     err = deliver_request(hdr, *sdRef);     // Will free hdr for us
1654     if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
1655     return err;
1656 }
1657 
1658 static void handle_enumeration_response(DNSServiceOp *const sdr, const CallbackHeader *const cbh, const char *data, const char *const end)
1659 {
1660     char domain[kDNSServiceMaxDomainName];
1661     get_string(&data, end, domain, kDNSServiceMaxDomainName);
1662     if (!data) syslog(LOG_WARNING, "dnssd_clientstub handle_enumeration_response: error reading result from daemon");
1663     else ((DNSServiceDomainEnumReply)sdr->AppCallback)(sdr, cbh->cb_flags, cbh->cb_interface, cbh->cb_err, domain, sdr->AppContext);
1664     // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1665 }
1666 
1667 DNSServiceErrorType DNSSD_API DNSServiceEnumerateDomains
1668 (
1669     DNSServiceRef             *sdRef,
1670     DNSServiceFlags flags,
1671     uint32_t interfaceIndex,
1672     DNSServiceDomainEnumReply callBack,
1673     void                      *context
1674 )
1675 {
1676     char *ptr;
1677     size_t len;
1678     ipc_msg_hdr *hdr;
1679     DNSServiceErrorType err;
1680 
1681     int f1 = (flags & kDNSServiceFlagsBrowseDomains) != 0;
1682     int f2 = (flags & kDNSServiceFlagsRegistrationDomains) != 0;
1683     if (f1 + f2 != 1) return kDNSServiceErr_BadParam;
1684 
1685     err = ConnectToServer(sdRef, flags, enumeration_request, handle_enumeration_response, (void *)callBack, context);
1686     if (err) return err;    // On error ConnectToServer leaves *sdRef set to NULL
1687 
1688     len = sizeof(DNSServiceFlags);
1689     len += sizeof(uint32_t);
1690 
1691     hdr = create_hdr(enumeration_request, &len, &ptr, (*sdRef)->primary ? 1 : 0, *sdRef);
1692     if (!hdr) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; return kDNSServiceErr_NoMemory; }
1693 
1694     put_flags(flags, &ptr);
1695     put_uint32(interfaceIndex, &ptr);
1696 
1697     err = deliver_request(hdr, *sdRef);     // Will free hdr for us
1698     if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
1699     return err;
1700 }
1701 
1702 static void ConnectionResponse(DNSServiceOp *const sdr, const CallbackHeader *const cbh, const char *const data, const char *const end)
1703 {
1704     (void)data; // Unused
1705 
1706     //printf("ConnectionResponse got %d\n", cbh->ipc_hdr.op);
1707     if (cbh->ipc_hdr.op != reg_record_reply_op)
1708     {
1709         // When using kDNSServiceFlagsShareConnection, need to search the list of associated DNSServiceOps
1710         // to find the one this response is intended for, and then call through to its ProcessReply handler.
1711         // We start with our first subordinate DNSServiceRef -- don't want to accidentally match the parent DNSServiceRef.
1712         DNSServiceOp *op = sdr->next;
1713         while (op && (op->uid.u32[0] != cbh->ipc_hdr.client_context.u32[0] || op->uid.u32[1] != cbh->ipc_hdr.client_context.u32[1]))
1714             op = op->next;
1715         // Note: We may sometimes not find a matching DNSServiceOp, in the case where the client has
1716         // cancelled the subordinate DNSServiceOp, but there are still messages in the pipeline from the daemon
1717         if (op && op->ProcessReply) op->ProcessReply(op, cbh, data, end);
1718         // WARNING: Don't touch op or sdr after this -- client may have called DNSServiceRefDeallocate
1719         return;
1720     }
1721     else
1722     {
1723         DNSRecordRef rec;
1724         for (rec = sdr->rec; rec; rec = rec->recnext)
1725         {
1726             if (rec->uid.u32[0] == cbh->ipc_hdr.client_context.u32[0] && rec->uid.u32[1] == cbh->ipc_hdr.client_context.u32[1])
1727                 break;
1728         }
1729         // The record might have been freed already and hence not an
1730         // error if the record is not found.
1731         if (!rec)
1732         {
1733             syslog(LOG_INFO, "ConnectionResponse: Record not found");
1734             return;
1735         }
1736         if (rec->sdr != sdr)
1737         {
1738             syslog(LOG_WARNING, "ConnectionResponse: Record sdr mismatch: rec %p sdr %p", rec->sdr, sdr);
1739             return;
1740         }
1741 
1742         if (sdr->op == connection_request || sdr->op == connection_delegate_request)
1743         {
1744             rec->AppCallback(rec->sdr, rec, cbh->cb_flags, cbh->cb_err, rec->AppContext);
1745         }
1746         else
1747         {
1748             syslog(LOG_WARNING, "dnssd_clientstub ConnectionResponse: sdr->op != connection_request");
1749             rec->AppCallback(rec->sdr, rec, 0, kDNSServiceErr_Unknown, rec->AppContext);
1750         }
1751         // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1752     }
1753 }
1754 
1755 DNSServiceErrorType DNSSD_API DNSServiceCreateConnection(DNSServiceRef *sdRef)
1756 {
1757     char *ptr;
1758     size_t len = 0;
1759     ipc_msg_hdr *hdr;
1760     DNSServiceErrorType err = ConnectToServer(sdRef, 0, connection_request, ConnectionResponse, NULL, NULL);
1761     if (err) return err;    // On error ConnectToServer leaves *sdRef set to NULL
1762 
1763     hdr = create_hdr(connection_request, &len, &ptr, 0, *sdRef);
1764     if (!hdr) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; return kDNSServiceErr_NoMemory; }
1765 
1766     err = deliver_request(hdr, *sdRef);     // Will free hdr for us
1767     if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
1768     return err;
1769 }
1770 
1771 #if APPLE_OSX_mDNSResponder && !TARGET_IPHONE_SIMULATOR
1772 DNSServiceErrorType DNSSD_API DNSServiceCreateDelegateConnection(DNSServiceRef *sdRef, int32_t pid, uuid_t uuid)
1773 {
1774     char *ptr;
1775     size_t len = 0;
1776     ipc_msg_hdr *hdr;
1777 
1778     DNSServiceErrorType err = ConnectToServer(sdRef, 0, connection_delegate_request, ConnectionResponse, NULL, NULL);
1779     if (err)
1780     {
1781          return err;    // On error ConnectToServer leaves *sdRef set to NULL
1782     }
1783 
1784     // Only one of the two options can be set. If pid is zero, uuid is used. 
1785     // If both are specified only pid will be used. We send across the pid
1786     // so that the daemon knows what to read from the socket.
1787 
1788     len += sizeof(int32_t);
1789 
1790     hdr = create_hdr(connection_delegate_request, &len, &ptr, 0, *sdRef);
1791     if (!hdr)
1792     {
1793         DNSServiceRefDeallocate(*sdRef);
1794         *sdRef = NULL;
1795         return kDNSServiceErr_NoMemory;
1796     }
1797 
1798     if (pid && setsockopt((*sdRef)->sockfd, SOL_SOCKET, SO_DELEGATED, &pid, sizeof(pid)) == -1)
1799     { 
1800         syslog(LOG_WARNING, "dnssdclientstub: Could not setsockopt() for PID[%d], no entitlements or process(pid) invalid errno:%d (%s)", pid, errno, strerror(errno)); 
1801         // Free the hdr in case we return before calling deliver_request() 
1802         if (hdr)
1803             free(hdr);
1804         DNSServiceRefDeallocate(*sdRef);
1805         *sdRef = NULL;
1806         return kDNSServiceErr_NoAuth;
1807     }
1808 
1809     if (!pid && setsockopt((*sdRef)->sockfd, SOL_SOCKET, SO_DELEGATED_UUID, uuid, sizeof(uuid_t)) == -1)
1810     {
1811         syslog(LOG_WARNING, "dnssdclientstub: Could not setsockopt() for UUID, no entitlements or process(uuid) invalid errno:%d (%s) ", errno, strerror(errno));
1812         // Free the hdr in case we return before calling deliver_request()
1813         if (hdr)
1814             free(hdr);
1815         DNSServiceRefDeallocate(*sdRef);
1816         *sdRef = NULL;
1817         return kDNSServiceErr_NoAuth;
1818     }
1819 
1820     put_uint32(pid, &ptr);
1821 
1822     err = deliver_request(hdr, *sdRef);     // Will free hdr for us
1823     if (err)
1824     {
1825         DNSServiceRefDeallocate(*sdRef);
1826         *sdRef = NULL;
1827     }
1828     return err;
1829 }
1830 #elif TARGET_IPHONE_SIMULATOR // This hack is for Simulator platform only
1831 DNSServiceErrorType DNSSD_API DNSServiceCreateDelegateConnection(DNSServiceRef *sdRef, int32_t pid, uuid_t uuid)
1832 {
1833     (void) pid;
1834     (void) uuid;
1835     return DNSServiceCreateConnection(sdRef);
1836 }
1837 #endif
1838 
1839 DNSServiceErrorType DNSSD_API DNSServiceRegisterRecord
1840 (
1841     DNSServiceRef sdRef,
1842     DNSRecordRef                  *RecordRef,
1843     DNSServiceFlags flags,
1844     uint32_t interfaceIndex,
1845     const char                    *fullname,
1846     uint16_t rrtype,
1847     uint16_t rrclass,
1848     uint16_t rdlen,
1849     const void                    *rdata,
1850     uint32_t ttl,
1851     DNSServiceRegisterRecordReply callBack,
1852     void                          *context
1853 )
1854 {
1855     char *ptr;
1856     size_t len;
1857     ipc_msg_hdr *hdr = NULL;
1858     DNSRecordRef rref = NULL;
1859     DNSRecord **p;
1860     int f1 = (flags & kDNSServiceFlagsShared) != 0;
1861     int f2 = (flags & kDNSServiceFlagsUnique) != 0;
1862     if (f1 + f2 != 1) return kDNSServiceErr_BadParam;
1863 
1864     if ((interfaceIndex == kDNSServiceInterfaceIndexAny) && includeP2PWithIndexAny())
1865         flags |= kDNSServiceFlagsIncludeP2P;
1866 
1867     if (!sdRef) { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRegisterRecord called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam; }
1868 
1869     if (!DNSServiceRefValid(sdRef))
1870     {
1871         syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRegisterRecord called with invalid DNSServiceRef %p %08X %08X", sdRef, sdRef->sockfd, sdRef->validator);
1872         return kDNSServiceErr_BadReference;
1873     }
1874 
1875     if (sdRef->op != connection_request && sdRef->op != connection_delegate_request)
1876     {
1877         syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRegisterRecord called with non-DNSServiceCreateConnection DNSServiceRef %p %d", sdRef, sdRef->op);
1878         return kDNSServiceErr_BadReference;
1879     }
1880 
1881     *RecordRef = NULL;
1882 
1883     len = sizeof(DNSServiceFlags);
1884     len += 2 * sizeof(uint32_t);  // interfaceIndex, ttl
1885     len += 3 * sizeof(uint16_t);  // rrtype, rrclass, rdlen
1886     len += strlen(fullname) + 1;
1887     len += rdlen;
1888 
1889     // Bump up the uid. Normally for shared operations (kDNSServiceFlagsShareConnection), this
1890     // is done in ConnectToServer. For DNSServiceRegisterRecord, ConnectToServer has already
1891     // been called. As multiple DNSServiceRegisterRecords can be multiplexed over a single
1892     // connection, we need a way to demultiplex the response so that the callback corresponding
1893     // to the right DNSServiceRegisterRecord instance can be called. Use the same mechanism that
1894     // is used by kDNSServiceFlagsShareConnection. create_hdr copies the uid value to ipc
1895     // hdr->client_context which will be returned in the ipc response.
1896     if (++sdRef->uid.u32[0] == 0)
1897         ++sdRef->uid.u32[1];
1898     hdr = create_hdr(reg_record_request, &len, &ptr, 1, sdRef);
1899     if (!hdr) return kDNSServiceErr_NoMemory;
1900 
1901     put_flags(flags, &ptr);
1902     put_uint32(interfaceIndex, &ptr);
1903     put_string(fullname, &ptr);
1904     put_uint16(rrtype, &ptr);
1905     put_uint16(rrclass, &ptr);
1906     put_uint16(rdlen, &ptr);
1907     put_rdata(rdlen, rdata, &ptr);
1908     put_uint32(ttl, &ptr);
1909 
1910     rref = malloc(sizeof(DNSRecord));
1911     if (!rref) { free(hdr); return kDNSServiceErr_NoMemory; }
1912     rref->AppContext = context;
1913     rref->AppCallback = callBack;
1914     rref->record_index = sdRef->max_index++;
1915     rref->sdr = sdRef;
1916     rref->recnext = NULL;
1917     *RecordRef = rref;
1918     // Remember the uid that we are sending across so that we can match
1919     // when the response comes back.
1920     rref->uid = sdRef->uid;
1921     hdr->reg_index = rref->record_index;
1922 
1923     p = &(sdRef)->rec;
1924     while (*p) p = &(*p)->recnext;
1925     *p = rref;
1926 
1927     return deliver_request(hdr, sdRef);     // Will free hdr for us
1928 }
1929 
1930 // sdRef returned by DNSServiceRegister()
1931 DNSServiceErrorType DNSSD_API DNSServiceAddRecord
1932 (
1933     DNSServiceRef sdRef,
1934     DNSRecordRef    *RecordRef,
1935     DNSServiceFlags flags,
1936     uint16_t rrtype,
1937     uint16_t rdlen,
1938     const void      *rdata,
1939     uint32_t ttl
1940 )
1941 {
1942     ipc_msg_hdr *hdr;
1943     size_t len = 0;
1944     char *ptr;
1945     DNSRecordRef rref;
1946     DNSRecord **p;
1947 
1948     if (!sdRef)     { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceAddRecord called with NULL DNSServiceRef");        return kDNSServiceErr_BadParam; }
1949     if (!RecordRef) { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceAddRecord called with NULL DNSRecordRef pointer"); return kDNSServiceErr_BadParam; }
1950     if (sdRef->op != reg_service_request)
1951     {
1952         syslog(LOG_WARNING, "dnssd_clientstub DNSServiceAddRecord called with non-DNSServiceRegister DNSServiceRef %p %d", sdRef, sdRef->op);
1953         return kDNSServiceErr_BadReference;
1954     }
1955 
1956     if (!DNSServiceRefValid(sdRef))
1957     {
1958         syslog(LOG_WARNING, "dnssd_clientstub DNSServiceAddRecord called with invalid DNSServiceRef %p %08X %08X", sdRef, sdRef->sockfd, sdRef->validator);
1959         return kDNSServiceErr_BadReference;
1960     }
1961 
1962     *RecordRef = NULL;
1963 
1964     len += 2 * sizeof(uint16_t);  // rrtype, rdlen
1965     len += rdlen;
1966     len += sizeof(uint32_t);
1967     len += sizeof(DNSServiceFlags);
1968 
1969     hdr = create_hdr(add_record_request, &len, &ptr, 1, sdRef);
1970     if (!hdr) return kDNSServiceErr_NoMemory;
1971     put_flags(flags, &ptr);
1972     put_uint16(rrtype, &ptr);
1973     put_uint16(rdlen, &ptr);
1974     put_rdata(rdlen, rdata, &ptr);
1975     put_uint32(ttl, &ptr);
1976 
1977     rref = malloc(sizeof(DNSRecord));
1978     if (!rref) { free(hdr); return kDNSServiceErr_NoMemory; }
1979     rref->AppContext = NULL;
1980     rref->AppCallback = NULL;
1981     rref->record_index = sdRef->max_index++;
1982     rref->sdr = sdRef;
1983     rref->recnext = NULL;
1984     *RecordRef = rref;
1985     hdr->reg_index = rref->record_index;
1986 
1987     p = &(sdRef)->rec;
1988     while (*p) p = &(*p)->recnext;
1989     *p = rref;
1990 
1991     return deliver_request(hdr, sdRef);     // Will free hdr for us
1992 }
1993 
1994 // DNSRecordRef returned by DNSServiceRegisterRecord or DNSServiceAddRecord
1995 DNSServiceErrorType DNSSD_API DNSServiceUpdateRecord
1996 (
1997     DNSServiceRef sdRef,
1998     DNSRecordRef RecordRef,
1999     DNSServiceFlags flags,
2000     uint16_t rdlen,
2001     const void      *rdata,
2002     uint32_t ttl
2003 )
2004 {
2005     ipc_msg_hdr *hdr;
2006     size_t len = 0;
2007     char *ptr;
2008 
2009     if (!sdRef) { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceUpdateRecord called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam; }
2010 
2011     if (!DNSServiceRefValid(sdRef))
2012     {
2013         syslog(LOG_WARNING, "dnssd_clientstub DNSServiceUpdateRecord called with invalid DNSServiceRef %p %08X %08X", sdRef, sdRef->sockfd, sdRef->validator);
2014         return kDNSServiceErr_BadReference;
2015     }
2016 
2017     // Note: RecordRef is allowed to be NULL
2018 
2019     len += sizeof(uint16_t);
2020     len += rdlen;
2021     len += sizeof(uint32_t);
2022     len += sizeof(DNSServiceFlags);
2023 
2024     hdr = create_hdr(update_record_request, &len, &ptr, 1, sdRef);
2025     if (!hdr) return kDNSServiceErr_NoMemory;
2026     hdr->reg_index = RecordRef ? RecordRef->record_index : TXT_RECORD_INDEX;
2027     put_flags(flags, &ptr);
2028     put_uint16(rdlen, &ptr);
2029     put_rdata(rdlen, rdata, &ptr);
2030     put_uint32(ttl, &ptr);
2031     return deliver_request(hdr, sdRef);     // Will free hdr for us
2032 }
2033 
2034 DNSServiceErrorType DNSSD_API DNSServiceRemoveRecord
2035 (
2036     DNSServiceRef sdRef,
2037     DNSRecordRef RecordRef,
2038     DNSServiceFlags flags
2039 )
2040 {
2041     ipc_msg_hdr *hdr;
2042     size_t len = 0;
2043     char *ptr;
2044     DNSServiceErrorType err;
2045 
2046     if (!sdRef)            { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRemoveRecord called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam; }
2047     if (!RecordRef)        { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRemoveRecord called with NULL DNSRecordRef");  return kDNSServiceErr_BadParam; }
2048     if (!sdRef->max_index) { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRemoveRecord called with bad DNSServiceRef");  return kDNSServiceErr_BadReference; }
2049 
2050     if (!DNSServiceRefValid(sdRef))
2051     {
2052         syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRemoveRecord called with invalid DNSServiceRef %p %08X %08X", sdRef, sdRef->sockfd, sdRef->validator);
2053         return kDNSServiceErr_BadReference;
2054     }
2055 
2056     len += sizeof(flags);
2057     hdr = create_hdr(remove_record_request, &len, &ptr, 1, sdRef);
2058     if (!hdr) return kDNSServiceErr_NoMemory;
2059     hdr->reg_index = RecordRef->record_index;
2060     put_flags(flags, &ptr);
2061     err = deliver_request(hdr, sdRef);      // Will free hdr for us
2062     if (!err)
2063     {
2064         // This RecordRef could have been allocated in DNSServiceRegisterRecord or DNSServiceAddRecord.
2065         // If so, delink from the list before freeing
2066         DNSRecord **p = &sdRef->rec;
2067         while (*p && *p != RecordRef) p = &(*p)->recnext;
2068         if (*p) *p = RecordRef->recnext;
2069         free(RecordRef);
2070     }
2071     return err;
2072 }
2073 
2074 DNSServiceErrorType DNSSD_API DNSServiceReconfirmRecord
2075 (
2076     DNSServiceFlags flags,
2077     uint32_t interfaceIndex,
2078     const char      *fullname,
2079     uint16_t rrtype,
2080     uint16_t rrclass,
2081     uint16_t rdlen,
2082     const void      *rdata
2083 )
2084 {
2085     char *ptr;
2086     size_t len;
2087     ipc_msg_hdr *hdr;
2088     DNSServiceOp *tmp;
2089 
2090     DNSServiceErrorType err = ConnectToServer(&tmp, flags, reconfirm_record_request, NULL, NULL, NULL);
2091     if (err) return err;
2092 
2093     len = sizeof(DNSServiceFlags);
2094     len += sizeof(uint32_t);
2095     len += strlen(fullname) + 1;
2096     len += 3 * sizeof(uint16_t);
2097     len += rdlen;
2098     hdr = create_hdr(reconfirm_record_request, &len, &ptr, 0, tmp);
2099     if (!hdr) { DNSServiceRefDeallocate(tmp); return kDNSServiceErr_NoMemory; }
2100 
2101     put_flags(flags, &ptr);
2102     put_uint32(interfaceIndex, &ptr);
2103     put_string(fullname, &ptr);
2104     put_uint16(rrtype, &ptr);
2105     put_uint16(rrclass, &ptr);
2106     put_uint16(rdlen, &ptr);
2107     put_rdata(rdlen, rdata, &ptr);
2108 
2109     err = deliver_request(hdr, tmp);        // Will free hdr for us
2110     DNSServiceRefDeallocate(tmp);
2111     return err;
2112 }
2113 
2114 
2115 static void handle_port_mapping_response(DNSServiceOp *const sdr, const CallbackHeader *const cbh, const char *data, const char *const end)
2116 {
2117     union { uint32_t l; u_char b[4]; } addr;
2118     uint8_t protocol;
2119     union { uint16_t s; u_char b[2]; } internalPort;
2120     union { uint16_t s; u_char b[2]; } externalPort;
2121     uint32_t ttl;
2122 
2123     if (!data || data + 13 > end) goto fail;
2124 
2125     addr.b[0] = *data++;
2126     addr.b[1] = *data++;
2127     addr.b[2] = *data++;
2128     addr.b[3] = *data++;
2129     protocol          = *data++;
2130     internalPort.b[0] = *data++;
2131     internalPort.b[1] = *data++;
2132     externalPort.b[0] = *data++;
2133     externalPort.b[1] = *data++;
2134     ttl               = get_uint32(&data, end);
2135     if (!data) goto fail;
2136 
2137     ((DNSServiceNATPortMappingReply)sdr->AppCallback)(sdr, cbh->cb_flags, cbh->cb_interface, cbh->cb_err, addr.l, protocol, internalPort.s, externalPort.s, ttl, sdr->AppContext);
2138     return;
2139     // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
2140 
2141     fail :
2142     syslog(LOG_WARNING, "dnssd_clientstub handle_port_mapping_response: error reading result from daemon");
2143 }
2144 
2145 DNSServiceErrorType DNSSD_API DNSServiceNATPortMappingCreate
2146 (
2147     DNSServiceRef                       *sdRef,
2148     DNSServiceFlags flags,
2149     uint32_t interfaceIndex,
2150     uint32_t protocol,                                /* TCP and/or UDP */
2151     uint16_t internalPortInNetworkByteOrder,
2152     uint16_t externalPortInNetworkByteOrder,
2153     uint32_t ttl,                                     /* time to live in seconds */
2154     DNSServiceNATPortMappingReply callBack,
2155     void                                *context      /* may be NULL */
2156 )
2157 {
2158     char *ptr;
2159     size_t len;
2160     ipc_msg_hdr *hdr;
2161     union { uint16_t s; u_char b[2]; } internalPort = { internalPortInNetworkByteOrder };
2162     union { uint16_t s; u_char b[2]; } externalPort = { externalPortInNetworkByteOrder };
2163 
2164     DNSServiceErrorType err = ConnectToServer(sdRef, flags, port_mapping_request, handle_port_mapping_response, (void *)callBack, context);
2165     if (err) return err;    // On error ConnectToServer leaves *sdRef set to NULL
2166 
2167     len = sizeof(flags);
2168     len += sizeof(interfaceIndex);
2169     len += sizeof(protocol);
2170     len += sizeof(internalPort);
2171     len += sizeof(externalPort);
2172     len += sizeof(ttl);
2173 
2174     hdr = create_hdr(port_mapping_request, &len, &ptr, (*sdRef)->primary ? 1 : 0, *sdRef);
2175     if (!hdr) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; return kDNSServiceErr_NoMemory; }
2176 
2177     put_flags(flags, &ptr);
2178     put_uint32(interfaceIndex, &ptr);
2179     put_uint32(protocol, &ptr);
2180     *ptr++ = internalPort.b[0];
2181     *ptr++ = internalPort.b[1];
2182     *ptr++ = externalPort.b[0];
2183     *ptr++ = externalPort.b[1];
2184     put_uint32(ttl, &ptr);
2185 
2186     err = deliver_request(hdr, *sdRef);     // Will free hdr for us
2187     if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
2188     return err;
2189 }
2190 
2191 #if _DNS_SD_LIBDISPATCH
2192 DNSServiceErrorType DNSSD_API DNSServiceSetDispatchQueue
2193 (
2194     DNSServiceRef service,
2195     dispatch_queue_t queue
2196 )
2197 {
2198     int dnssd_fd  = DNSServiceRefSockFD(service);
2199     if (dnssd_fd == dnssd_InvalidSocket) return kDNSServiceErr_BadParam;
2200     if (!queue)
2201     {
2202         syslog(LOG_WARNING, "dnssd_clientstub: DNSServiceSetDispatchQueue dispatch queue NULL");
2203         return kDNSServiceErr_BadParam;
2204     }
2205     if (service->disp_queue)
2206     {
2207         syslog(LOG_WARNING, "dnssd_clientstub DNSServiceSetDispatchQueue dispatch queue set already");
2208         return kDNSServiceErr_BadParam;
2209     }
2210     if (service->disp_source)
2211     {
2212         syslog(LOG_WARNING, "DNSServiceSetDispatchQueue dispatch source set already");
2213         return kDNSServiceErr_BadParam;
2214     }
2215     service->disp_source = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, dnssd_fd, 0, queue);
2216     if (!service->disp_source)
2217     {
2218         syslog(LOG_WARNING, "DNSServiceSetDispatchQueue dispatch_source_create failed");
2219         return kDNSServiceErr_NoMemory;
2220     }
2221     service->disp_queue = queue;
2222     dispatch_source_set_event_handler(service->disp_source, ^{DNSServiceProcessResult(service);});
2223     dispatch_source_set_cancel_handler(service->disp_source, ^{dnssd_close(dnssd_fd);});
2224     dispatch_resume(service->disp_source);
2225     return kDNSServiceErr_NoError;
2226 }
2227 #endif // _DNS_SD_LIBDISPATCH
2228 
2229 #if !defined(_WIN32)
2230 
2231 static void DNSSD_API SleepKeepaliveCallback(DNSServiceRef sdRef, DNSRecordRef rec, const DNSServiceFlags flags,
2232                                              DNSServiceErrorType errorCode, void *context)
2233 {
2234     SleepKAContext *ka = (SleepKAContext *)context;
2235     (void)rec;      // Unused
2236     (void)flags;    // Unused
2237 
2238     if (sdRef->kacontext != context)
2239         syslog(LOG_WARNING, "SleepKeepaliveCallback context mismatch");
2240 
2241     if (ka->AppCallback)
2242         ((DNSServiceSleepKeepaliveReply)ka->AppCallback)(sdRef, errorCode, ka->AppContext);
2243 }
2244 
2245 DNSServiceErrorType DNSSD_API DNSServiceSleepKeepalive
2246 (
2247     DNSServiceRef                       *sdRef,
2248     DNSServiceFlags flags,
2249     int fd,
2250     unsigned int timeout,
2251     DNSServiceSleepKeepaliveReply callBack,
2252     void                                *context
2253 )
2254 {
2255     char source_str[INET6_ADDRSTRLEN];
2256     char target_str[INET6_ADDRSTRLEN];
2257     struct sockaddr_storage lss;
2258     struct sockaddr_storage rss;
2259     socklen_t len1, len2;
2260     unsigned int len, proxyreclen;
2261     char buf[256];
2262     DNSServiceErrorType err;
2263     DNSRecordRef record = NULL;
2264     char name[10];
2265     char recname[128];
2266     SleepKAContext *ka;
2267     unsigned int i, unique;
2268 
2269 
2270     (void) flags; //unused
2271     if (!timeout) return kDNSServiceErr_BadParam;
2272 
2273 
2274     len1 = sizeof(lss);
2275     if (getsockname(fd, (struct sockaddr *)&lss, &len1) < 0)
2276     {
2277         syslog(LOG_WARNING, "DNSServiceSleepKeepalive: getsockname %d\n", errno);
2278         return kDNSServiceErr_BadParam;
2279     }
2280 
2281     len2 = sizeof(rss);
2282     if (getpeername(fd, (struct sockaddr *)&rss, &len2) < 0)
2283     {
2284         syslog(LOG_WARNING, "DNSServiceSleepKeepalive: getpeername %d\n", errno);
2285         return kDNSServiceErr_BadParam;
2286     }
2287 
2288     if (len1 != len2)
2289     {
2290         syslog(LOG_WARNING, "DNSServiceSleepKeepalive local/remote info not same");
2291         return kDNSServiceErr_Unknown;
2292     }
2293 
2294     unique = 0;
2295     if (lss.ss_family == AF_INET)
2296     {
2297         struct sockaddr_in *sl = (struct sockaddr_in *)&lss;
2298         struct sockaddr_in *sr = (struct sockaddr_in *)&rss;
2299         unsigned char *ptr = (unsigned char *)&sl->sin_addr;
2300 
2301         if (!inet_ntop(AF_INET, (const void *)&sr->sin_addr, target_str, sizeof (target_str)))
2302         {
2303             syslog(LOG_WARNING, "DNSServiceSleepKeepalive remote info failed %d", errno);
2304             return kDNSServiceErr_Unknown;
2305         }
2306         if (!inet_ntop(AF_INET, (const void *)&sl->sin_addr, source_str, sizeof (source_str)))
2307         {
2308             syslog(LOG_WARNING, "DNSServiceSleepKeepalive local info failed %d", errno);
2309             return kDNSServiceErr_Unknown;
2310         }
2311         // Sum of all bytes in the local address and port should result in a unique
2312         // number in the local network
2313         for (i = 0; i < sizeof(struct in_addr); i++)
2314             unique += ptr[i];
2315         unique += sl->sin_port;
2316         len = snprintf(buf+1, sizeof(buf) - 1, "t=%u h=%s d=%s l=%u r=%u", timeout, source_str, target_str, ntohs(sl->sin_port), ntohs(sr->sin_port));
2317     }
2318     else
2319     {
2320         struct sockaddr_in6 *sl6 = (struct sockaddr_in6 *)&lss;
2321         struct sockaddr_in6 *sr6 = (struct sockaddr_in6 *)&rss;
2322         unsigned char *ptr = (unsigned char *)&sl6->sin6_addr;
2323 
2324         if (!inet_ntop(AF_INET6, (const void *)&sr6->sin6_addr, target_str, sizeof (target_str)))
2325         {
2326             syslog(LOG_WARNING, "DNSServiceSleepKeepalive remote6 info failed %d", errno);
2327             return kDNSServiceErr_Unknown;
2328         }
2329         if (!inet_ntop(AF_INET6, (const void *)&sl6->sin6_addr, source_str, sizeof (source_str)))
2330         {
2331             syslog(LOG_WARNING, "DNSServiceSleepKeepalive local6 info failed %d", errno);
2332             return kDNSServiceErr_Unknown;
2333         }
2334         for (i = 0; i < sizeof(struct in6_addr); i++)
2335             unique += ptr[i];
2336         unique += sl6->sin6_port;
2337         len = snprintf(buf+1, sizeof(buf) - 1, "t=%u H=%s D=%s l=%u r=%u", timeout, source_str, target_str, ntohs(sl6->sin6_port), ntohs(sr6->sin6_port));
2338     }
2339 
2340     if (len >= (sizeof(buf) - 1))
2341     {
2342         syslog(LOG_WARNING, "DNSServiceSleepKeepalive could not fit local/remote info");
2343         return kDNSServiceErr_Unknown;
2344     }
2345     // Include the NULL byte also in the first byte. The total length of the record includes the
2346     // first byte also.
2347     buf[0] = len + 1;
2348     proxyreclen = len + 2;
2349 
2350     len = snprintf(name, sizeof(name), "%u", unique);
2351     if (len >= sizeof(name))
2352     {
2353         syslog(LOG_WARNING, "DNSServiceSleepKeepalive could not fit unique");
2354         return kDNSServiceErr_Unknown;
2355     }
2356 
2357     len = snprintf(recname, sizeof(recname), "%s.%s", name, "_keepalive._dns-sd._udp.local");
2358     if (len >= sizeof(recname))
2359     {
2360         syslog(LOG_WARNING, "DNSServiceSleepKeepalive could not fit name");
2361         return kDNSServiceErr_Unknown;
2362     }
2363 
2364     ka = malloc(sizeof(SleepKAContext));
2365     if (!ka) return kDNSServiceErr_NoMemory;
2366     ka->AppCallback = (void *)callBack;
2367     ka->AppContext = context;
2368 
2369     err = DNSServiceCreateConnection(sdRef);
2370     if (err)
2371     {
2372         syslog(LOG_WARNING, "DNSServiceSleepKeepalive cannot create connection");
2373         free(ka);
2374         return err;
2375     }
2376 
2377     // we don't care about the "record". When sdRef gets deallocated later, it will be freed too
2378     err = DNSServiceRegisterRecord(*sdRef, &record, kDNSServiceFlagsUnique, 0, recname,
2379                                    kDNSServiceType_NULL,  kDNSServiceClass_IN, proxyreclen, buf,  kDNSServiceInterfaceIndexAny, SleepKeepaliveCallback, ka);
2380     if (err)
2381     {
2382         syslog(LOG_WARNING, "DNSServiceSleepKeepalive cannot create connection");
2383         free(ka);
2384         return err;
2385     }
2386     (*sdRef)->kacontext = ka;
2387     return kDNSServiceErr_NoError;
2388 }
2389 #endif