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