<rdar://problem/6821367> Remove DNSServiceSetDefaultDomainForUser from header file
[people/sha0/mDNSResponder.git] / mDNSShared / dnssd_clientstub.c
1 /* -*- Mode: C; tab-width: 4 -*-
2  *
3  * Copyright (c) 2003-2004, Apple Computer, Inc. All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are met:
7  *
8  * 1.  Redistributions of source code must retain the above copyright notice,
9  *     this list of conditions and the following disclaimer.
10  * 2.  Redistributions in binary form must reproduce the above copyright notice,
11  *     this list of conditions and the following disclaimer in the documentation
12  *     and/or other materials provided with the distribution.
13  * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of its
14  *     contributors may be used to endorse or promote products derived from this
15  *     software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
18  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
21  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
24  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
26  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28
29 #include <errno.h>
30 #include <stdlib.h>
31
32 #include "dnssd_ipc.h"
33
34 #if defined(_WIN32)
35
36         #define _SSIZE_T
37         #include <CommonServices.h>
38         #include <DebugServices.h>
39         #include <winsock2.h>
40         #include <ws2tcpip.h>
41         #include <windows.h>
42         #include <stdarg.h>
43         
44         #define sockaddr_mdns sockaddr_in
45         #define AF_MDNS AF_INET
46         
47         // Disable warning: "'type cast' : from data pointer 'void *' to function pointer"
48         #pragma warning(disable:4055)
49         
50         // Disable warning: "nonstandard extension, function/data pointer conversion in expression"
51         #pragma warning(disable:4152)
52         
53         extern BOOL IsSystemServiceDisabled();
54         
55         #define sleep(X) Sleep((X) * 1000)
56         
57         static int g_initWinsock = 0;
58         #define LOG_WARNING kDebugLevelWarning
59         static void syslog( int priority, const char * message, ...)
60                 {
61                 va_list args;
62                 int len;
63                 char * buffer;
64                 DWORD err = WSAGetLastError();
65                 (void) priority;
66                 va_start( args, message );
67                 len = _vscprintf( message, args ) + 1;
68                 buffer = malloc( len * sizeof(char) );
69                 if ( buffer ) { vsprintf( buffer, message, args ); OutputDebugString( buffer ); free( buffer ); }
70                 WSASetLastError( err );
71                 }
72 #else
73
74         #include <sys/fcntl.h>          // For O_RDWR etc.
75         #include <sys/time.h>
76         #include <sys/socket.h>
77         #include <syslog.h>
78         
79         #define sockaddr_mdns sockaddr_un
80         #define AF_MDNS AF_LOCAL
81
82 #endif
83
84 // <rdar://problem/4096913> Specifies how many times we'll try and connect to the server.
85
86 #define DNSSD_CLIENT_MAXTRIES 4
87
88 // Uncomment the line below to use the old error return mechanism of creating a temporary named socket (e.g. in /var/tmp)
89 //#define USE_NAMED_ERROR_RETURN_SOCKET 1
90
91 #ifndef CTL_PATH_PREFIX
92 #define CTL_PATH_PREFIX "/var/tmp/dnssd_result_socket."
93 #endif
94
95 typedef struct
96         {
97         ipc_msg_hdr         ipc_hdr;
98         DNSServiceFlags     cb_flags;
99         uint32_t            cb_interface;
100         DNSServiceErrorType cb_err;
101         } CallbackHeader;
102
103 typedef struct _DNSServiceRef_t DNSServiceOp;
104 typedef struct _DNSRecordRef_t DNSRecord;
105
106 // client stub callback to process message from server and deliver results to client application
107 typedef void (*ProcessReplyFn)(DNSServiceOp *const sdr, const CallbackHeader *const cbh, const char *msg, const char *const end);
108
109 #define ValidatorBits 0x12345678
110 #define DNSServiceRefValid(X) (dnssd_SocketValid((X)->sockfd) && (((X)->sockfd ^ (X)->validator) == ValidatorBits))
111
112 // When using kDNSServiceFlagsShareConnection, there is one primary _DNSServiceOp_t, and zero or more subordinates
113 // For the primary, the 'next' field points to the first subordinate, and its 'next' field points to the next, and so on.
114 // For the primary, the 'primary' field is NULL; for subordinates the 'primary' field points back to the associated primary
115 struct _DNSServiceRef_t
116         {
117         DNSServiceOp    *next;                          // For shared connection
118         DNSServiceOp    *primary;                       // For shared connection
119         dnssd_sock_t     sockfd;                        // Connected socket between client and daemon
120         dnssd_sock_t     validator;                     // Used to detect memory corruption, double disposals, etc.
121         client_context_t uid;                           // For shared connection requests, each subordinate DNSServiceRef has its own ID,
122                                                                                 // unique within the scope of the same shared parent DNSServiceRef
123         uint32_t         op;                            // request_op_t or reply_op_t
124         uint32_t         max_index;                     // Largest assigned record index - 0 if no additional records registered
125         uint32_t         logcounter;            // Counter used to control number of syslog messages we write
126         int             *moreptr;                       // Set while DNSServiceProcessResult working on this particular DNSServiceRef
127         ProcessReplyFn   ProcessReply;          // Function pointer to the code to handle received messages
128         void            *AppCallback;           // Client callback function and context
129         void            *AppContext;
130         };
131
132 struct _DNSRecordRef_t
133         {
134         void *AppContext;
135         DNSServiceRegisterRecordReply AppCallback;
136         DNSRecordRef recref;
137         uint32_t record_index;  // index is unique to the ServiceDiscoveryRef
138         DNSServiceOp *sdr;
139         };
140
141 // Write len bytes. Return 0 on success, -1 on error
142 static int write_all(dnssd_sock_t sd, char *buf, size_t len)
143         {
144         // Don't use "MSG_WAITALL"; it returns "Invalid argument" on some Linux versions; use an explicit while() loop instead.
145         //if (send(sd, buf, len, MSG_WAITALL) != len) return -1;
146         while (len)
147                 {
148                 ssize_t num_written = send(sd, buf, (long)len, 0);
149                 if (num_written < 0 || (size_t)num_written > len)
150                         {
151                         // Should never happen. If it does, it indicates some OS bug,
152                         // or that the mDNSResponder daemon crashed (which should never happen).
153                         syslog(LOG_WARNING, "dnssd_clientstub write_all(%d) failed %ld/%d %d %s", sd, num_written, len,
154                                 (num_written < 0) ? dnssd_errno                 : 0,
155                                 (num_written < 0) ? dnssd_strerror(dnssd_errno) : "");
156                         return -1;
157                         }
158                 buf += num_written;
159                 len -= num_written;
160                 }
161         return 0;
162         }
163
164 enum { read_all_success = 0, read_all_fail = -1, read_all_wouldblock = -2 };
165
166 // Read len bytes. Return 0 on success, read_all_fail on error, or read_all_wouldblock for 
167 static int read_all(dnssd_sock_t sd, char *buf, int len)
168         {
169         // Don't use "MSG_WAITALL"; it returns "Invalid argument" on some Linux versions; use an explicit while() loop instead.
170         //if (recv(sd, buf, len, MSG_WAITALL) != len) return -1;
171
172         while (len)
173                 {
174                 ssize_t num_read = recv(sd, buf, len, 0);
175                 if ((num_read == 0) || (num_read < 0) || (num_read > len))
176                         {
177                         // Should never happen. If it does, it indicates some OS bug,
178                         // or that the mDNSResponder daemon crashed (which should never happen).
179                         syslog(LOG_WARNING, "dnssd_clientstub read_all(%d) failed %ld/%d %d %s", sd, num_read, len,
180                                 (num_read < 0) ? dnssd_errno                 : 0,
181                                 (num_read < 0) ? dnssd_strerror(dnssd_errno) : "");
182                         return (num_read < 0 && dnssd_errno == dnssd_EWOULDBLOCK) ? read_all_wouldblock : read_all_fail;
183                         }
184                 buf += num_read;
185                 len -= num_read;
186                 }
187         return read_all_success;
188         }
189
190 // Returns 1 if more bytes remain to be read on socket descriptor sd, 0 otherwise
191 static int more_bytes(dnssd_sock_t sd)
192         {
193         struct timeval tv = { 0, 0 };
194         fd_set readfds;
195         FD_ZERO(&readfds);
196         FD_SET(sd, &readfds);
197         return(select((int)sd+1, &readfds, (fd_set*)NULL, (fd_set*)NULL, &tv) > 0);
198         }
199
200 /* create_hdr
201  *
202  * allocate and initialize an ipc message header. Value of len should initially be the
203  * length of the data, and is set to the value of the data plus the header. data_start
204  * is set to point to the beginning of the data section. SeparateReturnSocket should be
205  * non-zero for calls that can't receive an immediate error return value on their primary
206  * socket, and therefore require a separate return path for the error code result.
207  * if zero, the path to a control socket is appended at the beginning of the message buffer.
208  * data_start is set past this string.
209  */
210 static ipc_msg_hdr *create_hdr(uint32_t op, size_t *len, char **data_start, int SeparateReturnSocket, DNSServiceOp *ref)
211         {
212         char *msg = NULL;
213         ipc_msg_hdr *hdr;
214         int datalen;
215 #if !defined(USE_TCP_LOOPBACK)
216         char ctrl_path[64] = "";        // "/var/tmp/dnssd_result_socket.xxxxxxxxxx-xxx-xxxxxx"
217 #endif
218
219         if (SeparateReturnSocket)
220                 {
221 #if defined(USE_TCP_LOOPBACK)
222                 *len += 2;  // Allocate space for two-byte port number
223 #elif defined(USE_NAMED_ERROR_RETURN_SOCKET)
224                 struct timeval tv;
225                 if (gettimeofday(&tv, NULL) < 0)
226                         { syslog(LOG_WARNING, "dnssd_clientstub create_hdr: gettimeofday failed %d %s", dnssd_errno, dnssd_strerror(dnssd_errno)); return NULL; }
227                 sprintf(ctrl_path, "%s%d-%.3lx-%.6lu", CTL_PATH_PREFIX, (int)getpid(),
228                         (unsigned long)(tv.tv_sec & 0xFFF), (unsigned long)(tv.tv_usec));
229                 *len += strlen(ctrl_path) + 1;
230 #else
231                 *len += 1;              // Allocate space for single zero byte (empty C string)
232 #endif
233                 }
234
235         datalen = (int) *len;
236         *len += sizeof(ipc_msg_hdr);
237
238         // Write message to buffer
239         msg = malloc(*len);
240         if (!msg) { syslog(LOG_WARNING, "dnssd_clientstub create_hdr: malloc failed"); return NULL; }
241
242         memset(msg, 0, *len);
243         hdr = (ipc_msg_hdr *)msg;
244         hdr->version                = VERSION;
245         hdr->datalen                = datalen;
246         hdr->ipc_flags              = 0;
247         hdr->op                     = op;
248         hdr->client_context         = ref->uid;
249         hdr->reg_index              = 0;
250         *data_start = msg + sizeof(ipc_msg_hdr);
251 #if defined(USE_TCP_LOOPBACK)
252         // Put dummy data in for the port, since we don't know what it is yet.
253         // The data will get filled in before we send the message. This happens in deliver_request().
254         if (SeparateReturnSocket) put_uint16(0, data_start);
255 #else
256         if (SeparateReturnSocket) put_string(ctrl_path, data_start);
257 #endif
258         return hdr;
259         }
260
261 static void FreeDNSServiceOp(DNSServiceOp *x)
262         {
263         // We don't use our DNSServiceRefValid macro here because if we're cleaning up after a socket() call failed 
264         // then sockfd could legitimately contain a failing value (e.g. dnssd_InvalidSocket)
265         if ((x->sockfd ^ x->validator) != ValidatorBits)
266                 syslog(LOG_WARNING, "dnssd_clientstub attempt to dispose invalid DNSServiceRef %p %08X %08X", x, x->sockfd, x->validator);
267         else
268                 {
269                 x->next         = NULL;
270                 x->primary      = NULL;
271                 x->sockfd       = dnssd_InvalidSocket;
272                 x->validator    = 0xDDDDDDDD;
273                 x->op           = request_op_none;
274                 x->max_index    = 0;
275                 x->logcounter   = 0;
276                 x->moreptr      = NULL;
277                 x->ProcessReply = NULL;
278                 x->AppCallback  = NULL;
279                 x->AppContext   = NULL;
280                 free(x);
281                 }
282         }
283
284 // Return a connected service ref (deallocate with DNSServiceRefDeallocate)
285 static DNSServiceErrorType ConnectToServer(DNSServiceRef *ref, DNSServiceFlags flags, uint32_t op, ProcessReplyFn ProcessReply, void *AppCallback, void *AppContext)
286         {
287         #if APPLE_OSX_mDNSResponder
288         int NumTries = DNSSD_CLIENT_MAXTRIES;
289         #else
290         int NumTries = 0;
291         #endif
292
293         dnssd_sockaddr_t saddr;
294         DNSServiceOp *sdr;
295
296         if (!ref) { syslog(LOG_WARNING, "dnssd_clientstub DNSService operation with NULL DNSServiceRef"); return kDNSServiceErr_BadParam; }
297
298         if (flags & kDNSServiceFlagsShareConnection)
299                 {
300                 if (!*ref)
301                         {
302                         syslog(LOG_WARNING, "dnssd_clientstub kDNSServiceFlagsShareConnection used with NULL DNSServiceRef");
303                         return kDNSServiceErr_BadParam;
304                         }
305                 if (!DNSServiceRefValid(*ref) || (*ref)->op != connection_request || (*ref)->primary)
306                         {
307                         syslog(LOG_WARNING, "dnssd_clientstub kDNSServiceFlagsShareConnection used with invalid DNSServiceRef %p %08X %08X",
308                                 (*ref), (*ref)->sockfd, (*ref)->validator);
309                         *ref = NULL;
310                         return kDNSServiceErr_BadReference;
311                         }
312                 }
313
314         #if defined(_WIN32)
315         if (!g_initWinsock)
316                 {
317                 WSADATA wsaData;
318                 g_initWinsock = 1;
319                 if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) { *ref = NULL; return kDNSServiceErr_ServiceNotRunning; }
320                 }
321         // <rdar://problem/4096913> If the system service is disabled, we only want to try to connect once
322         if (IsSystemServiceDisabled()) NumTries = DNSSD_CLIENT_MAXTRIES;
323         #endif
324
325         sdr = malloc(sizeof(DNSServiceOp));
326         if (!sdr) { syslog(LOG_WARNING, "dnssd_clientstub ConnectToServer: malloc failed"); *ref = NULL; return kDNSServiceErr_NoMemory; }
327         sdr->next          = NULL;
328         sdr->primary       = NULL;
329         sdr->sockfd        = dnssd_InvalidSocket;
330         sdr->validator     = sdr->sockfd ^ ValidatorBits;
331         sdr->op            = op;
332         sdr->max_index     = 0;
333         sdr->logcounter    = 0;
334         sdr->moreptr       = NULL;
335         sdr->uid.u32[0]    = 0;
336         sdr->uid.u32[1]    = 0;
337         sdr->ProcessReply  = ProcessReply;
338         sdr->AppCallback   = AppCallback;
339         sdr->AppContext    = AppContext;
340
341         if (flags & kDNSServiceFlagsShareConnection)
342                 {
343                 DNSServiceOp **p = &(*ref)->next;               // Append ourselves to end of primary's list
344                 while (*p) p = &(*p)->next;
345                 *p = sdr;
346                 // Preincrement counter before we use it -- it helps with debugging if we know the all-zeroes ID should never appear
347                 if (++(*ref)->uid.u32[0] == 0) ++(*ref)->uid.u32[1];    // In parent DNSServiceOp increment UID counter
348                 sdr->primary    = *ref;                                 // Set our primary pointer
349                 sdr->sockfd     = (*ref)->sockfd;               // Inherit primary's socket
350                 sdr->validator  = (*ref)->validator;
351                 sdr->uid        = (*ref)->uid;
352                 //printf("ConnectToServer sharing socket %d\n", sdr->sockfd);
353                 }
354         else
355                 {
356                 #ifdef SO_NOSIGPIPE
357                 const unsigned long optval = 1;
358                 #endif
359                 *ref = NULL;
360                 sdr->sockfd    = socket(AF_DNSSD, SOCK_STREAM, 0);
361                 sdr->validator = sdr->sockfd ^ ValidatorBits;
362                 if (!dnssd_SocketValid(sdr->sockfd))
363                         {
364                         syslog(LOG_WARNING, "dnssd_clientstub ConnectToServer: socket failed %d %s", dnssd_errno, dnssd_strerror(dnssd_errno));
365                         FreeDNSServiceOp(sdr);
366                         return kDNSServiceErr_NoMemory;
367                         }
368                 #ifdef SO_NOSIGPIPE
369                 // Some environments (e.g. OS X) support turning off SIGPIPE for a socket
370                 if (setsockopt(sdr->sockfd, SOL_SOCKET, SO_NOSIGPIPE, &optval, sizeof(optval)) < 0)
371                         syslog(LOG_WARNING, "dnssd_clientstub ConnectToServer: SO_NOSIGPIPE failed %d %s", dnssd_errno, dnssd_strerror(dnssd_errno));
372                 #endif
373                 #if defined(USE_TCP_LOOPBACK)
374                 saddr.sin_family      = AF_INET;
375                 saddr.sin_addr.s_addr = inet_addr(MDNS_TCP_SERVERADDR);
376                 saddr.sin_port        = htons(MDNS_TCP_SERVERPORT);
377                 #else
378                 saddr.sun_family      = AF_LOCAL;
379                 strcpy(saddr.sun_path, MDNS_UDS_SERVERPATH);
380                 #endif
381         
382                 while (1)
383                         {
384                         int err = connect(sdr->sockfd, (struct sockaddr *) &saddr, sizeof(saddr));
385                         if (!err) break; // If we succeeded, return sdr
386                         // If we failed, then it may be because the daemon is still launching.
387                         // This can happen for processes that launch early in the boot process, while the
388                         // daemon is still coming up. Rather than fail here, we'll wait a bit and try again.
389                         // If, after four seconds, we still can't connect to the daemon,
390                         // then we give up and return a failure code.
391                         if (++NumTries < DNSSD_CLIENT_MAXTRIES) sleep(1); // Sleep a bit, then try again
392                         else { dnssd_close(sdr->sockfd); FreeDNSServiceOp(sdr); return kDNSServiceErr_ServiceNotRunning; }
393                         }
394                 //printf("ConnectToServer opened socket %d\n", sdr->sockfd);
395                 }
396
397         *ref = sdr;
398         return kDNSServiceErr_NoError;
399         }
400
401 #define deliver_request_bailout(MSG) \
402         do { syslog(LOG_WARNING, "dnssd_clientstub deliver_request: %s failed %d (%s)", (MSG), dnssd_errno, dnssd_strerror(dnssd_errno)); goto cleanup; } while(0)
403
404 static DNSServiceErrorType deliver_request(ipc_msg_hdr *hdr, DNSServiceOp *sdr)
405         {
406         uint32_t datalen = hdr->datalen;        // We take a copy here because we're going to convert hdr->datalen to network byte order
407         #if defined(USE_TCP_LOOPBACK) || defined(USE_NAMED_ERROR_RETURN_SOCKET)
408         char *const data = (char *)hdr + sizeof(ipc_msg_hdr);
409         #endif
410         dnssd_sock_t listenfd = dnssd_InvalidSocket, errsd = dnssd_InvalidSocket;
411         DNSServiceErrorType err = kDNSServiceErr_Unknown;       // Default for the "goto cleanup" cases
412         int MakeSeparateReturnSocket = 0;
413
414         // Note: need to check hdr->op, not sdr->op.
415         // hdr->op contains the code for the specific operation we're currently doing, whereas sdr->op
416         // contains the original parent DNSServiceOp (e.g. for an add_record_request, hdr->op will be
417         // add_record_request but the parent sdr->op will be connection_request or reg_service_request)
418         if (sdr->primary ||
419                 hdr->op == reg_record_request || hdr->op == add_record_request || hdr->op == update_record_request || hdr->op == remove_record_request)
420                 MakeSeparateReturnSocket = 1;
421
422         if (!DNSServiceRefValid(sdr))
423                 {
424                 syslog(LOG_WARNING, "dnssd_clientstub deliver_request: invalid DNSServiceRef %p %08X %08X", sdr, sdr->sockfd, sdr->validator);
425                 return kDNSServiceErr_BadReference;
426                 }
427
428         if (!hdr) { syslog(LOG_WARNING, "dnssd_clientstub deliver_request: !hdr"); return kDNSServiceErr_Unknown; }
429
430         if (MakeSeparateReturnSocket)
431                 {
432                 #if defined(USE_TCP_LOOPBACK)
433                         {
434                         union { uint16_t s; u_char b[2]; } port;
435                         dnssd_sockaddr_t caddr;
436                         dnssd_socklen_t len = (dnssd_socklen_t) sizeof(caddr);
437                         listenfd = socket(AF_DNSSD, SOCK_STREAM, 0);
438                         if (!dnssd_SocketValid(listenfd)) deliver_request_bailout("TCP socket");
439
440                         caddr.sin_family      = AF_INET;
441                         caddr.sin_port        = 0;
442                         caddr.sin_addr.s_addr = inet_addr(MDNS_TCP_SERVERADDR);
443                         if (bind(listenfd, (struct sockaddr*) &caddr, sizeof(caddr)) < 0) deliver_request_bailout("TCP bind");
444                         if (getsockname(listenfd, (struct sockaddr*) &caddr, &len)   < 0) deliver_request_bailout("TCP getsockname");
445                         if (listen(listenfd, 1)                                      < 0) deliver_request_bailout("TCP listen");
446                         port.s = caddr.sin_port;
447                         data[0] = port.b[0];  // don't switch the byte order, as the
448                         data[1] = port.b[1];  // daemon expects it in network byte order
449                         }
450                 #elif defined(USE_NAMED_ERROR_RETURN_SOCKET)
451                         {
452                         mode_t mask;
453                         int bindresult;
454                         dnssd_sockaddr_t caddr;
455                         listenfd = socket(AF_DNSSD, SOCK_STREAM, 0);
456                         if (!dnssd_SocketValid(listenfd)) deliver_request_bailout("USE_NAMED_ERROR_RETURN_SOCKET socket");
457
458                         caddr.sun_family = AF_LOCAL;
459                         // According to Stevens (section 3.2), there is no portable way to
460                         // determine whether sa_len is defined on a particular platform.
461                         #ifndef NOT_HAVE_SA_LEN
462                         caddr.sun_len = sizeof(struct sockaddr_un);
463                         #endif
464                         strcpy(caddr.sun_path, data);
465                         mask = umask(0);
466                         bindresult = bind(listenfd, (struct sockaddr *)&caddr, sizeof(caddr));
467                         umask(mask);
468                         if (bindresult          < 0) deliver_request_bailout("USE_NAMED_ERROR_RETURN_SOCKET bind");
469                         if (listen(listenfd, 1) < 0) deliver_request_bailout("USE_NAMED_ERROR_RETURN_SOCKET listen");
470                         }
471                 #else
472                         {
473                         dnssd_sock_t sp[2];
474                         if (socketpair(AF_DNSSD, SOCK_STREAM, 0, sp) < 0) deliver_request_bailout("socketpair");
475                         else
476                                 {
477                                 errsd    = sp[0];       // We'll read our four-byte error code from sp[0]
478                                 listenfd = sp[1];       // We'll send sp[1] to the daemon
479                                 }
480                         }
481                 #endif
482                 }
483
484 #if !defined(USE_TCP_LOOPBACK) && !defined(USE_NAMED_ERROR_RETURN_SOCKET)
485         // If we're going to make a separate error return socket, and pass it to the daemon
486         // using sendmsg, then we'll hold back one data byte to go with it.
487         // On some versions of Unix (including Leopard) sending a control message without
488         // any associated data does not work reliably -- e.g. one particular issue we ran
489         // into is that if the receiving program is in a kqueue loop waiting to be notified
490         // of the received message, it doesn't get woken up when the control message arrives.
491         if (MakeSeparateReturnSocket || sdr->op == send_bpf) datalen--;         // Okay to use sdr->op when checking for op == send_bpf
492 #endif
493
494         // At this point, our listening socket is set up and waiting, if necessary, for the daemon to connect back to
495         ConvertHeaderBytes(hdr);
496         //syslog(LOG_WARNING, "dnssd_clientstub deliver_request writing %lu bytes", (unsigned long)(datalen + sizeof(ipc_msg_hdr)));
497         //if (MakeSeparateReturnSocket) syslog(LOG_WARNING, "dnssd_clientstub deliver_request name is %s", data);
498 #if TEST_SENDING_ONE_BYTE_AT_A_TIME
499         unsigned int i;
500         for (i=0; i<datalen + sizeof(ipc_msg_hdr); i++)
501                 {
502                 syslog(LOG_WARNING, "dnssd_clientstub deliver_request writing %d", i);
503                 if (write_all(sdr->sockfd, ((char *)hdr)+i, 1) < 0)
504                         { syslog(LOG_WARNING, "write_all (byte %u) failed", i); goto cleanup; }
505                 usleep(10000);
506                 }
507 #else
508         if (write_all(sdr->sockfd, (char *)hdr, datalen + sizeof(ipc_msg_hdr)) < 0)
509                 {
510                 syslog(LOG_WARNING, "dnssd_clientstub deliver_request ERROR: write_all(%d, %lu bytes) failed",
511                         sdr->sockfd, (unsigned long)(datalen + sizeof(ipc_msg_hdr)));
512                 goto cleanup;
513                 }
514 #endif
515
516         if (!MakeSeparateReturnSocket) errsd = sdr->sockfd;
517         if (MakeSeparateReturnSocket || sdr->op == send_bpf)    // Okay to use sdr->op when checking for op == send_bpf
518                 {
519 #if defined(USE_TCP_LOOPBACK) || defined(USE_NAMED_ERROR_RETURN_SOCKET)
520                 // At this point we may block in accept for a few milliseconds waiting for the daemon to connect back to us,
521                 // but that's okay -- the daemon is a trusted service and we know if won't take more than a few milliseconds to respond.
522                 dnssd_sockaddr_t daddr;
523                 dnssd_socklen_t len = sizeof(daddr);
524                 errsd = accept(listenfd, (struct sockaddr *)&daddr, &len);
525                 if (!dnssd_SocketValid(errsd)) deliver_request_bailout("accept");
526 #else
527
528 #if APPLE_OSX_mDNSResponder
529 // On Leopard, the stock definitions of the CMSG_* macros in /usr/include/sys/socket.h,
530 // while arguably correct in theory, nonetheless in practice produce code that doesn't work on 64-bit machines
531 // For details see <rdar://problem/5565787> Bonjour API broken for 64-bit apps (SCM_RIGHTS sendmsg fails)
532 #undef  CMSG_DATA
533 #define CMSG_DATA(cmsg) ((unsigned char *)(cmsg) + (sizeof(struct cmsghdr)))
534 #undef  CMSG_SPACE
535 #define CMSG_SPACE(l)   ((sizeof(struct cmsghdr)) + (l))
536 #undef  CMSG_LEN
537 #define CMSG_LEN(l)     ((sizeof(struct cmsghdr)) + (l))
538 #endif
539
540                 struct iovec vec = { ((char *)hdr) + sizeof(ipc_msg_hdr) + datalen, 1 }; // Send the last byte along with the SCM_RIGHTS
541                 struct msghdr msg;
542                 struct cmsghdr *cmsg;
543                 char cbuf[CMSG_SPACE(sizeof(dnssd_sock_t))];
544
545                 if (sdr->op == send_bpf)        // Okay to use sdr->op when checking for op == send_bpf
546                         {
547                         int i;
548                         char p[12];             // Room for "/dev/bpf999" with terminating null
549                         for (i=0; i<100; i++)
550                                 {
551                                 snprintf(p, sizeof(p), "/dev/bpf%d", i);
552                                 listenfd = open(p, O_RDWR, 0);
553                                 //if (dnssd_SocketValid(listenfd)) syslog(LOG_WARNING, "Sending fd %d for %s", listenfd, p);
554                                 if (!dnssd_SocketValid(listenfd) && dnssd_errno != EBUSY)
555                                         syslog(LOG_WARNING, "Error opening %s %d (%s)", p, dnssd_errno, dnssd_strerror(dnssd_errno));
556                                 if (dnssd_SocketValid(listenfd) || dnssd_errno != EBUSY) break;
557                                 }
558                         }
559
560                 msg.msg_name       = 0;
561                 msg.msg_namelen    = 0;
562                 msg.msg_iov        = &vec;
563                 msg.msg_iovlen     = 1;
564                 msg.msg_control    = cbuf;
565                 msg.msg_controllen = CMSG_LEN(sizeof(dnssd_sock_t));
566                 msg.msg_flags      = 0;
567                 cmsg = CMSG_FIRSTHDR(&msg);
568                 cmsg->cmsg_len     = CMSG_LEN(sizeof(dnssd_sock_t));
569                 cmsg->cmsg_level   = SOL_SOCKET;
570                 cmsg->cmsg_type    = SCM_RIGHTS;
571                 *((dnssd_sock_t *)CMSG_DATA(cmsg)) = listenfd;
572
573 #if TEST_KQUEUE_CONTROL_MESSAGE_BUG
574                 sleep(1);
575 #endif
576
577 #if DEBUG_64BIT_SCM_RIGHTS
578                 syslog(LOG_WARNING, "dnssd_clientstub sendmsg read sd=%d write sd=%d %ld %ld %ld/%ld/%ld/%ld",
579                         errsd, listenfd, sizeof(dnssd_sock_t), sizeof(void*),
580                         sizeof(struct cmsghdr) + sizeof(dnssd_sock_t),
581                         CMSG_LEN(sizeof(dnssd_sock_t)), (long)CMSG_SPACE(sizeof(dnssd_sock_t)),
582                         (long)((char*)CMSG_DATA(cmsg) + 4 - cbuf));
583 #endif // DEBUG_64BIT_SCM_RIGHTS
584
585                 if (sendmsg(sdr->sockfd, &msg, 0) < 0)
586                         {
587                         syslog(LOG_WARNING, "dnssd_clientstub deliver_request ERROR: sendmsg failed read sd=%d write sd=%d errno %d (%s)",
588                                 errsd, listenfd, dnssd_errno, dnssd_strerror(dnssd_errno));
589                         err = kDNSServiceErr_Incompatible;
590                         goto cleanup;
591                         }
592
593 #if DEBUG_64BIT_SCM_RIGHTS
594                 syslog(LOG_WARNING, "dnssd_clientstub sendmsg read sd=%d write sd=%d okay", errsd, listenfd);
595 #endif // DEBUG_64BIT_SCM_RIGHTS
596
597 #endif
598                 // Close our end of the socketpair *before* blocking in read_all to get the four-byte error code.
599                 // Otherwise, if the daemon closes our socket (or crashes), we block in read_all() forever
600                 // because the socket is not closed (we still have an open reference to it ourselves).
601                 dnssd_close(listenfd);
602                 listenfd = dnssd_InvalidSocket;         // Make sure we don't close it a second time in the cleanup handling below
603                 }
604
605         // At this point we may block in read_all for a few milliseconds waiting for the daemon to send us the error code,
606         // but that's okay -- the daemon is a trusted service and we know if won't take more than a few milliseconds to respond.
607         if (sdr->op == send_bpf)        // Okay to use sdr->op when checking for op == send_bpf
608                 err = kDNSServiceErr_NoError;
609         else if (read_all(errsd, (char*)&err, (int)sizeof(err)) < 0)
610                 err = kDNSServiceErr_ServiceNotRunning; // On failure read_all will have written a message to syslog for us
611         else
612                 err = ntohl(err);
613
614         //syslog(LOG_WARNING, "dnssd_clientstub deliver_request: retrieved error code %d", err);
615
616 cleanup:
617         if (MakeSeparateReturnSocket)
618                 {
619                 if (dnssd_SocketValid(listenfd)) dnssd_close(listenfd);
620                 if (dnssd_SocketValid(errsd))    dnssd_close(errsd);
621 #if defined(USE_NAMED_ERROR_RETURN_SOCKET)
622                 // syslog(LOG_WARNING, "dnssd_clientstub deliver_request: removing UDS: %s", data);
623                 if (unlink(data) != 0)
624                         syslog(LOG_WARNING, "dnssd_clientstub WARNING: unlink(\"%s\") failed errno %d (%s)", data, dnssd_errno, dnssd_strerror(dnssd_errno));
625                 // else syslog(LOG_WARNING, "dnssd_clientstub deliver_request: removed UDS: %s", data);
626 #endif
627                 }
628
629         free(hdr);
630         return err;
631         }
632
633 int DNSSD_API DNSServiceRefSockFD(DNSServiceRef sdRef)
634         {
635         if (!sdRef) { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRefSockFD called with NULL DNSServiceRef"); return dnssd_InvalidSocket; }
636
637         if (!DNSServiceRefValid(sdRef))
638                 {
639                 syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRefSockFD called with invalid DNSServiceRef %p %08X %08X",
640                         sdRef, sdRef->sockfd, sdRef->validator);
641                 return dnssd_InvalidSocket;
642                 }
643
644         if (sdRef->primary)
645                 {
646                 syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRefSockFD undefined for kDNSServiceFlagsShareConnection subordinate DNSServiceRef %p", sdRef);
647                 return dnssd_InvalidSocket;
648                 }
649
650         return (int) sdRef->sockfd;
651         }
652
653 // Handle reply from server, calling application client callback. If there is no reply
654 // from the daemon on the socket contained in sdRef, the call will block.
655 DNSServiceErrorType DNSSD_API DNSServiceProcessResult(DNSServiceRef sdRef)
656         {
657         int morebytes = 0;
658
659         if (!sdRef) { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceProcessResult called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam; }
660
661         if (!DNSServiceRefValid(sdRef))
662                 {
663                 syslog(LOG_WARNING, "dnssd_clientstub DNSServiceProcessResult called with invalid DNSServiceRef %p %08X %08X", sdRef, sdRef->sockfd, sdRef->validator);
664                 return kDNSServiceErr_BadReference;
665                 }
666
667         if (sdRef->primary)
668                 {
669                 syslog(LOG_WARNING, "dnssd_clientstub DNSServiceProcessResult undefined for kDNSServiceFlagsShareConnection subordinate DNSServiceRef %p", sdRef);
670                 return kDNSServiceErr_BadReference;
671                 }
672
673         if (!sdRef->ProcessReply)
674                 {
675                 static int num_logs = 0;
676                 if (num_logs < 10) syslog(LOG_WARNING, "dnssd_clientstub DNSServiceProcessResult called with DNSServiceRef with no ProcessReply function");
677                 if (num_logs < 1000) num_logs++; else sleep(1);
678                 return kDNSServiceErr_BadReference;
679                 }
680
681         do
682                 {
683                 CallbackHeader cbh;
684                 char *data;
685         
686                 // return NoError on EWOULDBLOCK. This will handle the case
687                 // where a non-blocking socket is told there is data, but it was a false positive.
688                 // On error, read_all will write a message to syslog for us, so don't need to duplicate that here
689                 // Note: If we want to properly support using non-blocking sockets in the future 
690                 int result = read_all(sdRef->sockfd, (void *)&cbh.ipc_hdr, sizeof(cbh.ipc_hdr));
691                 if (result == read_all_fail)
692                         {
693                         sdRef->ProcessReply = NULL;
694                         return kDNSServiceErr_ServiceNotRunning;
695                         }
696                 else if (result == read_all_wouldblock)
697                         {
698                         if (morebytes && sdRef->logcounter < 100)
699                                 {
700                                 sdRef->logcounter++;
701                                 syslog(LOG_WARNING, "dnssd_clientstub DNSServiceProcessResult error: select indicated data was waiting but read_all returned EWOULDBLOCK");
702                                 }
703                         return kDNSServiceErr_NoError;
704                         }
705         
706                 ConvertHeaderBytes(&cbh.ipc_hdr);
707                 if (cbh.ipc_hdr.version != VERSION)
708                         {
709                         syslog(LOG_WARNING, "dnssd_clientstub DNSServiceProcessResult daemon version %d does not match client version %d", cbh.ipc_hdr.version, VERSION);
710                         sdRef->ProcessReply = NULL;
711                         return kDNSServiceErr_Incompatible;
712                         }
713         
714                 data = malloc(cbh.ipc_hdr.datalen);
715                 if (!data) return kDNSServiceErr_NoMemory;
716                 if (read_all(sdRef->sockfd, data, cbh.ipc_hdr.datalen) < 0) // On error, read_all will write a message to syslog for us
717                         {
718                         free(data);
719                         sdRef->ProcessReply = NULL;
720                         return kDNSServiceErr_ServiceNotRunning;
721                         }
722                 else
723                         {
724                         const char *ptr = data;
725                         cbh.cb_flags     = get_flags     (&ptr, data + cbh.ipc_hdr.datalen);
726                         cbh.cb_interface = get_uint32    (&ptr, data + cbh.ipc_hdr.datalen);
727                         cbh.cb_err       = get_error_code(&ptr, data + cbh.ipc_hdr.datalen);
728
729                         // CAUTION: We have to handle the case where the client calls DNSServiceRefDeallocate from within the callback function.
730                         // To do this we set moreptr to point to morebytes. If the client does call DNSServiceRefDeallocate(),
731                         // then that routine will clear morebytes for us, and cause us to exit our loop.
732                         morebytes = more_bytes(sdRef->sockfd);
733                         if (morebytes)
734                                 {
735                                 cbh.cb_flags |= kDNSServiceFlagsMoreComing;
736                                 sdRef->moreptr = &morebytes;
737                                 }
738                         if (ptr) sdRef->ProcessReply(sdRef, &cbh, ptr, data + cbh.ipc_hdr.datalen);
739                         // Careful code here:
740                         // If morebytes is non-zero, that means we set sdRef->moreptr above, and the operation was not
741                         // cancelled out from under us, so now we need to clear sdRef->moreptr so we don't leave a stray
742                         // dangling pointer pointing to a long-gone stack variable.
743                         // If morebytes is zero, then one of two thing happened:
744                         // (a) morebytes was 0 above, so we didn't set sdRef->moreptr, so we don't need to clear it
745                         // (b) morebytes was 1 above, and we set sdRef->moreptr, but the operation was cancelled (with DNSServiceRefDeallocate()),
746                         //     so we MUST NOT try to dereference our stale sdRef pointer.
747                         if (morebytes) sdRef->moreptr = NULL;
748                         }
749                 free(data);
750                 } while (morebytes);
751
752         return kDNSServiceErr_NoError;
753         }
754
755 void DNSSD_API DNSServiceRefDeallocate(DNSServiceRef sdRef)
756         {
757         if (!sdRef) { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRefDeallocate called with NULL DNSServiceRef"); return; }
758
759         if (!DNSServiceRefValid(sdRef))         // Also verifies dnssd_SocketValid(sdRef->sockfd) for us too
760                 {
761                 syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRefDeallocate called with invalid DNSServiceRef %p %08X %08X", sdRef, sdRef->sockfd, sdRef->validator);
762                 return;
763                 }
764
765         // 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
766         if (sdRef->moreptr) *(sdRef->moreptr) = 0;
767
768         if (sdRef->primary)             // If this is a subordinate DNSServiceOp, just send a 'stop' command
769                 {
770                 DNSServiceOp **p = &sdRef->primary->next;
771                 while (*p && *p != sdRef) p = &(*p)->next;
772                 if (*p)
773                         {
774                         char *ptr;
775                         size_t len = 0;
776                         ipc_msg_hdr *hdr = create_hdr(cancel_request, &len, &ptr, 0, sdRef);
777                         ConvertHeaderBytes(hdr);
778                         write_all(sdRef->sockfd, (char *)hdr, len);
779                         free(hdr);
780                         *p = sdRef->next;
781                         FreeDNSServiceOp(sdRef);
782                         }
783                 }
784         else                                    // else, make sure to terminate all subordinates as well
785                 {
786                 dnssd_close(sdRef->sockfd);
787                 while (sdRef)
788                         {
789                         DNSServiceOp *p = sdRef;
790                         sdRef = sdRef->next;
791                         FreeDNSServiceOp(p);
792                         }
793                 }
794         }
795
796 DNSServiceErrorType DNSSD_API DNSServiceGetProperty(const char *property, void *result, uint32_t *size)
797         {
798         char *ptr;
799         size_t len = strlen(property) + 1;
800         ipc_msg_hdr *hdr;
801         DNSServiceOp *tmp;
802         uint32_t actualsize;
803
804         DNSServiceErrorType err = ConnectToServer(&tmp, 0, getproperty_request, NULL, NULL, NULL);
805         if (err) return err;
806
807         hdr = create_hdr(getproperty_request, &len, &ptr, 0, tmp);
808         if (!hdr) { DNSServiceRefDeallocate(tmp); return kDNSServiceErr_NoMemory; }
809
810         put_string(property, &ptr);
811         err = deliver_request(hdr, tmp);                // Will free hdr for us
812         if (read_all(tmp->sockfd, (char*)&actualsize, (int)sizeof(actualsize)) < 0)
813                 { DNSServiceRefDeallocate(tmp); return kDNSServiceErr_ServiceNotRunning; }
814
815         actualsize = ntohl(actualsize);
816         if (read_all(tmp->sockfd, (char*)result, actualsize < *size ? actualsize : *size) < 0)
817                 { DNSServiceRefDeallocate(tmp); return kDNSServiceErr_ServiceNotRunning; }
818         DNSServiceRefDeallocate(tmp);
819
820         // Swap version result back to local process byte order
821         if (!strcmp(property, kDNSServiceProperty_DaemonVersion) && *size >= 4)
822                 *(uint32_t*)result = ntohl(*(uint32_t*)result);
823
824         *size = actualsize;
825         return kDNSServiceErr_NoError;
826         }
827
828 static void handle_resolve_response(DNSServiceOp *const sdr, const CallbackHeader *const cbh, const char *data, const char *end)
829         {
830         char fullname[kDNSServiceMaxDomainName];
831         char target[kDNSServiceMaxDomainName];
832         uint16_t txtlen;
833         union { uint16_t s; u_char b[2]; } port;
834         unsigned char *txtrecord;
835
836         get_string(&data, end, fullname, kDNSServiceMaxDomainName);
837         get_string(&data, end, target,   kDNSServiceMaxDomainName);
838         if (!data || data + 2 > end) goto fail;
839
840         port.b[0] = *data++;
841         port.b[1] = *data++;
842         txtlen = get_uint16(&data, end);
843         txtrecord = (unsigned char *)get_rdata(&data, end, txtlen);
844
845         if (!data) goto fail;
846         ((DNSServiceResolveReply)sdr->AppCallback)(sdr, cbh->cb_flags, cbh->cb_interface, cbh->cb_err, fullname, target, port.s, txtlen, txtrecord, sdr->AppContext);
847         return;
848         // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
849 fail:
850         syslog(LOG_WARNING, "dnssd_clientstub handle_resolve_response: error reading result from daemon");
851         }
852
853 DNSServiceErrorType DNSSD_API DNSServiceResolve
854         (
855         DNSServiceRef                 *sdRef,
856         DNSServiceFlags               flags,
857         uint32_t                      interfaceIndex,
858         const char                    *name,
859         const char                    *regtype,
860         const char                    *domain,
861         DNSServiceResolveReply        callBack,
862         void                          *context
863         )
864         {
865         char *ptr;
866         size_t len;
867         ipc_msg_hdr *hdr;
868         DNSServiceErrorType err;
869
870         if (!name || !regtype || !domain || !callBack) return kDNSServiceErr_BadParam;
871
872         err = ConnectToServer(sdRef, flags, resolve_request, handle_resolve_response, callBack, context);
873         if (err) return err;    // On error ConnectToServer leaves *sdRef set to NULL
874
875         // Calculate total message length
876         len = sizeof(flags);
877         len += sizeof(interfaceIndex);
878         len += strlen(name) + 1;
879         len += strlen(regtype) + 1;
880         len += strlen(domain) + 1;
881
882         hdr = create_hdr(resolve_request, &len, &ptr, (*sdRef)->primary ? 1 : 0, *sdRef);
883         if (!hdr) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; return kDNSServiceErr_NoMemory; }
884
885         put_flags(flags, &ptr);
886         put_uint32(interfaceIndex, &ptr);
887         put_string(name, &ptr);
888         put_string(regtype, &ptr);
889         put_string(domain, &ptr);
890
891         err = deliver_request(hdr, *sdRef);             // Will free hdr for us
892         if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
893         return err;
894         }
895
896 static void handle_query_response(DNSServiceOp *const sdr, const CallbackHeader *const cbh, const char *data, const char *const end)
897         {
898         uint32_t ttl;
899         char name[kDNSServiceMaxDomainName];
900         uint16_t rrtype, rrclass, rdlen;
901         const char *rdata;
902
903         get_string(&data, end, name, kDNSServiceMaxDomainName);
904         rrtype  = get_uint16(&data, end);
905         rrclass = get_uint16(&data, end);
906         rdlen   = get_uint16(&data, end);
907         rdata   = get_rdata(&data, end, rdlen);
908         ttl     = get_uint32(&data, end);
909
910         if (!data) syslog(LOG_WARNING, "dnssd_clientstub handle_query_response: error reading result from daemon");
911         else ((DNSServiceQueryRecordReply)sdr->AppCallback)(sdr, cbh->cb_flags, cbh->cb_interface, cbh->cb_err, name, rrtype, rrclass, rdlen, rdata, ttl, sdr->AppContext);
912         // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
913         }
914
915 DNSServiceErrorType DNSSD_API DNSServiceQueryRecord
916         (
917         DNSServiceRef              *sdRef,
918         DNSServiceFlags             flags,
919         uint32_t                    interfaceIndex,
920         const char                 *name,
921         uint16_t                    rrtype,
922         uint16_t                    rrclass,
923         DNSServiceQueryRecordReply  callBack,
924         void                       *context
925         )
926         {
927         char *ptr;
928         size_t len;
929         ipc_msg_hdr *hdr;
930         DNSServiceErrorType err = ConnectToServer(sdRef, flags, query_request, handle_query_response, callBack, context);
931         if (err) return err;    // On error ConnectToServer leaves *sdRef set to NULL
932
933         if (!name) name = "\0";
934
935         // Calculate total message length
936         len = sizeof(flags);
937         len += sizeof(uint32_t);  // interfaceIndex
938         len += strlen(name) + 1;
939         len += 2 * sizeof(uint16_t);  // rrtype, rrclass
940
941         hdr = create_hdr(query_request, &len, &ptr, (*sdRef)->primary ? 1 : 0, *sdRef);
942         if (!hdr) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; return kDNSServiceErr_NoMemory; }
943
944         put_flags(flags, &ptr);
945         put_uint32(interfaceIndex, &ptr);
946         put_string(name, &ptr);
947         put_uint16(rrtype, &ptr);
948         put_uint16(rrclass, &ptr);
949
950         err = deliver_request(hdr, *sdRef);             // Will free hdr for us
951         if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
952         return err;
953         }
954
955 static void handle_addrinfo_response(DNSServiceOp *const sdr, const CallbackHeader *const cbh, const char *data, const char *const end)
956         {
957         char hostname[kDNSServiceMaxDomainName];
958         uint16_t rrtype, rrclass, rdlen;
959         const char *rdata;
960         uint32_t ttl;
961
962         get_string(&data, end, hostname, kDNSServiceMaxDomainName);
963         rrtype  = get_uint16(&data, end);
964         rrclass = get_uint16(&data, end);
965         rdlen   = get_uint16(&data, end);
966         rdata   = get_rdata (&data, end, rdlen);
967         ttl     = get_uint32(&data, end);
968
969         // We only generate client callbacks for A and AAAA results (including NXDOMAIN results for
970         // those types, if the client has requested those with the kDNSServiceFlagsReturnIntermediates).
971         // Other result types, specifically CNAME referrals, are not communicated to the client, because
972         // the DNSServiceGetAddrInfoReply interface doesn't have any meaningful way to communiate CNAME referrals.
973         if (!data) syslog(LOG_WARNING, "dnssd_clientstub handle_addrinfo_response: error reading result from daemon");
974         else if (rrtype == kDNSServiceType_A || rrtype == kDNSServiceType_AAAA)
975                 {
976                 struct sockaddr_in  sa4;
977                 struct sockaddr_in6 sa6;
978                 const struct sockaddr *const sa = (rrtype == kDNSServiceType_A) ? (struct sockaddr*)&sa4 : (struct sockaddr*)&sa6;
979                 if (rrtype == kDNSServiceType_A)
980                         {
981                         memset(&sa4, 0, sizeof(sa4));
982                         #ifndef NOT_HAVE_SA_LEN
983                         sa4.sin_len = sizeof(struct sockaddr_in);
984                         #endif
985                         sa4.sin_family = AF_INET;
986                         //  sin_port   = 0;
987                         if (!cbh->cb_err) memcpy(&sa4.sin_addr, rdata, rdlen);
988                         }
989                 else
990                         {
991                         memset(&sa6, 0, sizeof(sa6));
992                         #ifndef NOT_HAVE_SA_LEN
993                         sa6.sin6_len = sizeof(struct sockaddr_in6);
994                         #endif
995                         sa6.sin6_family     = AF_INET6;
996                         //  sin6_port     = 0;
997                         //  sin6_flowinfo = 0;
998                         //  sin6_scope_id = 0;
999                         if (!cbh->cb_err)
1000                                 {
1001                                 memcpy(&sa6.sin6_addr, rdata, rdlen);
1002                                 if (IN6_IS_ADDR_LINKLOCAL(&sa6.sin6_addr)) sa6.sin6_scope_id = cbh->cb_interface;
1003                                 }
1004                         }
1005                 ((DNSServiceGetAddrInfoReply)sdr->AppCallback)(sdr, cbh->cb_flags, cbh->cb_interface, cbh->cb_err, hostname, sa, ttl, sdr->AppContext);
1006                 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1007                 }
1008         }
1009
1010 DNSServiceErrorType DNSSD_API DNSServiceGetAddrInfo
1011         (
1012         DNSServiceRef                    *sdRef,
1013         DNSServiceFlags                  flags,
1014         uint32_t                         interfaceIndex,
1015         uint32_t                         protocol,
1016         const char                       *hostname,
1017         DNSServiceGetAddrInfoReply       callBack,
1018         void                             *context          /* may be NULL */
1019         )
1020         {
1021         char *ptr;
1022         size_t len;
1023         ipc_msg_hdr *hdr;
1024         DNSServiceErrorType err;
1025
1026         if (!hostname) return kDNSServiceErr_BadParam;
1027
1028         err = ConnectToServer(sdRef, flags, addrinfo_request, handle_addrinfo_response, callBack, context);
1029         if (err) return err;    // On error ConnectToServer leaves *sdRef set to NULL
1030
1031         // Calculate total message length
1032         len = sizeof(flags);
1033         len += sizeof(uint32_t);      // interfaceIndex
1034         len += sizeof(uint32_t);      // protocol
1035         len += strlen(hostname) + 1;
1036
1037         hdr = create_hdr(addrinfo_request, &len, &ptr, (*sdRef)->primary ? 1 : 0, *sdRef);
1038         if (!hdr) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; return kDNSServiceErr_NoMemory; }
1039
1040         put_flags(flags, &ptr);
1041         put_uint32(interfaceIndex, &ptr);
1042         put_uint32(protocol, &ptr);
1043         put_string(hostname, &ptr);
1044
1045         err = deliver_request(hdr, *sdRef);             // Will free hdr for us
1046         if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
1047         return err;
1048         }
1049         
1050 static void handle_browse_response(DNSServiceOp *const sdr, const CallbackHeader *const cbh, const char *data, const char *const end)
1051         {
1052         char replyName[256], replyType[kDNSServiceMaxDomainName], replyDomain[kDNSServiceMaxDomainName];
1053         get_string(&data, end, replyName, 256);
1054         get_string(&data, end, replyType, kDNSServiceMaxDomainName);
1055         get_string(&data, end, replyDomain, kDNSServiceMaxDomainName);
1056         if (!data) syslog(LOG_WARNING, "dnssd_clientstub handle_browse_response: error reading result from daemon");
1057         else ((DNSServiceBrowseReply)sdr->AppCallback)(sdr, cbh->cb_flags, cbh->cb_interface, cbh->cb_err, replyName, replyType, replyDomain, sdr->AppContext);
1058         // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1059         }
1060
1061 DNSServiceErrorType DNSSD_API DNSServiceBrowse
1062         (
1063         DNSServiceRef         *sdRef,
1064         DNSServiceFlags        flags,
1065         uint32_t               interfaceIndex,
1066         const char            *regtype,
1067         const char            *domain,
1068         DNSServiceBrowseReply  callBack,
1069         void                  *context
1070         )
1071         {
1072         char *ptr;
1073         size_t len;
1074         ipc_msg_hdr *hdr;
1075         DNSServiceErrorType err = ConnectToServer(sdRef, flags, browse_request, handle_browse_response, callBack, context);
1076         if (err) return err;    // On error ConnectToServer leaves *sdRef set to NULL
1077
1078         if (!domain) domain = "";
1079         len = sizeof(flags);
1080         len += sizeof(interfaceIndex);
1081         len += strlen(regtype) + 1;
1082         len += strlen(domain) + 1;
1083
1084         hdr = create_hdr(browse_request, &len, &ptr, (*sdRef)->primary ? 1 : 0, *sdRef);
1085         if (!hdr) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; return kDNSServiceErr_NoMemory; }
1086
1087         put_flags(flags, &ptr);
1088         put_uint32(interfaceIndex, &ptr);
1089         put_string(regtype, &ptr);
1090         put_string(domain, &ptr);
1091
1092         err = deliver_request(hdr, *sdRef);             // Will free hdr for us
1093         if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
1094         return err;
1095         }
1096
1097 DNSServiceErrorType DNSSD_API DNSServiceSetDefaultDomainForUser(DNSServiceFlags flags, const char *domain)
1098         {
1099         DNSServiceOp *tmp;
1100         char *ptr;
1101         size_t len = sizeof(flags) + strlen(domain) + 1;
1102         ipc_msg_hdr *hdr;
1103         DNSServiceErrorType err = ConnectToServer(&tmp, 0, setdomain_request, NULL, NULL, NULL);
1104         if (err) return err;
1105
1106         hdr = create_hdr(setdomain_request, &len, &ptr, 0, tmp);
1107         if (!hdr) { DNSServiceRefDeallocate(tmp); return kDNSServiceErr_NoMemory; }
1108
1109         put_flags(flags, &ptr);
1110         put_string(domain, &ptr);
1111         err = deliver_request(hdr, tmp);                // Will free hdr for us
1112         DNSServiceRefDeallocate(tmp);
1113         return err;
1114         }
1115
1116 static void handle_regservice_response(DNSServiceOp *const sdr, const CallbackHeader *const cbh, const char *data, const char *const end)
1117         {
1118         char name[256], regtype[kDNSServiceMaxDomainName], domain[kDNSServiceMaxDomainName];
1119         get_string(&data, end, name, 256);
1120         get_string(&data, end, regtype, kDNSServiceMaxDomainName);
1121         get_string(&data, end, domain,  kDNSServiceMaxDomainName);
1122         if (!data) syslog(LOG_WARNING, "dnssd_clientstub handle_regservice_response: error reading result from daemon");
1123         else ((DNSServiceRegisterReply)sdr->AppCallback)(sdr, cbh->cb_flags, cbh->cb_err, name, regtype, domain, sdr->AppContext);
1124         // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1125         }
1126
1127 DNSServiceErrorType DNSSD_API DNSServiceRegister
1128         (
1129         DNSServiceRef                       *sdRef,
1130         DNSServiceFlags                     flags,
1131         uint32_t                            interfaceIndex,
1132         const char                          *name,
1133         const char                          *regtype,
1134         const char                          *domain,
1135         const char                          *host,
1136         uint16_t                            PortInNetworkByteOrder,
1137         uint16_t                            txtLen,
1138         const void                          *txtRecord,
1139         DNSServiceRegisterReply             callBack,
1140         void                                *context
1141         )
1142         {
1143         char *ptr;
1144         size_t len;
1145         ipc_msg_hdr *hdr;
1146         DNSServiceErrorType err;
1147         union { uint16_t s; u_char b[2]; } port = { PortInNetworkByteOrder };
1148
1149         if (!name) name = "";
1150         if (!regtype) return kDNSServiceErr_BadParam;
1151         if (!domain) domain = "";
1152         if (!host) host = "";
1153         if (!txtRecord) txtRecord = (void*)"";
1154
1155         // No callback must have auto-rename
1156         if (!callBack && (flags & kDNSServiceFlagsNoAutoRename)) return kDNSServiceErr_BadParam;
1157
1158         err = ConnectToServer(sdRef, flags, reg_service_request, callBack ? handle_regservice_response : NULL, callBack, context);
1159         if (err) return err;    // On error ConnectToServer leaves *sdRef set to NULL
1160
1161         len = sizeof(DNSServiceFlags);
1162         len += sizeof(uint32_t);  // interfaceIndex
1163         len += strlen(name) + strlen(regtype) + strlen(domain) + strlen(host) + 4;
1164         len += 2 * sizeof(uint16_t);  // port, txtLen
1165         len += txtLen;
1166
1167         hdr = create_hdr(reg_service_request, &len, &ptr, (*sdRef)->primary ? 1 : 0, *sdRef);
1168         if (!hdr) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; return kDNSServiceErr_NoMemory; }
1169         if (!callBack) hdr->ipc_flags |= IPC_FLAGS_NOREPLY;
1170
1171         put_flags(flags, &ptr);
1172         put_uint32(interfaceIndex, &ptr);
1173         put_string(name, &ptr);
1174         put_string(regtype, &ptr);
1175         put_string(domain, &ptr);
1176         put_string(host, &ptr);
1177         *ptr++ = port.b[0];
1178         *ptr++ = port.b[1];
1179         put_uint16(txtLen, &ptr);
1180         put_rdata(txtLen, txtRecord, &ptr);
1181
1182         err = deliver_request(hdr, *sdRef);             // Will free hdr for us
1183         if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
1184         return err;
1185         }
1186
1187 static void handle_enumeration_response(DNSServiceOp *const sdr, const CallbackHeader *const cbh, const char *data, const char *const end)
1188         {
1189         char domain[kDNSServiceMaxDomainName];
1190         get_string(&data, end, domain, kDNSServiceMaxDomainName);
1191         if (!data) syslog(LOG_WARNING, "dnssd_clientstub handle_enumeration_response: error reading result from daemon");
1192         else ((DNSServiceDomainEnumReply)sdr->AppCallback)(sdr, cbh->cb_flags, cbh->cb_interface, cbh->cb_err, domain, sdr->AppContext);
1193         // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1194         }
1195
1196 DNSServiceErrorType DNSSD_API DNSServiceEnumerateDomains
1197         (
1198         DNSServiceRef             *sdRef,
1199         DNSServiceFlags            flags,
1200         uint32_t                   interfaceIndex,
1201         DNSServiceDomainEnumReply  callBack,
1202         void                      *context
1203         )
1204         {
1205         char *ptr;
1206         size_t len;
1207         ipc_msg_hdr *hdr;
1208         DNSServiceErrorType err;
1209
1210         int f1 = (flags & kDNSServiceFlagsBrowseDomains) != 0;
1211         int f2 = (flags & kDNSServiceFlagsRegistrationDomains) != 0;
1212         if (f1 + f2 != 1) return kDNSServiceErr_BadParam;
1213
1214         err = ConnectToServer(sdRef, flags, enumeration_request, handle_enumeration_response, callBack, context);
1215         if (err) return err;    // On error ConnectToServer leaves *sdRef set to NULL
1216
1217         len = sizeof(DNSServiceFlags);
1218         len += sizeof(uint32_t);
1219
1220         hdr = create_hdr(enumeration_request, &len, &ptr, (*sdRef)->primary ? 1 : 0, *sdRef);
1221         if (!hdr) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; return kDNSServiceErr_NoMemory; }
1222
1223         put_flags(flags, &ptr);
1224         put_uint32(interfaceIndex, &ptr);
1225
1226         err = deliver_request(hdr, *sdRef);             // Will free hdr for us
1227         if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
1228         return err;
1229         }
1230
1231 static void ConnectionResponse(DNSServiceOp *const sdr, const CallbackHeader *const cbh, const char *const data, const char *const end)
1232         {
1233         DNSRecordRef rref = cbh->ipc_hdr.client_context.context;
1234         (void)data; // Unused
1235
1236         //printf("ConnectionResponse got %d\n", cbh->ipc_hdr.op);
1237         if (cbh->ipc_hdr.op != reg_record_reply_op)
1238                 {
1239                 // When using kDNSServiceFlagsShareConnection, need to search the list of associated DNSServiceOps
1240                 // to find the one this response is intended for, and then call through to its ProcessReply handler.
1241                 // We start with our first subordinate DNSServiceRef -- don't want to accidentally match the parent DNSServiceRef.
1242                 DNSServiceOp *op = sdr->next;
1243                 while (op && (op->uid.u32[0] != cbh->ipc_hdr.client_context.u32[0] || op->uid.u32[1] != cbh->ipc_hdr.client_context.u32[1]))
1244                         op = op->next;
1245                 // Note: We may sometimes not find a matching DNSServiceOp, in the case where the client has
1246                 // cancelled the subordinate DNSServiceOp, but there are still messages in the pipeline from the daemon
1247                 if (op && op->ProcessReply) op->ProcessReply(op, cbh, data, end);
1248                 // WARNING: Don't touch op or sdr after this -- client may have called DNSServiceRefDeallocate
1249                 return;
1250                 }
1251
1252         if (sdr->op == connection_request)
1253                 rref->AppCallback(rref->sdr, rref, cbh->cb_flags, cbh->cb_err, rref->AppContext);
1254         else
1255                 {
1256                 syslog(LOG_WARNING, "dnssd_clientstub ConnectionResponse: sdr->op != connection_request");
1257                 rref->AppCallback(rref->sdr, rref, 0, kDNSServiceErr_Unknown, rref->AppContext);
1258                 }
1259         // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1260         }
1261
1262 DNSServiceErrorType DNSSD_API DNSServiceCreateConnection(DNSServiceRef *sdRef)
1263         {
1264         char *ptr;
1265         size_t len = 0;
1266         ipc_msg_hdr *hdr;
1267         DNSServiceErrorType err = ConnectToServer(sdRef, 0, connection_request, ConnectionResponse, NULL, NULL);
1268         if (err) return err;    // On error ConnectToServer leaves *sdRef set to NULL
1269         
1270         hdr = create_hdr(connection_request, &len, &ptr, 0, *sdRef);
1271         if (!hdr) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; return kDNSServiceErr_NoMemory; }
1272
1273         err = deliver_request(hdr, *sdRef);             // Will free hdr for us
1274         if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
1275         return err;
1276         }
1277
1278 DNSServiceErrorType DNSSD_API DNSServiceRegisterRecord
1279         (
1280         DNSServiceRef                  sdRef,
1281         DNSRecordRef                  *RecordRef,
1282         DNSServiceFlags                flags,
1283         uint32_t                       interfaceIndex,
1284         const char                    *fullname,
1285         uint16_t                       rrtype,
1286         uint16_t                       rrclass,
1287         uint16_t                       rdlen,
1288         const void                    *rdata,
1289         uint32_t                       ttl,
1290         DNSServiceRegisterRecordReply  callBack,
1291         void                          *context
1292         )
1293         {
1294         char *ptr;
1295         size_t len;
1296         ipc_msg_hdr *hdr = NULL;
1297         DNSRecordRef rref = NULL;
1298         int f1 = (flags & kDNSServiceFlagsShared) != 0;
1299         int f2 = (flags & kDNSServiceFlagsUnique) != 0;
1300         if (f1 + f2 != 1) return kDNSServiceErr_BadParam;
1301
1302         if (!sdRef) { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRegisterRecord called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam; }
1303
1304         if (!DNSServiceRefValid(sdRef))
1305                 {
1306                 syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRegisterRecord called with invalid DNSServiceRef %p %08X %08X", sdRef, sdRef->sockfd, sdRef->validator);
1307                 return kDNSServiceErr_BadReference;
1308                 }
1309
1310         if (sdRef->op != connection_request)
1311                 {
1312                 syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRegisterRecord called with non-DNSServiceCreateConnection DNSServiceRef %p %d", sdRef, sdRef->op);
1313                 return kDNSServiceErr_BadReference;
1314                 }
1315
1316         *RecordRef = NULL;
1317
1318         len = sizeof(DNSServiceFlags);
1319         len += 2 * sizeof(uint32_t);  // interfaceIndex, ttl
1320         len += 3 * sizeof(uint16_t);  // rrtype, rrclass, rdlen
1321         len += strlen(fullname) + 1;
1322         len += rdlen;
1323
1324         hdr = create_hdr(reg_record_request, &len, &ptr, 1, sdRef);
1325         if (!hdr) return kDNSServiceErr_NoMemory;
1326
1327         put_flags(flags, &ptr);
1328         put_uint32(interfaceIndex, &ptr);
1329         put_string(fullname, &ptr);
1330         put_uint16(rrtype, &ptr);
1331         put_uint16(rrclass, &ptr);
1332         put_uint16(rdlen, &ptr);
1333         put_rdata(rdlen, rdata, &ptr);
1334         put_uint32(ttl, &ptr);
1335
1336         rref = malloc(sizeof(DNSRecord));
1337         if (!rref) { free(hdr); return kDNSServiceErr_NoMemory; }
1338         rref->AppContext = context;
1339         rref->AppCallback = callBack;
1340         rref->record_index = sdRef->max_index++;
1341         rref->sdr = sdRef;
1342         *RecordRef = rref;
1343         hdr->client_context.context = rref;
1344         hdr->reg_index = rref->record_index;
1345
1346         return deliver_request(hdr, sdRef);             // Will free hdr for us
1347         }
1348
1349 // sdRef returned by DNSServiceRegister()
1350 DNSServiceErrorType DNSSD_API DNSServiceAddRecord
1351         (
1352         DNSServiceRef    sdRef,
1353         DNSRecordRef    *RecordRef,
1354         DNSServiceFlags  flags,
1355         uint16_t         rrtype,
1356         uint16_t         rdlen,
1357         const void      *rdata,
1358         uint32_t         ttl
1359         )
1360         {
1361         ipc_msg_hdr *hdr;
1362         size_t len = 0;
1363         char *ptr;
1364         DNSRecordRef rref;
1365
1366         if (!sdRef)     { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceAddRecord called with NULL DNSServiceRef");        return kDNSServiceErr_BadParam; }
1367         if (!RecordRef) { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceAddRecord called with NULL DNSRecordRef pointer"); return kDNSServiceErr_BadParam; }
1368         if (sdRef->op != reg_service_request)
1369                 {
1370                 syslog(LOG_WARNING, "dnssd_clientstub DNSServiceAddRecord called with non-DNSServiceRegister DNSServiceRef %p %d", sdRef, sdRef->op);
1371                 return kDNSServiceErr_BadReference;
1372                 }
1373
1374         if (!DNSServiceRefValid(sdRef))
1375                 {
1376                 syslog(LOG_WARNING, "dnssd_clientstub DNSServiceAddRecord called with invalid DNSServiceRef %p %08X %08X", sdRef, sdRef->sockfd, sdRef->validator);
1377                 return kDNSServiceErr_BadReference;
1378                 }
1379
1380         *RecordRef = NULL;
1381
1382         len += 2 * sizeof(uint16_t);  // rrtype, rdlen
1383         len += rdlen;
1384         len += sizeof(uint32_t);
1385         len += sizeof(DNSServiceFlags);
1386
1387         hdr = create_hdr(add_record_request, &len, &ptr, 1, sdRef);
1388         if (!hdr) return kDNSServiceErr_NoMemory;
1389         put_flags(flags, &ptr);
1390         put_uint16(rrtype, &ptr);
1391         put_uint16(rdlen, &ptr);
1392         put_rdata(rdlen, rdata, &ptr);
1393         put_uint32(ttl, &ptr);
1394
1395         rref = malloc(sizeof(DNSRecord));
1396         if (!rref) { free(hdr); return kDNSServiceErr_NoMemory; }
1397         rref->AppContext = NULL;
1398         rref->AppCallback = NULL;
1399         rref->record_index = sdRef->max_index++;
1400         rref->sdr = sdRef;
1401         *RecordRef = rref;
1402         hdr->reg_index = rref->record_index;
1403
1404         return deliver_request(hdr, sdRef);             // Will free hdr for us
1405         }
1406
1407 // DNSRecordRef returned by DNSServiceRegisterRecord or DNSServiceAddRecord
1408 DNSServiceErrorType DNSSD_API DNSServiceUpdateRecord
1409         (
1410         DNSServiceRef    sdRef,
1411         DNSRecordRef     RecordRef,
1412         DNSServiceFlags  flags,
1413         uint16_t         rdlen,
1414         const void      *rdata,
1415         uint32_t         ttl
1416         )
1417         {
1418         ipc_msg_hdr *hdr;
1419         size_t len = 0;
1420         char *ptr;
1421
1422         if (!sdRef) { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceUpdateRecord called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam; }
1423
1424         if (!DNSServiceRefValid(sdRef))
1425                 {
1426                 syslog(LOG_WARNING, "dnssd_clientstub DNSServiceUpdateRecord called with invalid DNSServiceRef %p %08X %08X", sdRef, sdRef->sockfd, sdRef->validator);
1427                 return kDNSServiceErr_BadReference;
1428                 }
1429
1430         // Note: RecordRef is allowed to be NULL
1431
1432         len += sizeof(uint16_t);
1433         len += rdlen;
1434         len += sizeof(uint32_t);
1435         len += sizeof(DNSServiceFlags);
1436
1437         hdr = create_hdr(update_record_request, &len, &ptr, 1, sdRef);
1438         if (!hdr) return kDNSServiceErr_NoMemory;
1439         hdr->reg_index = RecordRef ? RecordRef->record_index : TXT_RECORD_INDEX;
1440         put_flags(flags, &ptr);
1441         put_uint16(rdlen, &ptr);
1442         put_rdata(rdlen, rdata, &ptr);
1443         put_uint32(ttl, &ptr);
1444         return deliver_request(hdr, sdRef);             // Will free hdr for us
1445         }
1446
1447 DNSServiceErrorType DNSSD_API DNSServiceRemoveRecord
1448         (
1449         DNSServiceRef    sdRef,
1450         DNSRecordRef     RecordRef,
1451         DNSServiceFlags  flags
1452         )
1453         {
1454         ipc_msg_hdr *hdr;
1455         size_t len = 0;
1456         char *ptr;
1457         DNSServiceErrorType err;
1458
1459         if (!sdRef)            { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRemoveRecord called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam; }
1460         if (!RecordRef)        { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRemoveRecord called with NULL DNSRecordRef");  return kDNSServiceErr_BadParam; }
1461         if (!sdRef->max_index) { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRemoveRecord called with bad DNSServiceRef");  return kDNSServiceErr_BadReference; }
1462
1463         if (!DNSServiceRefValid(sdRef))
1464                 {
1465                 syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRemoveRecord called with invalid DNSServiceRef %p %08X %08X", sdRef, sdRef->sockfd, sdRef->validator);
1466                 return kDNSServiceErr_BadReference;
1467                 }
1468
1469         len += sizeof(flags);
1470         hdr = create_hdr(remove_record_request, &len, &ptr, 1, sdRef);
1471         if (!hdr) return kDNSServiceErr_NoMemory;
1472         hdr->reg_index = RecordRef->record_index;
1473         put_flags(flags, &ptr);
1474         err = deliver_request(hdr, sdRef);              // Will free hdr for us
1475         if (!err) free(RecordRef);
1476         return err;
1477         }
1478
1479 DNSServiceErrorType DNSSD_API DNSServiceReconfirmRecord
1480         (
1481         DNSServiceFlags  flags,
1482         uint32_t         interfaceIndex,
1483         const char      *fullname,
1484         uint16_t         rrtype,
1485         uint16_t         rrclass,
1486         uint16_t         rdlen,
1487         const void      *rdata
1488         )
1489         {
1490         char *ptr;
1491         size_t len;
1492         ipc_msg_hdr *hdr;
1493         DNSServiceOp *tmp;
1494
1495         DNSServiceErrorType err = ConnectToServer(&tmp, flags, reconfirm_record_request, NULL, NULL, NULL);
1496         if (err) return err;
1497
1498         len = sizeof(DNSServiceFlags);
1499         len += sizeof(uint32_t);
1500         len += strlen(fullname) + 1;
1501         len += 3 * sizeof(uint16_t);
1502         len += rdlen;
1503         hdr = create_hdr(reconfirm_record_request, &len, &ptr, 0, tmp);
1504         if (!hdr) { DNSServiceRefDeallocate(tmp); return kDNSServiceErr_NoMemory; }
1505
1506         put_flags(flags, &ptr);
1507         put_uint32(interfaceIndex, &ptr);
1508         put_string(fullname, &ptr);
1509         put_uint16(rrtype, &ptr);
1510         put_uint16(rrclass, &ptr);
1511         put_uint16(rdlen, &ptr);
1512         put_rdata(rdlen, rdata, &ptr);
1513
1514         err = deliver_request(hdr, tmp);                // Will free hdr for us
1515         DNSServiceRefDeallocate(tmp);
1516         return err;
1517         }
1518
1519 static void handle_port_mapping_response(DNSServiceOp *const sdr, const CallbackHeader *const cbh, const char *data, const char *const end)
1520         {
1521         union { uint32_t l; u_char b[4]; } addr;
1522         uint8_t protocol;
1523         union { uint16_t s; u_char b[2]; } internalPort;
1524         union { uint16_t s; u_char b[2]; } externalPort;
1525         uint32_t ttl;
1526
1527         if (!data || data + 13 > end) goto fail;
1528
1529         addr        .b[0] = *data++;
1530         addr        .b[1] = *data++;
1531         addr        .b[2] = *data++;
1532         addr        .b[3] = *data++;
1533         protocol          = *data++;
1534         internalPort.b[0] = *data++;
1535         internalPort.b[1] = *data++;
1536         externalPort.b[0] = *data++;
1537         externalPort.b[1] = *data++;
1538         ttl               = get_uint32(&data, end);
1539         if (!data) goto fail;
1540
1541         ((DNSServiceNATPortMappingReply)sdr->AppCallback)(sdr, cbh->cb_flags, cbh->cb_interface, cbh->cb_err, addr.l, protocol, internalPort.s, externalPort.s, ttl, sdr->AppContext);
1542         return;
1543         // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1544
1545 fail:
1546         syslog(LOG_WARNING, "dnssd_clientstub handle_port_mapping_response: error reading result from daemon");
1547         }
1548
1549 DNSServiceErrorType DNSSD_API DNSServiceNATPortMappingCreate
1550         (
1551         DNSServiceRef                       *sdRef,
1552         DNSServiceFlags                     flags,
1553         uint32_t                            interfaceIndex,
1554         uint32_t                            protocol,     /* TCP and/or UDP */
1555         uint16_t                            internalPortInNetworkByteOrder,
1556         uint16_t                            externalPortInNetworkByteOrder,
1557         uint32_t                            ttl,          /* time to live in seconds */
1558         DNSServiceNATPortMappingReply       callBack,
1559         void                                *context      /* may be NULL */
1560         )
1561         {
1562         char *ptr;
1563         size_t len;
1564         ipc_msg_hdr *hdr;
1565         union { uint16_t s; u_char b[2]; } internalPort = { internalPortInNetworkByteOrder };
1566         union { uint16_t s; u_char b[2]; } externalPort = { externalPortInNetworkByteOrder };
1567
1568         DNSServiceErrorType err = ConnectToServer(sdRef, flags, port_mapping_request, handle_port_mapping_response, callBack, context);
1569         if (err) return err;    // On error ConnectToServer leaves *sdRef set to NULL
1570
1571         len = sizeof(flags);
1572         len += sizeof(interfaceIndex);
1573         len += sizeof(protocol);
1574         len += sizeof(internalPort);
1575         len += sizeof(externalPort);
1576         len += sizeof(ttl);
1577
1578         hdr = create_hdr(port_mapping_request, &len, &ptr, (*sdRef)->primary ? 1 : 0, *sdRef);
1579         if (!hdr) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; return kDNSServiceErr_NoMemory; }
1580
1581         put_flags(flags, &ptr);
1582         put_uint32(interfaceIndex, &ptr);
1583         put_uint32(protocol, &ptr);
1584         *ptr++ = internalPort.b[0];
1585         *ptr++ = internalPort.b[1];
1586         *ptr++ = externalPort.b[0];
1587         *ptr++ = externalPort.b[1];
1588         put_uint32(ttl, &ptr);
1589
1590         err = deliver_request(hdr, *sdRef);             // Will free hdr for us
1591         if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
1592         return err;
1593         }