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