source: rtems-libbsd/mDNSResponder/mDNSShared/dnssd_clientstub.c @ e36ca10

55-freebsd-126-freebsd-12
Last change on this file since e36ca10 was e36ca10, checked in by Sebastian Huber <sebastian.huber@…>, on 09/19/18 at 06:49:34

mDNSResponder: Update to v567

The sources can be obtained via:

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

Update #3522.

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