1 /* -*- Mode: C; tab-width: 4 -*-
3 * Copyright (c) 2003-2015 Apple Inc. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. Neither the name of Apple Inc. ("Apple") nor the names of its
14 * contributors may be used to endorse or promote products derived from this
15 * software without specific prior written permission.
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.
32 #include "dnssd_ipc.h"
34 #if APPLE_OSX_mDNSResponder
35 #include <mach-o/dyld.h>
36 #include <uuid/uuid.h>
37 #include <TargetConditionals.h>
38 #include "dns_sd_internal.h"
44 #include <CommonServices.h>
45 #include <DebugServices.h>
52 #define sockaddr_mdns sockaddr_in
53 #define AF_MDNS AF_INET
55 // Disable warning: "'type cast' : from data pointer 'void *' to function pointer"
56 #pragma warning(disable:4055)
58 // Disable warning: "nonstandard extension, function/data pointer conversion in expression"
59 #pragma warning(disable:4152)
61 extern BOOL
IsSystemServiceDisabled();
63 #define sleep(X) Sleep((X) * 1000)
65 static int g_initWinsock
= 0;
66 #define LOG_WARNING kDebugLevelWarning
67 #define LOG_INFO kDebugLevelInfo
68 static void syslog( int priority
, const char * message
, ...)
73 DWORD err
= WSAGetLastError();
75 va_start( args
, message
);
76 len
= _vscprintf( message
, args
) + 1;
77 buffer
= malloc( len
* sizeof(char) );
78 if ( buffer
) { vsnprintf( buffer
, len
, message
, args
); OutputDebugString( buffer
); free( buffer
); }
79 WSASetLastError( err
);
83 #include <sys/fcntl.h> // For O_RDWR etc.
85 #include <sys/socket.h>
88 #define sockaddr_mdns sockaddr_un
89 #define AF_MDNS AF_LOCAL
93 // <rdar://problem/4096913> Specifies how many times we'll try and connect to the server.
95 #define DNSSD_CLIENT_MAXTRIES 4
97 // Uncomment the line below to use the old error return mechanism of creating a temporary named socket (e.g. in /var/tmp)
98 //#define USE_NAMED_ERROR_RETURN_SOCKET 1
100 // If the UDS client has not received a response from the daemon in 60 secs, it is unlikely to get one
101 // Note: Timeout of 3 secs should be sufficient in normal scenarios, but 60 secs is chosen as a safeguard since
102 // some clients may come up before mDNSResponder itself after a BOOT and on rare ocassions IOPM/Keychain/D2D calls
103 // in mDNSResponder's INIT may take a much longer time to return
104 #define DNSSD_CLIENT_TIMEOUT 60
106 #ifndef CTL_PATH_PREFIX
107 #define CTL_PATH_PREFIX "/var/tmp/dnssd_result_socket."
113 DNSServiceFlags cb_flags
;
114 uint32_t cb_interface
;
115 DNSServiceErrorType cb_err
;
118 typedef struct _DNSServiceRef_t DNSServiceOp
;
119 typedef struct _DNSRecordRef_t DNSRecord
;
124 void *AppCallback
; // Client callback function and context
129 // client stub callback to process message from server and deliver results to client application
130 typedef void (*ProcessReplyFn
)(DNSServiceOp
*const sdr
, const CallbackHeader
*const cbh
, const char *msg
, const char *const end
);
132 #define ValidatorBits 0x12345678
133 #define DNSServiceRefValid(X) (dnssd_SocketValid((X)->sockfd) && (((X)->sockfd ^ (X)->validator) == ValidatorBits))
135 // When using kDNSServiceFlagsShareConnection, there is one primary _DNSServiceOp_t, and zero or more subordinates
136 // For the primary, the 'next' field points to the first subordinate, and its 'next' field points to the next, and so on.
137 // For the primary, the 'primary' field is NULL; for subordinates the 'primary' field points back to the associated primary
139 // _DNS_SD_LIBDISPATCH is defined where libdispatch/GCD is available. This does not mean that the application will use the
140 // DNSServiceSetDispatchQueue API. Hence any new code guarded with _DNS_SD_LIBDISPATCH should still be backwards compatible.
141 struct _DNSServiceRef_t
143 DNSServiceOp
*next
; // For shared connection
144 DNSServiceOp
*primary
; // For shared connection
145 dnssd_sock_t sockfd
; // Connected socket between client and daemon
146 dnssd_sock_t validator
; // Used to detect memory corruption, double disposals, etc.
147 client_context_t uid
; // For shared connection requests, each subordinate DNSServiceRef has its own ID,
148 // unique within the scope of the same shared parent DNSServiceRef
149 uint32_t op
; // request_op_t or reply_op_t
150 uint32_t max_index
; // Largest assigned record index - 0 if no additional records registered
151 uint32_t logcounter
; // Counter used to control number of syslog messages we write
152 int *moreptr
; // Set while DNSServiceProcessResult working on this particular DNSServiceRef
153 ProcessReplyFn ProcessReply
; // Function pointer to the code to handle received messages
154 void *AppCallback
; // Client callback function and context
157 #if _DNS_SD_LIBDISPATCH
158 dispatch_source_t disp_source
;
159 dispatch_queue_t disp_queue
;
164 struct _DNSRecordRef_t
168 DNSServiceRegisterRecordReply AppCallback
;
170 uint32_t record_index
; // index is unique to the ServiceDiscoveryRef
171 client_context_t uid
; // For demultiplexing multiple DNSServiceRegisterRecord calls
175 #if !defined(USE_TCP_LOOPBACK)
176 static void SetUDSPath(struct sockaddr_un
*saddr
, const char *path
)
180 pathLen
= strlen(path
);
181 if (pathLen
< sizeof(saddr
->sun_path
))
182 memcpy(saddr
->sun_path
, path
, pathLen
+ 1);
184 saddr
->sun_path
[0] = '\0';
188 // Write len bytes. Return 0 on success, -1 on error
189 static int write_all(dnssd_sock_t sd
, char *buf
, size_t len
)
191 // Don't use "MSG_WAITALL"; it returns "Invalid argument" on some Linux versions; use an explicit while() loop instead.
192 //if (send(sd, buf, len, MSG_WAITALL) != len) return -1;
195 ssize_t num_written
= send(sd
, buf
, (long)len
, 0);
196 if (num_written
< 0 || (size_t)num_written
> len
)
198 // Check whether socket has gone defunct,
199 // otherwise, an error here indicates some OS bug
200 // or that the mDNSResponder daemon crashed (which should never happen).
201 #if !defined(__ppc__) && defined(SO_ISDEFUNCT)
203 socklen_t dlen
= sizeof (defunct
);
204 if (getsockopt(sd
, SOL_SOCKET
, SO_ISDEFUNCT
, &defunct
, &dlen
) < 0)
205 syslog(LOG_WARNING
, "dnssd_clientstub write_all: SO_ISDEFUNCT failed %d %s", dnssd_errno
, dnssd_strerror(dnssd_errno
));
207 syslog(LOG_WARNING
, "dnssd_clientstub write_all(%d) failed %ld/%ld %d %s", sd
,
208 (long)num_written
, (long)len
,
209 (num_written
< 0) ? dnssd_errno
: 0,
210 (num_written
< 0) ? dnssd_strerror(dnssd_errno
) : "");
212 syslog(LOG_INFO
, "dnssd_clientstub write_all(%d) DEFUNCT", sd
);
214 syslog(LOG_WARNING
, "dnssd_clientstub write_all(%d) failed %ld/%ld %d %s", sd
,
215 (long)num_written
, (long)len
,
216 (num_written
< 0) ? dnssd_errno
: 0,
217 (num_written
< 0) ? dnssd_strerror(dnssd_errno
) : "");
227 enum { read_all_success
= 0, read_all_fail
= -1, read_all_wouldblock
= -2 };
229 // Read len bytes. Return 0 on success, read_all_fail on error, or read_all_wouldblock for
230 static int read_all(dnssd_sock_t sd
, char *buf
, int len
)
232 // Don't use "MSG_WAITALL"; it returns "Invalid argument" on some Linux versions; use an explicit while() loop instead.
233 //if (recv(sd, buf, len, MSG_WAITALL) != len) return -1;
237 ssize_t num_read
= recv(sd
, buf
, len
, 0);
238 // It is valid to get an interrupted system call error e.g., somebody attaching
239 // in a debugger, retry without failing
240 if ((num_read
< 0) && (errno
== EINTR
))
242 syslog(LOG_INFO
, "dnssd_clientstub read_all: EINTR continue");
245 if ((num_read
== 0) || (num_read
< 0) || (num_read
> len
))
250 // Check whether socket has gone defunct,
251 // otherwise, an error here indicates some OS bug
252 // or that the mDNSResponder daemon crashed (which should never happen).
254 // <rdar://problem/7481776> Suppress logs for "A non-blocking socket operation
255 // could not be completed immediately"
256 if (WSAGetLastError() != WSAEWOULDBLOCK
)
259 #if !defined(__ppc__) && defined(SO_ISDEFUNCT)
261 socklen_t dlen
= sizeof (defunct
);
262 if (getsockopt(sd
, SOL_SOCKET
, SO_ISDEFUNCT
, &defunct
, &dlen
) < 0)
263 syslog(LOG_WARNING
, "dnssd_clientstub read_all: SO_ISDEFUNCT failed %d %s", dnssd_errno
, dnssd_strerror(dnssd_errno
));
269 syslog(LOG_WARNING
, "dnssd_clientstub read_all(%d) failed %ld/%ld %d %s", sd
,
270 (long)num_read
, (long)len
,
271 (num_read
< 0) ? dnssd_errno
: 0,
272 (num_read
< 0) ? dnssd_strerror(dnssd_errno
) : "");
274 syslog(LOG_INFO
, "dnssd_clientstub read_all(%d) DEFUNCT", sd
);
275 return (num_read
< 0 && dnssd_errno
== dnssd_EWOULDBLOCK
) ? read_all_wouldblock
: read_all_fail
;
280 return read_all_success
;
283 // Returns 1 if more bytes remain to be read on socket descriptor sd, 0 otherwise
284 static int more_bytes(dnssd_sock_t sd
)
286 struct timeval tv
= { 0, 0 };
295 ret
= select((int)sd
+1, fs
, (fd_set
*)NULL
, (fd_set
*)NULL
, &tv
);
304 // Compute the number of integers needed for storing "sd". Internally fd_set is stored
305 // as an array of ints with one bit for each fd and hence we need to compute
306 // the number of ints needed rather than the number of bytes. If "sd" is 32, we need
307 // two ints and not just one.
308 int nfdbits
= sizeof (int) * 8;
309 int nints
= (sd
/nfdbits
) + 1;
310 fs
= (fd_set
*)calloc(nints
, (size_t)sizeof(int));
313 syslog(LOG_WARNING
, "dnssd_clientstub more_bytes: malloc failed");
318 ret
= select((int)sd
+1, fs
, (fd_set
*)NULL
, (fd_set
*)NULL
, &tv
);
325 // set_waitlimit() implements a timeout using select. It is called from deliver_request() before recv() OR accept()
326 // to ensure the UDS clients are not blocked in these system calls indefinitely.
327 // Note: Ideally one should never be blocked here, because it indicates either mDNSResponder daemon is not yet up/hung/
328 // superbusy/crashed or some other OS bug. For eg: On Windows which suffers from 3rd party software
329 // (primarily 3rd party firewall software) interfering with proper functioning of the TCP protocol stack it is possible
330 // the next operation on this socket(recv/accept) is blocked since we depend on TCP to communicate with the system service.
331 static int set_waitlimit(dnssd_sock_t sock
, int timeout
)
333 int gDaemonErr
= kDNSServiceErr_NoError
;
335 // To prevent stack corruption since select does not work with timeout if fds > FD_SETSIZE(1024)
336 if (!gDaemonErr
&& sock
< FD_SETSIZE
)
345 if (!select((int)(sock
+ 1), &set
, NULL
, NULL
, &tv
))
347 // Ideally one should never hit this case: See comments before set_waitlimit()
348 syslog(LOG_WARNING
, "dnssd_clientstub set_waitlimit:_daemon timed out (%d secs) without any response: Socket %d", timeout
, sock
);
349 gDaemonErr
= kDNSServiceErr_Timeout
;
357 * allocate and initialize an ipc message header. Value of len should initially be the
358 * length of the data, and is set to the value of the data plus the header. data_start
359 * is set to point to the beginning of the data section. SeparateReturnSocket should be
360 * non-zero for calls that can't receive an immediate error return value on their primary
361 * socket, and therefore require a separate return path for the error code result.
362 * if zero, the path to a control socket is appended at the beginning of the message buffer.
363 * data_start is set past this string.
365 static ipc_msg_hdr
*create_hdr(uint32_t op
, size_t *len
, char **data_start
, int SeparateReturnSocket
, DNSServiceOp
*ref
)
370 #if !defined(USE_TCP_LOOPBACK)
371 char ctrl_path
[64] = ""; // "/var/tmp/dnssd_result_socket.xxxxxxxxxx-xxx-xxxxxx"
374 if (SeparateReturnSocket
)
376 #if defined(USE_TCP_LOOPBACK)
377 *len
+= 2; // Allocate space for two-byte port number
378 #elif defined(USE_NAMED_ERROR_RETURN_SOCKET)
380 if (gettimeofday(&tv
, NULL
) < 0)
381 { syslog(LOG_WARNING
, "dnssd_clientstub create_hdr: gettimeofday failed %d %s", dnssd_errno
, dnssd_strerror(dnssd_errno
)); return NULL
; }
382 snprintf(ctrl_path
, sizeof(ctrl_path
), "%s%d-%.3lx-%.6lu", CTL_PATH_PREFIX
, (int)getpid(),
383 (unsigned long)(tv
.tv_sec
& 0xFFF), (unsigned long)(tv
.tv_usec
));
384 *len
+= strlen(ctrl_path
) + 1;
386 *len
+= 1; // Allocate space for single zero byte (empty C string)
390 datalen
= (int) *len
;
391 *len
+= sizeof(ipc_msg_hdr
);
393 // Write message to buffer
395 if (!msg
) { syslog(LOG_WARNING
, "dnssd_clientstub create_hdr: malloc failed"); return NULL
; }
397 memset(msg
, 0, *len
);
398 hdr
= (ipc_msg_hdr
*)msg
;
399 hdr
->version
= VERSION
;
400 hdr
->datalen
= datalen
;
403 hdr
->client_context
= ref
->uid
;
405 *data_start
= msg
+ sizeof(ipc_msg_hdr
);
406 #if defined(USE_TCP_LOOPBACK)
407 // Put dummy data in for the port, since we don't know what it is yet.
408 // The data will get filled in before we send the message. This happens in deliver_request().
409 if (SeparateReturnSocket
) put_uint16(0, data_start
);
411 if (SeparateReturnSocket
) put_string(ctrl_path
, data_start
);
416 static void FreeDNSRecords(DNSServiceOp
*sdRef
)
418 DNSRecord
*rec
= sdRef
->rec
;
421 DNSRecord
*next
= rec
->recnext
;
427 static void FreeDNSServiceOp(DNSServiceOp
*x
)
429 // We don't use our DNSServiceRefValid macro here because if we're cleaning up after a socket() call failed
430 // then sockfd could legitimately contain a failing value (e.g. dnssd_InvalidSocket)
431 if ((x
->sockfd
^ x
->validator
) != ValidatorBits
)
433 static DNSServiceOp
*op_were_not_going_to_free_but_we_need_to_fool_the_analyzer
;
434 syslog(LOG_WARNING
, "dnssd_clientstub attempt to dispose invalid DNSServiceRef %p %08X %08X", x
, x
->sockfd
, x
->validator
);
435 op_were_not_going_to_free_but_we_need_to_fool_the_analyzer
= x
;
441 x
->sockfd
= dnssd_InvalidSocket
;
442 x
->validator
= 0xDDDDDDDD;
443 x
->op
= request_op_none
;
447 x
->ProcessReply
= NULL
;
448 x
->AppCallback
= NULL
;
449 x
->AppContext
= NULL
;
450 #if _DNS_SD_LIBDISPATCH
451 if (x
->disp_source
) dispatch_release(x
->disp_source
);
452 x
->disp_source
= NULL
;
453 x
->disp_queue
= NULL
;
455 // DNSRecords may have been added to subordinate sdRef e.g., DNSServiceRegister/DNSServiceAddRecord
456 // or on the main sdRef e.g., DNSServiceCreateConnection/DNSServiceRegisterRecord.
457 // DNSRecords may have been freed if the application called DNSRemoveRecord.
468 // Return a connected service ref (deallocate with DNSServiceRefDeallocate)
469 static DNSServiceErrorType
ConnectToServer(DNSServiceRef
*ref
, DNSServiceFlags flags
, uint32_t op
, ProcessReplyFn ProcessReply
, void *AppCallback
, void *AppContext
)
473 dnssd_sockaddr_t saddr
;
478 syslog(LOG_WARNING
, "dnssd_clientstub DNSService operation with NULL DNSServiceRef");
479 return kDNSServiceErr_BadParam
;
482 if (flags
& kDNSServiceFlagsShareConnection
)
486 syslog(LOG_WARNING
, "dnssd_clientstub kDNSServiceFlagsShareConnection used with NULL DNSServiceRef");
487 return kDNSServiceErr_BadParam
;
489 if (!DNSServiceRefValid(*ref
) || ((*ref
)->op
!= connection_request
&& (*ref
)->op
!= connection_delegate_request
) || (*ref
)->primary
)
491 syslog(LOG_WARNING
, "dnssd_clientstub kDNSServiceFlagsShareConnection used with invalid DNSServiceRef %p %08X %08X op %d",
492 (*ref
), (*ref
)->sockfd
, (*ref
)->validator
, (*ref
)->op
);
494 return kDNSServiceErr_BadReference
;
503 if (WSAStartup(MAKEWORD(2,2), &wsaData
) != 0) { *ref
= NULL
; return kDNSServiceErr_ServiceNotRunning
; }
505 // <rdar://problem/4096913> If the system service is disabled, we only want to try to connect once
506 if (IsSystemServiceDisabled())
507 NumTries
= DNSSD_CLIENT_MAXTRIES
;
510 sdr
= malloc(sizeof(DNSServiceOp
));
513 syslog(LOG_WARNING
, "dnssd_clientstub ConnectToServer: malloc failed");
515 return kDNSServiceErr_NoMemory
;
519 sdr
->sockfd
= dnssd_InvalidSocket
;
520 sdr
->validator
= sdr
->sockfd
^ ValidatorBits
;
527 sdr
->ProcessReply
= ProcessReply
;
528 sdr
->AppCallback
= AppCallback
;
529 sdr
->AppContext
= AppContext
;
531 #if _DNS_SD_LIBDISPATCH
532 sdr
->disp_source
= NULL
;
533 sdr
->disp_queue
= NULL
;
535 sdr
->kacontext
= NULL
;
537 if (flags
& kDNSServiceFlagsShareConnection
)
539 DNSServiceOp
**p
= &(*ref
)->next
; // Append ourselves to end of primary's list
543 // Preincrement counter before we use it -- it helps with debugging if we know the all-zeroes ID should never appear
544 if (++(*ref
)->uid
.u32
[0] == 0)
545 ++(*ref
)->uid
.u32
[1]; // In parent DNSServiceOp increment UID counter
546 sdr
->primary
= *ref
; // Set our primary pointer
547 sdr
->sockfd
= (*ref
)->sockfd
; // Inherit primary's socket
548 sdr
->validator
= (*ref
)->validator
;
549 sdr
->uid
= (*ref
)->uid
;
550 //printf("ConnectToServer sharing socket %d\n", sdr->sockfd);
555 const unsigned long optval
= 1;
557 #ifndef USE_TCP_LOOPBACK
558 char* uds_serverpath
= getenv(MDNS_UDS_SERVERPATH_ENVVAR
);
559 if (uds_serverpath
== NULL
)
560 uds_serverpath
= MDNS_UDS_SERVERPATH
;
561 else if (strlen(uds_serverpath
) >= MAX_CTLPATH
)
563 uds_serverpath
= MDNS_UDS_SERVERPATH
;
564 syslog(LOG_WARNING
, "dnssd_clientstub ConnectToServer: using default path since env len is invalid");
568 sdr
->sockfd
= socket(AF_DNSSD
, SOCK_STREAM
, 0);
569 sdr
->validator
= sdr
->sockfd
^ ValidatorBits
;
570 if (!dnssd_SocketValid(sdr
->sockfd
))
572 syslog(LOG_WARNING
, "dnssd_clientstub ConnectToServer: socket failed %d %s", dnssd_errno
, dnssd_strerror(dnssd_errno
));
573 FreeDNSServiceOp(sdr
);
574 return kDNSServiceErr_NoMemory
;
577 // Some environments (e.g. OS X) support turning off SIGPIPE for a socket
578 if (setsockopt(sdr
->sockfd
, SOL_SOCKET
, SO_NOSIGPIPE
, &optval
, sizeof(optval
)) < 0)
579 syslog(LOG_WARNING
, "dnssd_clientstub ConnectToServer: SO_NOSIGPIPE failed %d %s", dnssd_errno
, dnssd_strerror(dnssd_errno
));
581 #if defined(USE_TCP_LOOPBACK)
582 saddr
.sin_family
= AF_INET
;
583 saddr
.sin_addr
.s_addr
= inet_addr(MDNS_TCP_SERVERADDR
);
584 saddr
.sin_port
= htons(MDNS_TCP_SERVERPORT
);
586 saddr
.sun_family
= AF_LOCAL
;
587 SetUDSPath(&saddr
, uds_serverpath
);
588 #if !defined(__ppc__) && defined(SO_DEFUNCTOK)
591 if (setsockopt(sdr
->sockfd
, SOL_SOCKET
, SO_DEFUNCTOK
, &defunct
, sizeof(defunct
)) < 0)
592 syslog(LOG_WARNING
, "dnssd_clientstub ConnectToServer: SO_DEFUNCTOK failed %d %s", dnssd_errno
, dnssd_strerror(dnssd_errno
));
599 int err
= connect(sdr
->sockfd
, (struct sockaddr
*) &saddr
, sizeof(saddr
));
601 break; // If we succeeded, return sdr
602 // If we failed, then it may be because the daemon is still launching.
603 // This can happen for processes that launch early in the boot process, while the
604 // daemon is still coming up. Rather than fail here, we wait 1 sec and try again.
605 // If, after DNSSD_CLIENT_MAXTRIES, we still can't connect to the daemon,
606 // then we give up and return a failure code.
607 if (++NumTries
< DNSSD_CLIENT_MAXTRIES
)
609 syslog(LOG_WARNING
, "dnssd_clientstub ConnectToServer: connect()-> No of tries: %d", NumTries
);
610 sleep(1); // Sleep a bit, then try again
614 #if !defined(USE_TCP_LOOPBACK)
615 syslog(LOG_WARNING
, "dnssd_clientstub ConnectToServer: connect() failed path:%s Socket:%d Err:%d Errno:%d %s",
616 uds_serverpath
, sdr
->sockfd
, err
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
618 dnssd_close(sdr
->sockfd
);
619 FreeDNSServiceOp(sdr
);
620 return kDNSServiceErr_ServiceNotRunning
;
623 //printf("ConnectToServer opened socket %d\n", sdr->sockfd);
627 return kDNSServiceErr_NoError
;
630 #define deliver_request_bailout(MSG) \
631 do { syslog(LOG_WARNING, "dnssd_clientstub deliver_request: %s failed %d (%s)", (MSG), dnssd_errno, dnssd_strerror(dnssd_errno)); goto cleanup; } while(0)
633 static DNSServiceErrorType
deliver_request(ipc_msg_hdr
*hdr
, DNSServiceOp
*sdr
)
636 dnssd_sock_t listenfd
= dnssd_InvalidSocket
, errsd
= dnssd_InvalidSocket
;
637 DNSServiceErrorType err
= kDNSServiceErr_Unknown
; // Default for the "goto cleanup" cases
638 int MakeSeparateReturnSocket
;
639 #if defined(USE_TCP_LOOPBACK) || defined(USE_NAMED_ERROR_RETURN_SOCKET)
645 syslog(LOG_WARNING
, "dnssd_clientstub deliver_request: !hdr");
646 return kDNSServiceErr_Unknown
;
649 datalen
= hdr
->datalen
; // We take a copy here because we're going to convert hdr->datalen to network byte order
650 #if defined(USE_TCP_LOOPBACK) || defined(USE_NAMED_ERROR_RETURN_SOCKET)
651 data
= (char *)hdr
+ sizeof(ipc_msg_hdr
);
654 // Note: need to check hdr->op, not sdr->op.
655 // hdr->op contains the code for the specific operation we're currently doing, whereas sdr->op
656 // contains the original parent DNSServiceOp (e.g. for an add_record_request, hdr->op will be
657 // add_record_request but the parent sdr->op will be connection_request or reg_service_request)
658 MakeSeparateReturnSocket
= (sdr
->primary
||
659 hdr
->op
== reg_record_request
|| hdr
->op
== add_record_request
|| hdr
->op
== update_record_request
|| hdr
->op
== remove_record_request
);
661 if (!DNSServiceRefValid(sdr
))
665 syslog(LOG_WARNING
, "dnssd_clientstub deliver_request: invalid DNSServiceRef %p %08X %08X", sdr
, sdr
->sockfd
, sdr
->validator
);
666 return kDNSServiceErr_BadReference
;
669 if (MakeSeparateReturnSocket
)
671 #if defined(USE_TCP_LOOPBACK)
673 union { uint16_t s
; u_char b
[2]; } port
;
674 dnssd_sockaddr_t caddr
;
675 dnssd_socklen_t len
= (dnssd_socklen_t
) sizeof(caddr
);
676 listenfd
= socket(AF_DNSSD
, SOCK_STREAM
, 0);
677 if (!dnssd_SocketValid(listenfd
)) deliver_request_bailout("TCP socket");
679 caddr
.sin_family
= AF_INET
;
681 caddr
.sin_addr
.s_addr
= inet_addr(MDNS_TCP_SERVERADDR
);
682 if (bind(listenfd
, (struct sockaddr
*) &caddr
, sizeof(caddr
)) < 0) deliver_request_bailout("TCP bind");
683 if (getsockname(listenfd
, (struct sockaddr
*) &caddr
, &len
) < 0) deliver_request_bailout("TCP getsockname");
684 if (listen(listenfd
, 1) < 0) deliver_request_bailout("TCP listen");
685 port
.s
= caddr
.sin_port
;
686 data
[0] = port
.b
[0]; // don't switch the byte order, as the
687 data
[1] = port
.b
[1]; // daemon expects it in network byte order
689 #elif defined(USE_NAMED_ERROR_RETURN_SOCKET)
693 dnssd_sockaddr_t caddr
;
694 listenfd
= socket(AF_DNSSD
, SOCK_STREAM
, 0);
695 if (!dnssd_SocketValid(listenfd
)) deliver_request_bailout("USE_NAMED_ERROR_RETURN_SOCKET socket");
697 caddr
.sun_family
= AF_LOCAL
;
698 // According to Stevens (section 3.2), there is no portable way to
699 // determine whether sa_len is defined on a particular platform.
700 #ifndef NOT_HAVE_SA_LEN
701 caddr
.sun_len
= sizeof(struct sockaddr_un
);
703 SetUDSPath(&caddr
, data
);
705 bindresult
= bind(listenfd
, (struct sockaddr
*)&caddr
, sizeof(caddr
));
707 if (bindresult
< 0) deliver_request_bailout("USE_NAMED_ERROR_RETURN_SOCKET bind");
708 if (listen(listenfd
, 1) < 0) deliver_request_bailout("USE_NAMED_ERROR_RETURN_SOCKET listen");
713 if (socketpair(AF_DNSSD
, SOCK_STREAM
, 0, sp
) < 0) deliver_request_bailout("socketpair");
716 errsd
= sp
[0]; // We'll read our four-byte error code from sp[0]
717 listenfd
= sp
[1]; // We'll send sp[1] to the daemon
718 #if !defined(__ppc__) && defined(SO_DEFUNCTOK)
721 if (setsockopt(errsd
, SOL_SOCKET
, SO_DEFUNCTOK
, &defunct
, sizeof(defunct
)) < 0)
722 syslog(LOG_WARNING
, "dnssd_clientstub ConnectToServer: SO_DEFUNCTOK failed %d %s", dnssd_errno
, dnssd_strerror(dnssd_errno
));
730 #if !defined(USE_TCP_LOOPBACK) && !defined(USE_NAMED_ERROR_RETURN_SOCKET)
731 // If we're going to make a separate error return socket, and pass it to the daemon
732 // using sendmsg, then we'll hold back one data byte to go with it.
733 // On some versions of Unix (including Leopard) sending a control message without
734 // any associated data does not work reliably -- e.g. one particular issue we ran
735 // into is that if the receiving program is in a kqueue loop waiting to be notified
736 // of the received message, it doesn't get woken up when the control message arrives.
737 if (MakeSeparateReturnSocket
|| sdr
->op
== send_bpf
)
738 datalen
--; // Okay to use sdr->op when checking for op == send_bpf
741 // At this point, our listening socket is set up and waiting, if necessary, for the daemon to connect back to
742 ConvertHeaderBytes(hdr
);
743 //syslog(LOG_WARNING, "dnssd_clientstub deliver_request writing %lu bytes", (unsigned long)(datalen + sizeof(ipc_msg_hdr)));
744 //if (MakeSeparateReturnSocket) syslog(LOG_WARNING, "dnssd_clientstub deliver_request name is %s", data);
745 #if TEST_SENDING_ONE_BYTE_AT_A_TIME
747 for (i
=0; i
<datalen
+ sizeof(ipc_msg_hdr
); i
++)
749 syslog(LOG_WARNING
, "dnssd_clientstub deliver_request writing %d", i
);
750 if (write_all(sdr
->sockfd
, ((char *)hdr
)+i
, 1) < 0)
751 { syslog(LOG_WARNING
, "write_all (byte %u) failed", i
); goto cleanup
; }
755 if (write_all(sdr
->sockfd
, (char *)hdr
, datalen
+ sizeof(ipc_msg_hdr
)) < 0)
757 // write_all already prints an error message if there is an error writing to
758 // the socket except for DEFUNCT. Logging here is unnecessary and also wrong
759 // in the case of DEFUNCT sockets
760 syslog(LOG_INFO
, "dnssd_clientstub deliver_request ERROR: write_all(%d, %lu bytes) failed",
761 sdr
->sockfd
, (unsigned long)(datalen
+ sizeof(ipc_msg_hdr
)));
766 if (!MakeSeparateReturnSocket
)
768 if (MakeSeparateReturnSocket
|| sdr
->op
== send_bpf
) // Okay to use sdr->op when checking for op == send_bpf
770 #if defined(USE_TCP_LOOPBACK) || defined(USE_NAMED_ERROR_RETURN_SOCKET)
771 // At this point we may wait in accept for a few milliseconds waiting for the daemon to connect back to us,
772 // but that's okay -- the daemon should not take more than a few milliseconds to respond.
773 // set_waitlimit() ensures we do not block indefinitely just in case something is wrong
774 dnssd_sockaddr_t daddr
;
775 dnssd_socklen_t len
= sizeof(daddr
);
776 if ((err
= set_waitlimit(listenfd
, DNSSD_CLIENT_TIMEOUT
)) != kDNSServiceErr_NoError
)
778 errsd
= accept(listenfd
, (struct sockaddr
*)&daddr
, &len
);
779 if (!dnssd_SocketValid(errsd
))
780 deliver_request_bailout("accept");
783 struct iovec vec
= { ((char *)hdr
) + sizeof(ipc_msg_hdr
) + datalen
, 1 }; // Send the last byte along with the SCM_RIGHTS
785 struct cmsghdr
*cmsg
;
786 char cbuf
[CMSG_SPACE(4 * sizeof(dnssd_sock_t
))];
793 if (MakeSeparateReturnSocket
|| sdr
->op
== send_bpf
) // Okay to use sdr->op when checking for op == send_bpf
795 if (sdr
->op
== send_bpf
)
798 char p
[12]; // Room for "/dev/bpf999" with terminating null
799 for (i
=0; i
<100; i
++)
801 snprintf(p
, sizeof(p
), "/dev/bpf%d", i
);
802 listenfd
= open(p
, O_RDWR
, 0);
803 //if (dnssd_SocketValid(listenfd)) syslog(LOG_WARNING, "Sending fd %d for %s", listenfd, p);
804 if (!dnssd_SocketValid(listenfd
) && dnssd_errno
!= EBUSY
)
805 syslog(LOG_WARNING
, "Error opening %s %d (%s)", p
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
806 if (dnssd_SocketValid(listenfd
) || dnssd_errno
!= EBUSY
) break;
809 msg
.msg_control
= cbuf
;
810 msg
.msg_controllen
= CMSG_LEN(sizeof(dnssd_sock_t
));
812 cmsg
= CMSG_FIRSTHDR(&msg
);
813 cmsg
->cmsg_len
= CMSG_LEN(sizeof(dnssd_sock_t
));
814 cmsg
->cmsg_level
= SOL_SOCKET
;
815 cmsg
->cmsg_type
= SCM_RIGHTS
;
816 *((dnssd_sock_t
*)CMSG_DATA(cmsg
)) = listenfd
;
819 #if TEST_KQUEUE_CONTROL_MESSAGE_BUG
823 #if DEBUG_64BIT_SCM_RIGHTS
824 syslog(LOG_WARNING
, "dnssd_clientstub sendmsg read sd=%d write sd=%d %ld %ld %ld/%ld/%ld/%ld",
825 errsd
, listenfd
, sizeof(dnssd_sock_t
), sizeof(void*),
826 sizeof(struct cmsghdr
) + sizeof(dnssd_sock_t
),
827 CMSG_LEN(sizeof(dnssd_sock_t
)), (long)CMSG_SPACE(sizeof(dnssd_sock_t
)),
828 (long)((char*)CMSG_DATA(cmsg
) + 4 - cbuf
));
829 #endif // DEBUG_64BIT_SCM_RIGHTS
831 if (sendmsg(sdr
->sockfd
, &msg
, 0) < 0)
833 syslog(LOG_WARNING
, "dnssd_clientstub deliver_request ERROR: sendmsg failed read sd=%d write sd=%d errno %d (%s)",
834 errsd
, listenfd
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
835 err
= kDNSServiceErr_Incompatible
;
839 #if DEBUG_64BIT_SCM_RIGHTS
840 syslog(LOG_WARNING
, "dnssd_clientstub sendmsg read sd=%d write sd=%d okay", errsd
, listenfd
);
841 #endif // DEBUG_64BIT_SCM_RIGHTS
844 // Close our end of the socketpair *before* calling read_all() to get the four-byte error code.
845 // Otherwise, if the daemon closes our socket (or crashes), we will have to wait for a timeout
846 // in read_all() because the socket is not closed (we still have an open reference to it)
847 // Note: listenfd is overwritten in the case of send_bpf above and that will be closed here
848 // for send_bpf operation.
849 dnssd_close(listenfd
);
850 listenfd
= dnssd_InvalidSocket
; // Make sure we don't close it a second time in the cleanup handling below
853 // At this point we may wait in read_all for a few milliseconds waiting for the daemon to send us the error code,
854 // but that's okay -- the daemon should not take more than a few milliseconds to respond.
855 // set_waitlimit() ensures we do not block indefinitely just in case something is wrong
856 if (sdr
->op
== send_bpf
) // Okay to use sdr->op when checking for op == send_bpf
857 err
= kDNSServiceErr_NoError
;
858 else if ((err
= set_waitlimit(errsd
, DNSSD_CLIENT_TIMEOUT
)) == kDNSServiceErr_NoError
)
860 if (read_all(errsd
, (char*)&err
, (int)sizeof(err
)) < 0)
861 err
= kDNSServiceErr_ServiceNotRunning
; // On failure read_all will have written a message to syslog for us
865 //syslog(LOG_WARNING, "dnssd_clientstub deliver_request: retrieved error code %d", err);
868 if (MakeSeparateReturnSocket
)
870 if (dnssd_SocketValid(listenfd
)) dnssd_close(listenfd
);
871 if (dnssd_SocketValid(errsd
)) dnssd_close(errsd
);
872 #if defined(USE_NAMED_ERROR_RETURN_SOCKET)
873 // syslog(LOG_WARNING, "dnssd_clientstub deliver_request: removing UDS: %s", data);
874 if (unlink(data
) != 0)
875 syslog(LOG_WARNING
, "dnssd_clientstub WARNING: unlink(\"%s\") failed errno %d (%s)", data
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
876 // else syslog(LOG_WARNING, "dnssd_clientstub deliver_request: removed UDS: %s", data);
884 dnssd_sock_t DNSSD_API
DNSServiceRefSockFD(DNSServiceRef sdRef
)
886 if (!sdRef
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRefSockFD called with NULL DNSServiceRef"); return dnssd_InvalidSocket
; }
888 if (!DNSServiceRefValid(sdRef
))
890 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRefSockFD called with invalid DNSServiceRef %p %08X %08X",
891 sdRef
, sdRef
->sockfd
, sdRef
->validator
);
892 return dnssd_InvalidSocket
;
897 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRefSockFD undefined for kDNSServiceFlagsShareConnection subordinate DNSServiceRef %p", sdRef
);
898 return dnssd_InvalidSocket
;
901 return sdRef
->sockfd
;
904 #if _DNS_SD_LIBDISPATCH
905 static void CallbackWithError(DNSServiceRef sdRef
, DNSServiceErrorType error
)
907 DNSServiceOp
*sdr
= sdRef
;
908 DNSServiceOp
*sdrNext
;
915 // We can't touch the sdr after the callback as it can be deallocated in the callback
918 sdr
->moreptr
= &morebytes
;
921 case resolve_request
:
922 if (sdr
->AppCallback
) ((DNSServiceResolveReply
) sdr
->AppCallback
)(sdr
, 0, 0, error
, NULL
, 0, 0, 0, NULL
, sdr
->AppContext
);
925 if (sdr
->AppCallback
) ((DNSServiceQueryRecordReply
)sdr
->AppCallback
)(sdr
, 0, 0, error
, NULL
, 0, 0, 0, NULL
, 0, sdr
->AppContext
);
927 case addrinfo_request
:
928 if (sdr
->AppCallback
) ((DNSServiceGetAddrInfoReply
)sdr
->AppCallback
)(sdr
, 0, 0, error
, NULL
, NULL
, 0, sdr
->AppContext
);
931 if (sdr
->AppCallback
) ((DNSServiceBrowseReply
) sdr
->AppCallback
)(sdr
, 0, 0, error
, NULL
, 0, NULL
, sdr
->AppContext
);
933 case reg_service_request
:
934 if (sdr
->AppCallback
) ((DNSServiceRegisterReply
) sdr
->AppCallback
)(sdr
, 0, error
, NULL
, 0, NULL
, sdr
->AppContext
);
936 case enumeration_request
:
937 if (sdr
->AppCallback
) ((DNSServiceDomainEnumReply
) sdr
->AppCallback
)(sdr
, 0, 0, error
, NULL
, sdr
->AppContext
);
939 case connection_request
:
940 case connection_delegate_request
:
941 // This means Register Record, walk the list of DNSRecords to do the callback
945 recnext
= rec
->recnext
;
946 if (rec
->AppCallback
) ((DNSServiceRegisterRecordReply
)rec
->AppCallback
)(sdr
, 0, 0, error
, rec
->AppContext
);
947 // The Callback can call DNSServiceRefDeallocate which in turn frees sdr and all the records.
948 // Detect that and return early
949 if (!morebytes
) {syslog(LOG_WARNING
, "dnssdclientstub:Record: CallbackwithError morebytes zero"); return;}
953 case port_mapping_request
:
954 if (sdr
->AppCallback
) ((DNSServiceNATPortMappingReply
)sdr
->AppCallback
)(sdr
, 0, 0, error
, 0, 0, 0, 0, 0, sdr
->AppContext
);
957 syslog(LOG_WARNING
, "dnssd_clientstub CallbackWithError called with bad op %d", sdr
->op
);
959 // If DNSServiceRefDeallocate was called in the callback, morebytes will be zero. As the sdRef
960 // (and its subordinates) have been freed, we should not proceed further. Note that when we
961 // call the callback with a subordinate sdRef the application can call DNSServiceRefDeallocate
962 // on the main sdRef and DNSServiceRefDeallocate handles this case by walking all the sdRefs and
963 // clears the moreptr so that we can terminate here.
965 // If DNSServiceRefDeallocate was not called in the callback, then set moreptr to NULL so that
966 // we don't access the stack variable after we return from this function.
967 if (!morebytes
) {syslog(LOG_WARNING
, "dnssdclientstub:sdRef: CallbackwithError morebytes zero sdr %p", sdr
); return;}
968 else {sdr
->moreptr
= NULL
;}
972 #endif // _DNS_SD_LIBDISPATCH
974 // Handle reply from server, calling application client callback. If there is no reply
975 // from the daemon on the socket contained in sdRef, the call will block.
976 DNSServiceErrorType DNSSD_API
DNSServiceProcessResult(DNSServiceRef sdRef
)
980 if (!sdRef
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceProcessResult called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam
; }
982 if (!DNSServiceRefValid(sdRef
))
984 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceProcessResult called with invalid DNSServiceRef %p %08X %08X", sdRef
, sdRef
->sockfd
, sdRef
->validator
);
985 return kDNSServiceErr_BadReference
;
990 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceProcessResult undefined for kDNSServiceFlagsShareConnection subordinate DNSServiceRef %p", sdRef
);
991 return kDNSServiceErr_BadReference
;
994 if (!sdRef
->ProcessReply
)
996 static int num_logs
= 0;
997 if (num_logs
< 10) syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceProcessResult called with DNSServiceRef with no ProcessReply function");
998 if (num_logs
< 1000) num_logs
++;else sleep(1);
999 return kDNSServiceErr_BadReference
;
1007 // return NoError on EWOULDBLOCK. This will handle the case
1008 // where a non-blocking socket is told there is data, but it was a false positive.
1009 // On error, read_all will write a message to syslog for us, so don't need to duplicate that here
1010 // Note: If we want to properly support using non-blocking sockets in the future
1011 int result
= read_all(sdRef
->sockfd
, (void *)&cbh
.ipc_hdr
, sizeof(cbh
.ipc_hdr
));
1012 if (result
== read_all_fail
)
1014 // Set the ProcessReply to NULL before callback as the sdRef can get deallocated
1016 sdRef
->ProcessReply
= NULL
;
1017 #if _DNS_SD_LIBDISPATCH
1018 // Call the callbacks with an error if using the dispatch API, as DNSServiceProcessResult
1019 // is not called by the application and hence need to communicate the error. Cancel the
1020 // source so that we don't get any more events
1021 // Note: read_all fails if we could not read from the daemon which can happen if the
1022 // daemon dies or the file descriptor is disconnected (defunct).
1023 if (sdRef
->disp_source
)
1025 dispatch_source_cancel(sdRef
->disp_source
);
1026 dispatch_release(sdRef
->disp_source
);
1027 sdRef
->disp_source
= NULL
;
1028 CallbackWithError(sdRef
, kDNSServiceErr_ServiceNotRunning
);
1031 // Don't touch sdRef anymore as it might have been deallocated
1032 return kDNSServiceErr_ServiceNotRunning
;
1034 else if (result
== read_all_wouldblock
)
1036 if (morebytes
&& sdRef
->logcounter
< 100)
1038 sdRef
->logcounter
++;
1039 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceProcessResult error: select indicated data was waiting but read_all returned EWOULDBLOCK");
1041 return kDNSServiceErr_NoError
;
1044 ConvertHeaderBytes(&cbh
.ipc_hdr
);
1045 if (cbh
.ipc_hdr
.version
!= VERSION
)
1047 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceProcessResult daemon version %d does not match client version %d", cbh
.ipc_hdr
.version
, VERSION
);
1048 sdRef
->ProcessReply
= NULL
;
1049 return kDNSServiceErr_Incompatible
;
1052 data
= malloc(cbh
.ipc_hdr
.datalen
);
1053 if (!data
) return kDNSServiceErr_NoMemory
;
1054 if (read_all(sdRef
->sockfd
, data
, cbh
.ipc_hdr
.datalen
) < 0) // On error, read_all will write a message to syslog for us
1056 // Set the ProcessReply to NULL before callback as the sdRef can get deallocated
1058 sdRef
->ProcessReply
= NULL
;
1059 #if _DNS_SD_LIBDISPATCH
1060 // Call the callbacks with an error if using the dispatch API, as DNSServiceProcessResult
1061 // is not called by the application and hence need to communicate the error. Cancel the
1062 // source so that we don't get any more events
1063 if (sdRef
->disp_source
)
1065 dispatch_source_cancel(sdRef
->disp_source
);
1066 dispatch_release(sdRef
->disp_source
);
1067 sdRef
->disp_source
= NULL
;
1068 CallbackWithError(sdRef
, kDNSServiceErr_ServiceNotRunning
);
1071 // Don't touch sdRef anymore as it might have been deallocated
1073 return kDNSServiceErr_ServiceNotRunning
;
1077 const char *ptr
= data
;
1078 cbh
.cb_flags
= get_flags (&ptr
, data
+ cbh
.ipc_hdr
.datalen
);
1079 cbh
.cb_interface
= get_uint32 (&ptr
, data
+ cbh
.ipc_hdr
.datalen
);
1080 cbh
.cb_err
= get_error_code(&ptr
, data
+ cbh
.ipc_hdr
.datalen
);
1082 // CAUTION: We have to handle the case where the client calls DNSServiceRefDeallocate from within the callback function.
1083 // To do this we set moreptr to point to morebytes. If the client does call DNSServiceRefDeallocate(),
1084 // then that routine will clear morebytes for us, and cause us to exit our loop.
1085 morebytes
= more_bytes(sdRef
->sockfd
);
1088 cbh
.cb_flags
|= kDNSServiceFlagsMoreComing
;
1089 sdRef
->moreptr
= &morebytes
;
1091 if (ptr
) sdRef
->ProcessReply(sdRef
, &cbh
, ptr
, data
+ cbh
.ipc_hdr
.datalen
);
1092 // Careful code here:
1093 // If morebytes is non-zero, that means we set sdRef->moreptr above, and the operation was not
1094 // cancelled out from under us, so now we need to clear sdRef->moreptr so we don't leave a stray
1095 // dangling pointer pointing to a long-gone stack variable.
1096 // If morebytes is zero, then one of two thing happened:
1097 // (a) morebytes was 0 above, so we didn't set sdRef->moreptr, so we don't need to clear it
1098 // (b) morebytes was 1 above, and we set sdRef->moreptr, but the operation was cancelled (with DNSServiceRefDeallocate()),
1099 // so we MUST NOT try to dereference our stale sdRef pointer.
1100 if (morebytes
) sdRef
->moreptr
= NULL
;
1103 } while (morebytes
);
1105 return kDNSServiceErr_NoError
;
1108 void DNSSD_API
DNSServiceRefDeallocate(DNSServiceRef sdRef
)
1110 if (!sdRef
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRefDeallocate called with NULL DNSServiceRef"); return; }
1112 if (!DNSServiceRefValid(sdRef
)) // Also verifies dnssd_SocketValid(sdRef->sockfd) for us too
1114 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRefDeallocate called with invalid DNSServiceRef %p %08X %08X", sdRef
, sdRef
->sockfd
, sdRef
->validator
);
1118 // If we're in the middle of a DNSServiceProcessResult() invocation for this DNSServiceRef, clear its morebytes flag to break it out of its while loop
1119 if (sdRef
->moreptr
) *(sdRef
->moreptr
) = 0;
1121 if (sdRef
->primary
) // If this is a subordinate DNSServiceOp, just send a 'stop' command
1123 DNSServiceOp
**p
= &sdRef
->primary
->next
;
1124 while (*p
&& *p
!= sdRef
) p
= &(*p
)->next
;
1129 ipc_msg_hdr
*hdr
= create_hdr(cancel_request
, &len
, &ptr
, 0, sdRef
);
1132 ConvertHeaderBytes(hdr
);
1133 write_all(sdRef
->sockfd
, (char *)hdr
, len
);
1137 FreeDNSServiceOp(sdRef
);
1140 else // else, make sure to terminate all subordinates as well
1142 #if _DNS_SD_LIBDISPATCH
1143 // The cancel handler will close the fd if a dispatch source has been set
1144 if (sdRef
->disp_source
)
1146 // By setting the ProcessReply to NULL, we make sure that we never call
1147 // the application callbacks ever, after returning from this function. We
1148 // assume that DNSServiceRefDeallocate is called from the serial queue
1149 // that was passed to DNSServiceSetDispatchQueue. Hence, dispatch_source_cancel
1150 // should cancel all the blocks on the queue and hence there should be no more
1151 // callbacks when we return from this function. Setting ProcessReply to NULL
1152 // provides extra protection.
1153 sdRef
->ProcessReply
= NULL
;
1154 shutdown(sdRef
->sockfd
, SHUT_WR
);
1155 dispatch_source_cancel(sdRef
->disp_source
);
1156 dispatch_release(sdRef
->disp_source
);
1157 sdRef
->disp_source
= NULL
;
1159 // if disp_queue is set, it means it used the DNSServiceSetDispatchQueue API. In that case,
1160 // when the source was cancelled, the fd was closed in the handler. Currently the source
1161 // is cancelled only when the mDNSResponder daemon dies
1162 else if (!sdRef
->disp_queue
) dnssd_close(sdRef
->sockfd
);
1164 dnssd_close(sdRef
->sockfd
);
1166 // Free DNSRecords added in DNSRegisterRecord if they have not
1167 // been freed in DNSRemoveRecord
1170 DNSServiceOp
*p
= sdRef
;
1171 sdRef
= sdRef
->next
;
1172 // When there is an error reading from the daemon e.g., bad fd, CallbackWithError
1173 // is called which sets moreptr. It might set the moreptr on a subordinate sdRef
1174 // but the application might call DNSServiceRefDeallocate with the main sdRef from
1175 // the callback. Hence, when we loop through the subordinate sdRefs, we need
1176 // to clear the moreptr so that CallbackWithError can terminate itself instead of
1177 // walking through the freed sdRefs.
1178 if (p
->moreptr
) *(p
->moreptr
) = 0;
1179 FreeDNSServiceOp(p
);
1184 DNSServiceErrorType DNSSD_API
DNSServiceGetProperty(const char *property
, void *result
, uint32_t *size
)
1186 DNSServiceErrorType err
;
1191 uint32_t actualsize
;
1193 if (!property
|| !result
|| !size
)
1194 return kDNSServiceErr_BadParam
;
1196 len
= strlen(property
) + 1;
1197 err
= ConnectToServer(&tmp
, 0, getproperty_request
, NULL
, NULL
, NULL
);
1198 if (err
) return err
;
1200 hdr
= create_hdr(getproperty_request
, &len
, &ptr
, 0, tmp
);
1201 if (!hdr
) { DNSServiceRefDeallocate(tmp
); return kDNSServiceErr_NoMemory
; }
1203 put_string(property
, &ptr
);
1204 err
= deliver_request(hdr
, tmp
); // Will free hdr for us
1205 if (err
) { DNSServiceRefDeallocate(tmp
); return err
; }
1207 if (read_all(tmp
->sockfd
, (char*)&actualsize
, (int)sizeof(actualsize
)) < 0)
1208 { DNSServiceRefDeallocate(tmp
); return kDNSServiceErr_ServiceNotRunning
; }
1210 actualsize
= ntohl(actualsize
);
1211 if (read_all(tmp
->sockfd
, (char*)result
, actualsize
< *size
? actualsize
: *size
) < 0)
1212 { DNSServiceRefDeallocate(tmp
); return kDNSServiceErr_ServiceNotRunning
; }
1213 DNSServiceRefDeallocate(tmp
);
1215 // Swap version result back to local process byte order
1216 if (!strcmp(property
, kDNSServiceProperty_DaemonVersion
) && *size
>= 4)
1217 *(uint32_t*)result
= ntohl(*(uint32_t*)result
);
1220 return kDNSServiceErr_NoError
;
1223 DNSServiceErrorType DNSSD_API
DNSServiceGetPID(const uint16_t srcport
, int32_t *pid
)
1227 DNSServiceOp
*tmp
= NULL
;
1228 size_t len
= sizeof(int32_t);
1230 DNSServiceErrorType err
= ConnectToServer(&tmp
, 0, getpid_request
, NULL
, NULL
, NULL
);
1231 if (err
) return err
;
1233 hdr
= create_hdr(getpid_request
, &len
, &ptr
, 0, tmp
);
1234 if (!hdr
) { DNSServiceRefDeallocate(tmp
); return kDNSServiceErr_NoMemory
; }
1236 put_uint16(srcport
, &ptr
);
1237 err
= deliver_request(hdr
, tmp
); // Will free hdr for us
1238 if (err
) { DNSServiceRefDeallocate(tmp
); return err
; }
1240 if (read_all(tmp
->sockfd
, (char*)pid
, sizeof(int32_t)) < 0)
1241 { DNSServiceRefDeallocate(tmp
); return kDNSServiceErr_ServiceNotRunning
; }
1243 DNSServiceRefDeallocate(tmp
);
1244 return kDNSServiceErr_NoError
;
1247 static void handle_resolve_response(DNSServiceOp
*const sdr
, const CallbackHeader
*const cbh
, const char *data
, const char *end
)
1249 char fullname
[kDNSServiceMaxDomainName
];
1250 char target
[kDNSServiceMaxDomainName
];
1252 union { uint16_t s
; u_char b
[2]; } port
;
1253 unsigned char *txtrecord
;
1255 get_string(&data
, end
, fullname
, kDNSServiceMaxDomainName
);
1256 get_string(&data
, end
, target
, kDNSServiceMaxDomainName
);
1257 if (!data
|| data
+ 2 > end
) goto fail
;
1259 port
.b
[0] = *data
++;
1260 port
.b
[1] = *data
++;
1261 txtlen
= get_uint16(&data
, end
);
1262 txtrecord
= (unsigned char *)get_rdata(&data
, end
, txtlen
);
1264 if (!data
) goto fail
;
1265 ((DNSServiceResolveReply
)sdr
->AppCallback
)(sdr
, cbh
->cb_flags
, cbh
->cb_interface
, cbh
->cb_err
, fullname
, target
, port
.s
, txtlen
, txtrecord
, sdr
->AppContext
);
1267 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1269 syslog(LOG_WARNING
, "dnssd_clientstub handle_resolve_response: error reading result from daemon");
1272 #if TARGET_OS_EMBEDDED
1274 static int32_t libSystemVersion
= 0;
1276 // Return true if the iOS application linked against a version of libsystem where P2P
1277 // interfaces were included by default when using kDNSServiceInterfaceIndexAny.
1278 // Using 160.0.0 == 0xa00000 as the version threshold.
1279 static int includeP2PWithIndexAny()
1281 if (libSystemVersion
== 0)
1282 libSystemVersion
= NSVersionOfLinkTimeLibrary("System");
1284 if (libSystemVersion
< 0xa00000)
1290 #else // TARGET_OS_EMBEDDED
1292 // always return false for non iOS platforms
1293 static int includeP2PWithIndexAny()
1298 #endif // TARGET_OS_EMBEDDED
1300 DNSServiceErrorType DNSSD_API DNSServiceResolve
1302 DNSServiceRef
*sdRef
,
1303 DNSServiceFlags flags
,
1304 uint32_t interfaceIndex
,
1306 const char *regtype
,
1308 DNSServiceResolveReply callBack
,
1315 DNSServiceErrorType err
;
1317 if (!sdRef
|| !name
|| !regtype
|| !domain
|| !callBack
) return kDNSServiceErr_BadParam
;
1319 // Need a real InterfaceID for WakeOnResolve
1320 if ((flags
& kDNSServiceFlagsWakeOnResolve
) != 0 &&
1321 ((interfaceIndex
== kDNSServiceInterfaceIndexAny
) ||
1322 (interfaceIndex
== kDNSServiceInterfaceIndexLocalOnly
) ||
1323 (interfaceIndex
== kDNSServiceInterfaceIndexUnicast
) ||
1324 (interfaceIndex
== kDNSServiceInterfaceIndexP2P
) ||
1325 (interfaceIndex
== kDNSServiceInterfaceIndexBLE
)))
1327 return kDNSServiceErr_BadParam
;
1330 if ((interfaceIndex
== kDNSServiceInterfaceIndexAny
) && includeP2PWithIndexAny())
1331 flags
|= kDNSServiceFlagsIncludeP2P
;
1333 err
= ConnectToServer(sdRef
, flags
, resolve_request
, handle_resolve_response
, callBack
, context
);
1334 if (err
) return err
; // On error ConnectToServer leaves *sdRef set to NULL
1336 // Calculate total message length
1337 len
= sizeof(flags
);
1338 len
+= sizeof(interfaceIndex
);
1339 len
+= strlen(name
) + 1;
1340 len
+= strlen(regtype
) + 1;
1341 len
+= strlen(domain
) + 1;
1343 hdr
= create_hdr(resolve_request
, &len
, &ptr
, (*sdRef
)->primary
? 1 : 0, *sdRef
);
1344 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
1346 put_flags(flags
, &ptr
);
1347 put_uint32(interfaceIndex
, &ptr
);
1348 put_string(name
, &ptr
);
1349 put_string(regtype
, &ptr
);
1350 put_string(domain
, &ptr
);
1352 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1353 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
1357 static void handle_query_response(DNSServiceOp
*const sdr
, const CallbackHeader
*const cbh
, const char *data
, const char *const end
)
1360 char name
[kDNSServiceMaxDomainName
];
1361 uint16_t rrtype
, rrclass
, rdlen
;
1364 get_string(&data
, end
, name
, kDNSServiceMaxDomainName
);
1365 rrtype
= get_uint16(&data
, end
);
1366 rrclass
= get_uint16(&data
, end
);
1367 rdlen
= get_uint16(&data
, end
);
1368 rdata
= get_rdata(&data
, end
, rdlen
);
1369 ttl
= get_uint32(&data
, end
);
1371 if (!data
) syslog(LOG_WARNING
, "dnssd_clientstub handle_query_response: error reading result from daemon");
1372 else ((DNSServiceQueryRecordReply
)sdr
->AppCallback
)(sdr
, cbh
->cb_flags
, cbh
->cb_interface
, cbh
->cb_err
, name
, rrtype
, rrclass
, rdlen
, rdata
, ttl
, sdr
->AppContext
);
1373 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1376 DNSServiceErrorType DNSSD_API DNSServiceQueryRecord
1378 DNSServiceRef
*sdRef
,
1379 DNSServiceFlags flags
,
1380 uint32_t interfaceIndex
,
1384 DNSServiceQueryRecordReply callBack
,
1391 DNSServiceErrorType err
;
1393 // NULL name handled below.
1394 if (!sdRef
|| !callBack
) return kDNSServiceErr_BadParam
;
1396 if ((interfaceIndex
== kDNSServiceInterfaceIndexAny
) && includeP2PWithIndexAny())
1397 flags
|= kDNSServiceFlagsIncludeP2P
;
1399 err
= ConnectToServer(sdRef
, flags
, query_request
, handle_query_response
, callBack
, context
);
1400 if (err
) return err
; // On error ConnectToServer leaves *sdRef set to NULL
1402 if (!name
) name
= "\0";
1404 // Calculate total message length
1405 len
= sizeof(flags
);
1406 len
+= sizeof(uint32_t); // interfaceIndex
1407 len
+= strlen(name
) + 1;
1408 len
+= 2 * sizeof(uint16_t); // rrtype, rrclass
1410 hdr
= create_hdr(query_request
, &len
, &ptr
, (*sdRef
)->primary
? 1 : 0, *sdRef
);
1411 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
1413 put_flags(flags
, &ptr
);
1414 put_uint32(interfaceIndex
, &ptr
);
1415 put_string(name
, &ptr
);
1416 put_uint16(rrtype
, &ptr
);
1417 put_uint16(rrclass
, &ptr
);
1419 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1420 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
1424 static void handle_addrinfo_response(DNSServiceOp
*const sdr
, const CallbackHeader
*const cbh
, const char *data
, const char *const end
)
1426 char hostname
[kDNSServiceMaxDomainName
];
1427 uint16_t rrtype
, rrclass
, rdlen
;
1431 get_string(&data
, end
, hostname
, kDNSServiceMaxDomainName
);
1432 rrtype
= get_uint16(&data
, end
);
1433 rrclass
= get_uint16(&data
, end
);
1434 rdlen
= get_uint16(&data
, end
);
1435 rdata
= get_rdata (&data
, end
, rdlen
);
1436 ttl
= get_uint32(&data
, end
);
1437 (void)rrclass
; // Unused
1439 // We only generate client callbacks for A and AAAA results (including NXDOMAIN results for
1440 // those types, if the client has requested those with the kDNSServiceFlagsReturnIntermediates).
1441 // Other result types, specifically CNAME referrals, are not communicated to the client, because
1442 // the DNSServiceGetAddrInfoReply interface doesn't have any meaningful way to communiate CNAME referrals.
1443 if (!data
) syslog(LOG_WARNING
, "dnssd_clientstub handle_addrinfo_response: error reading result from daemon");
1444 else if (rrtype
== kDNSServiceType_A
|| rrtype
== kDNSServiceType_AAAA
)
1446 struct sockaddr_in sa4
;
1447 struct sockaddr_in6 sa6
;
1448 const struct sockaddr
*const sa
= (rrtype
== kDNSServiceType_A
) ? (struct sockaddr
*)&sa4
: (struct sockaddr
*)&sa6
;
1449 if (rrtype
== kDNSServiceType_A
)
1451 memset(&sa4
, 0, sizeof(sa4
));
1452 #ifndef NOT_HAVE_SA_LEN
1453 sa4
.sin_len
= sizeof(struct sockaddr_in
);
1455 sa4
.sin_family
= AF_INET
;
1457 if (!cbh
->cb_err
) memcpy(&sa4
.sin_addr
, rdata
, rdlen
);
1461 memset(&sa6
, 0, sizeof(sa6
));
1462 #ifndef NOT_HAVE_SA_LEN
1463 sa6
.sin6_len
= sizeof(struct sockaddr_in6
);
1465 sa6
.sin6_family
= AF_INET6
;
1467 // sin6_flowinfo = 0;
1468 // sin6_scope_id = 0;
1471 memcpy(&sa6
.sin6_addr
, rdata
, rdlen
);
1472 if (IN6_IS_ADDR_LINKLOCAL(&sa6
.sin6_addr
)) sa6
.sin6_scope_id
= cbh
->cb_interface
;
1475 // Validation results are always delivered separately from the actual results of the
1476 // DNSServiceGetAddrInfo. Set the "addr" to NULL as per the documentation.
1478 // Note: If we deliver validation results along with the "addr" in the future, we need
1479 // a way to differentiate the negative response from validation-only response as both
1480 // has zero address.
1481 if (!(cbh
->cb_flags
& kDNSServiceFlagsValidate
))
1482 ((DNSServiceGetAddrInfoReply
)sdr
->AppCallback
)(sdr
, cbh
->cb_flags
, cbh
->cb_interface
, cbh
->cb_err
, hostname
, sa
, ttl
, sdr
->AppContext
);
1484 ((DNSServiceGetAddrInfoReply
)sdr
->AppCallback
)(sdr
, cbh
->cb_flags
, cbh
->cb_interface
, cbh
->cb_err
, hostname
, NULL
, 0, sdr
->AppContext
);
1485 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1489 DNSServiceErrorType DNSSD_API DNSServiceGetAddrInfo
1491 DNSServiceRef
*sdRef
,
1492 DNSServiceFlags flags
,
1493 uint32_t interfaceIndex
,
1495 const char *hostname
,
1496 DNSServiceGetAddrInfoReply callBack
,
1497 void *context
/* may be NULL */
1503 DNSServiceErrorType err
;
1505 if (!sdRef
|| !hostname
|| !callBack
) return kDNSServiceErr_BadParam
;
1507 err
= ConnectToServer(sdRef
, flags
, addrinfo_request
, handle_addrinfo_response
, callBack
, context
);
1510 return err
; // On error ConnectToServer leaves *sdRef set to NULL
1513 // Calculate total message length
1514 len
= sizeof(flags
);
1515 len
+= sizeof(uint32_t); // interfaceIndex
1516 len
+= sizeof(uint32_t); // protocol
1517 len
+= strlen(hostname
) + 1;
1519 hdr
= create_hdr(addrinfo_request
, &len
, &ptr
, (*sdRef
)->primary
? 1 : 0, *sdRef
);
1520 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
1522 put_flags(flags
, &ptr
);
1523 put_uint32(interfaceIndex
, &ptr
);
1524 put_uint32(protocol
, &ptr
);
1525 put_string(hostname
, &ptr
);
1527 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1528 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
1532 static void handle_browse_response(DNSServiceOp
*const sdr
, const CallbackHeader
*const cbh
, const char *data
, const char *const end
)
1534 char replyName
[256], replyType
[kDNSServiceMaxDomainName
], replyDomain
[kDNSServiceMaxDomainName
];
1535 get_string(&data
, end
, replyName
, 256);
1536 get_string(&data
, end
, replyType
, kDNSServiceMaxDomainName
);
1537 get_string(&data
, end
, replyDomain
, kDNSServiceMaxDomainName
);
1538 if (!data
) syslog(LOG_WARNING
, "dnssd_clientstub handle_browse_response: error reading result from daemon");
1539 else ((DNSServiceBrowseReply
)sdr
->AppCallback
)(sdr
, cbh
->cb_flags
, cbh
->cb_interface
, cbh
->cb_err
, replyName
, replyType
, replyDomain
, sdr
->AppContext
);
1540 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1543 DNSServiceErrorType DNSSD_API DNSServiceBrowse
1545 DNSServiceRef
*sdRef
,
1546 DNSServiceFlags flags
,
1547 uint32_t interfaceIndex
,
1548 const char *regtype
,
1550 DNSServiceBrowseReply callBack
,
1557 DNSServiceErrorType err
;
1559 // NULL domain handled below
1560 if (!sdRef
|| !regtype
|| !callBack
) return kDNSServiceErr_BadParam
;
1562 if ((interfaceIndex
== kDNSServiceInterfaceIndexAny
) && includeP2PWithIndexAny())
1563 flags
|= kDNSServiceFlagsIncludeP2P
;
1565 err
= ConnectToServer(sdRef
, flags
, browse_request
, handle_browse_response
, callBack
, context
);
1566 if (err
) return err
; // On error ConnectToServer leaves *sdRef set to NULL
1568 if (!domain
) domain
= "";
1569 len
= sizeof(flags
);
1570 len
+= sizeof(interfaceIndex
);
1571 len
+= strlen(regtype
) + 1;
1572 len
+= strlen(domain
) + 1;
1574 hdr
= create_hdr(browse_request
, &len
, &ptr
, (*sdRef
)->primary
? 1 : 0, *sdRef
);
1575 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
1577 put_flags(flags
, &ptr
);
1578 put_uint32(interfaceIndex
, &ptr
);
1579 put_string(regtype
, &ptr
);
1580 put_string(domain
, &ptr
);
1582 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1583 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
1587 DNSServiceErrorType DNSSD_API
DNSServiceSetDefaultDomainForUser(DNSServiceFlags flags
, const char *domain
)
1589 DNSServiceErrorType err
;
1595 if (!domain
) return kDNSServiceErr_BadParam
;
1596 len
= sizeof(flags
) + strlen(domain
) + 1;
1598 err
= ConnectToServer(&tmp
, 0, setdomain_request
, NULL
, NULL
, NULL
);
1599 if (err
) return err
;
1601 hdr
= create_hdr(setdomain_request
, &len
, &ptr
, 0, tmp
);
1602 if (!hdr
) { DNSServiceRefDeallocate(tmp
); return kDNSServiceErr_NoMemory
; }
1604 put_flags(flags
, &ptr
);
1605 put_string(domain
, &ptr
);
1606 err
= deliver_request(hdr
, tmp
); // Will free hdr for us
1607 DNSServiceRefDeallocate(tmp
);
1611 static void handle_regservice_response(DNSServiceOp
*const sdr
, const CallbackHeader
*const cbh
, const char *data
, const char *const end
)
1613 char name
[256], regtype
[kDNSServiceMaxDomainName
], domain
[kDNSServiceMaxDomainName
];
1614 get_string(&data
, end
, name
, 256);
1615 get_string(&data
, end
, regtype
, kDNSServiceMaxDomainName
);
1616 get_string(&data
, end
, domain
, kDNSServiceMaxDomainName
);
1617 if (!data
) syslog(LOG_WARNING
, "dnssd_clientstub handle_regservice_response: error reading result from daemon");
1618 else ((DNSServiceRegisterReply
)sdr
->AppCallback
)(sdr
, cbh
->cb_flags
, cbh
->cb_err
, name
, regtype
, domain
, sdr
->AppContext
);
1619 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1622 DNSServiceErrorType DNSSD_API DNSServiceRegister
1624 DNSServiceRef
*sdRef
,
1625 DNSServiceFlags flags
,
1626 uint32_t interfaceIndex
,
1628 const char *regtype
,
1631 uint16_t PortInNetworkByteOrder
,
1633 const void *txtRecord
,
1634 DNSServiceRegisterReply callBack
,
1641 DNSServiceErrorType err
;
1642 union { uint16_t s
; u_char b
[2]; } port
= { PortInNetworkByteOrder
};
1644 if (!sdRef
|| !regtype
) return kDNSServiceErr_BadParam
;
1645 if (!name
) name
= "";
1646 if (!domain
) domain
= "";
1647 if (!host
) host
= "";
1648 if (!txtRecord
) txtRecord
= (void*)"";
1650 // No callback must have auto-rename
1651 if (!callBack
&& (flags
& kDNSServiceFlagsNoAutoRename
)) return kDNSServiceErr_BadParam
;
1653 if ((interfaceIndex
== kDNSServiceInterfaceIndexAny
) && includeP2PWithIndexAny())
1654 flags
|= kDNSServiceFlagsIncludeP2P
;
1656 err
= ConnectToServer(sdRef
, flags
, reg_service_request
, callBack
? handle_regservice_response
: NULL
, callBack
, context
);
1657 if (err
) return err
; // On error ConnectToServer leaves *sdRef set to NULL
1659 len
= sizeof(DNSServiceFlags
);
1660 len
+= sizeof(uint32_t); // interfaceIndex
1661 len
+= strlen(name
) + strlen(regtype
) + strlen(domain
) + strlen(host
) + 4;
1662 len
+= 2 * sizeof(uint16_t); // port, txtLen
1665 hdr
= create_hdr(reg_service_request
, &len
, &ptr
, (*sdRef
)->primary
? 1 : 0, *sdRef
);
1666 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
1667 if (!callBack
) hdr
->ipc_flags
|= IPC_FLAGS_NOREPLY
;
1669 put_flags(flags
, &ptr
);
1670 put_uint32(interfaceIndex
, &ptr
);
1671 put_string(name
, &ptr
);
1672 put_string(regtype
, &ptr
);
1673 put_string(domain
, &ptr
);
1674 put_string(host
, &ptr
);
1677 put_uint16(txtLen
, &ptr
);
1678 put_rdata(txtLen
, txtRecord
, &ptr
);
1680 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1681 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
1685 static void handle_enumeration_response(DNSServiceOp
*const sdr
, const CallbackHeader
*const cbh
, const char *data
, const char *const end
)
1687 char domain
[kDNSServiceMaxDomainName
];
1688 get_string(&data
, end
, domain
, kDNSServiceMaxDomainName
);
1689 if (!data
) syslog(LOG_WARNING
, "dnssd_clientstub handle_enumeration_response: error reading result from daemon");
1690 else ((DNSServiceDomainEnumReply
)sdr
->AppCallback
)(sdr
, cbh
->cb_flags
, cbh
->cb_interface
, cbh
->cb_err
, domain
, sdr
->AppContext
);
1691 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1694 DNSServiceErrorType DNSSD_API DNSServiceEnumerateDomains
1696 DNSServiceRef
*sdRef
,
1697 DNSServiceFlags flags
,
1698 uint32_t interfaceIndex
,
1699 DNSServiceDomainEnumReply callBack
,
1706 DNSServiceErrorType err
;
1710 if (!sdRef
|| !callBack
) return kDNSServiceErr_BadParam
;
1712 f1
= (flags
& kDNSServiceFlagsBrowseDomains
) != 0;
1713 f2
= (flags
& kDNSServiceFlagsRegistrationDomains
) != 0;
1714 if (f1
+ f2
!= 1) return kDNSServiceErr_BadParam
;
1716 err
= ConnectToServer(sdRef
, flags
, enumeration_request
, handle_enumeration_response
, callBack
, context
);
1717 if (err
) return err
; // On error ConnectToServer leaves *sdRef set to NULL
1719 len
= sizeof(DNSServiceFlags
);
1720 len
+= sizeof(uint32_t);
1722 hdr
= create_hdr(enumeration_request
, &len
, &ptr
, (*sdRef
)->primary
? 1 : 0, *sdRef
);
1723 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
1725 put_flags(flags
, &ptr
);
1726 put_uint32(interfaceIndex
, &ptr
);
1728 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1729 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
1733 static void ConnectionResponse(DNSServiceOp
*const sdr
, const CallbackHeader
*const cbh
, const char *const data
, const char *const end
)
1735 (void)data
; // Unused
1737 //printf("ConnectionResponse got %d\n", cbh->ipc_hdr.op);
1738 if (cbh
->ipc_hdr
.op
!= reg_record_reply_op
)
1740 // When using kDNSServiceFlagsShareConnection, need to search the list of associated DNSServiceOps
1741 // to find the one this response is intended for, and then call through to its ProcessReply handler.
1742 // We start with our first subordinate DNSServiceRef -- don't want to accidentally match the parent DNSServiceRef.
1743 DNSServiceOp
*op
= sdr
->next
;
1744 while (op
&& (op
->uid
.u32
[0] != cbh
->ipc_hdr
.client_context
.u32
[0] || op
->uid
.u32
[1] != cbh
->ipc_hdr
.client_context
.u32
[1]))
1746 // Note: We may sometimes not find a matching DNSServiceOp, in the case where the client has
1747 // cancelled the subordinate DNSServiceOp, but there are still messages in the pipeline from the daemon
1748 if (op
&& op
->ProcessReply
) op
->ProcessReply(op
, cbh
, data
, end
);
1749 // WARNING: Don't touch op or sdr after this -- client may have called DNSServiceRefDeallocate
1755 for (rec
= sdr
->rec
; rec
; rec
= rec
->recnext
)
1757 if (rec
->uid
.u32
[0] == cbh
->ipc_hdr
.client_context
.u32
[0] && rec
->uid
.u32
[1] == cbh
->ipc_hdr
.client_context
.u32
[1])
1760 // The record might have been freed already and hence not an
1761 // error if the record is not found.
1764 syslog(LOG_INFO
, "ConnectionResponse: Record not found");
1767 if (rec
->sdr
!= sdr
)
1769 syslog(LOG_WARNING
, "ConnectionResponse: Record sdr mismatch: rec %p sdr %p", rec
->sdr
, sdr
);
1773 if (sdr
->op
== connection_request
|| sdr
->op
== connection_delegate_request
)
1775 rec
->AppCallback(rec
->sdr
, rec
, cbh
->cb_flags
, cbh
->cb_err
, rec
->AppContext
);
1779 syslog(LOG_WARNING
, "dnssd_clientstub ConnectionResponse: sdr->op != connection_request");
1780 rec
->AppCallback(rec
->sdr
, rec
, 0, kDNSServiceErr_Unknown
, rec
->AppContext
);
1782 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1786 DNSServiceErrorType DNSSD_API
DNSServiceCreateConnection(DNSServiceRef
*sdRef
)
1788 DNSServiceErrorType err
;
1793 if (!sdRef
) return kDNSServiceErr_BadParam
;
1794 err
= ConnectToServer(sdRef
, 0, connection_request
, ConnectionResponse
, NULL
, NULL
);
1795 if (err
) return err
; // On error ConnectToServer leaves *sdRef set to NULL
1797 hdr
= create_hdr(connection_request
, &len
, &ptr
, 0, *sdRef
);
1798 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
1800 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1801 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
1805 #if APPLE_OSX_mDNSResponder && !TARGET_IPHONE_SIMULATOR
1806 DNSServiceErrorType DNSSD_API
DNSServiceCreateDelegateConnection(DNSServiceRef
*sdRef
, int32_t pid
, uuid_t uuid
)
1812 if (!sdRef
) return kDNSServiceErr_BadParam
;
1813 DNSServiceErrorType err
= ConnectToServer(sdRef
, 0, connection_delegate_request
, ConnectionResponse
, NULL
, NULL
);
1816 return err
; // On error ConnectToServer leaves *sdRef set to NULL
1819 // Only one of the two options can be set. If pid is zero, uuid is used.
1820 // If both are specified only pid will be used. We send across the pid
1821 // so that the daemon knows what to read from the socket.
1823 len
+= sizeof(int32_t);
1825 hdr
= create_hdr(connection_delegate_request
, &len
, &ptr
, 0, *sdRef
);
1828 DNSServiceRefDeallocate(*sdRef
);
1830 return kDNSServiceErr_NoMemory
;
1833 if (pid
&& setsockopt((*sdRef
)->sockfd
, SOL_SOCKET
, SO_DELEGATED
, &pid
, sizeof(pid
)) == -1)
1835 syslog(LOG_WARNING
, "dnssdclientstub: Could not setsockopt() for PID[%d], no entitlements or process(pid) invalid errno:%d (%s)", pid
, errno
, strerror(errno
));
1836 // Free the hdr in case we return before calling deliver_request()
1839 DNSServiceRefDeallocate(*sdRef
);
1841 return kDNSServiceErr_NoAuth
;
1844 if (!pid
&& setsockopt((*sdRef
)->sockfd
, SOL_SOCKET
, SO_DELEGATED_UUID
, uuid
, sizeof(uuid_t
)) == -1)
1846 syslog(LOG_WARNING
, "dnssdclientstub: Could not setsockopt() for UUID, no entitlements or process(uuid) invalid errno:%d (%s) ", errno
, strerror(errno
));
1847 // Free the hdr in case we return before calling deliver_request()
1850 DNSServiceRefDeallocate(*sdRef
);
1852 return kDNSServiceErr_NoAuth
;
1855 put_uint32(pid
, &ptr
);
1857 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1860 DNSServiceRefDeallocate(*sdRef
);
1865 #elif TARGET_IPHONE_SIMULATOR // This hack is for Simulator platform only
1866 DNSServiceErrorType DNSSD_API
DNSServiceCreateDelegateConnection(DNSServiceRef
*sdRef
, int32_t pid
, uuid_t uuid
)
1870 return DNSServiceCreateConnection(sdRef
);
1874 DNSServiceErrorType DNSSD_API DNSServiceRegisterRecord
1876 DNSServiceRef sdRef
,
1877 DNSRecordRef
*RecordRef
,
1878 DNSServiceFlags flags
,
1879 uint32_t interfaceIndex
,
1880 const char *fullname
,
1886 DNSServiceRegisterRecordReply callBack
,
1892 ipc_msg_hdr
*hdr
= NULL
;
1893 DNSRecordRef rref
= NULL
;
1895 int f1
= (flags
& kDNSServiceFlagsShared
) != 0;
1896 int f2
= (flags
& kDNSServiceFlagsUnique
) != 0;
1897 if (f1
+ f2
!= 1) return kDNSServiceErr_BadParam
;
1899 if ((interfaceIndex
== kDNSServiceInterfaceIndexAny
) && includeP2PWithIndexAny())
1900 flags
|= kDNSServiceFlagsIncludeP2P
;
1902 if (!sdRef
|| !RecordRef
|| !fullname
|| (!rdata
&& rdlen
) || !callBack
)
1904 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRegisterRecord called with NULL parameter");
1905 return kDNSServiceErr_BadParam
;
1908 if (!DNSServiceRefValid(sdRef
))
1910 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRegisterRecord called with invalid DNSServiceRef %p %08X %08X", sdRef
, sdRef
->sockfd
, sdRef
->validator
);
1911 return kDNSServiceErr_BadReference
;
1914 if (sdRef
->op
!= connection_request
&& sdRef
->op
!= connection_delegate_request
)
1916 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRegisterRecord called with non-DNSServiceCreateConnection DNSServiceRef %p %d", sdRef
, sdRef
->op
);
1917 return kDNSServiceErr_BadReference
;
1922 len
= sizeof(DNSServiceFlags
);
1923 len
+= 2 * sizeof(uint32_t); // interfaceIndex, ttl
1924 len
+= 3 * sizeof(uint16_t); // rrtype, rrclass, rdlen
1925 len
+= strlen(fullname
) + 1;
1928 // Bump up the uid. Normally for shared operations (kDNSServiceFlagsShareConnection), this
1929 // is done in ConnectToServer. For DNSServiceRegisterRecord, ConnectToServer has already
1930 // been called. As multiple DNSServiceRegisterRecords can be multiplexed over a single
1931 // connection, we need a way to demultiplex the response so that the callback corresponding
1932 // to the right DNSServiceRegisterRecord instance can be called. Use the same mechanism that
1933 // is used by kDNSServiceFlagsShareConnection. create_hdr copies the uid value to ipc
1934 // hdr->client_context which will be returned in the ipc response.
1935 if (++sdRef
->uid
.u32
[0] == 0)
1936 ++sdRef
->uid
.u32
[1];
1937 hdr
= create_hdr(reg_record_request
, &len
, &ptr
, 1, sdRef
);
1938 if (!hdr
) return kDNSServiceErr_NoMemory
;
1940 put_flags(flags
, &ptr
);
1941 put_uint32(interfaceIndex
, &ptr
);
1942 put_string(fullname
, &ptr
);
1943 put_uint16(rrtype
, &ptr
);
1944 put_uint16(rrclass
, &ptr
);
1945 put_uint16(rdlen
, &ptr
);
1946 put_rdata(rdlen
, rdata
, &ptr
);
1947 put_uint32(ttl
, &ptr
);
1949 rref
= malloc(sizeof(DNSRecord
));
1950 if (!rref
) { free(hdr
); return kDNSServiceErr_NoMemory
; }
1951 rref
->AppContext
= context
;
1952 rref
->AppCallback
= callBack
;
1953 rref
->record_index
= sdRef
->max_index
++;
1955 rref
->recnext
= NULL
;
1957 // Remember the uid that we are sending across so that we can match
1958 // when the response comes back.
1959 rref
->uid
= sdRef
->uid
;
1960 hdr
->reg_index
= rref
->record_index
;
1963 while (*p
) p
= &(*p
)->recnext
;
1966 return deliver_request(hdr
, sdRef
); // Will free hdr for us
1969 // sdRef returned by DNSServiceRegister()
1970 DNSServiceErrorType DNSSD_API DNSServiceAddRecord
1972 DNSServiceRef sdRef
,
1973 DNSRecordRef
*RecordRef
,
1974 DNSServiceFlags flags
,
1987 if (!sdRef
|| !RecordRef
|| (!rdata
&& rdlen
))
1989 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceAddRecord called with NULL parameter");
1990 return kDNSServiceErr_BadParam
;
1992 if (sdRef
->op
!= reg_service_request
)
1994 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceAddRecord called with non-DNSServiceRegister DNSServiceRef %p %d", sdRef
, sdRef
->op
);
1995 return kDNSServiceErr_BadReference
;
1998 if (!DNSServiceRefValid(sdRef
))
2000 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceAddRecord called with invalid DNSServiceRef %p %08X %08X", sdRef
, sdRef
->sockfd
, sdRef
->validator
);
2001 return kDNSServiceErr_BadReference
;
2006 len
+= 2 * sizeof(uint16_t); // rrtype, rdlen
2008 len
+= sizeof(uint32_t);
2009 len
+= sizeof(DNSServiceFlags
);
2011 hdr
= create_hdr(add_record_request
, &len
, &ptr
, 1, sdRef
);
2012 if (!hdr
) return kDNSServiceErr_NoMemory
;
2013 put_flags(flags
, &ptr
);
2014 put_uint16(rrtype
, &ptr
);
2015 put_uint16(rdlen
, &ptr
);
2016 put_rdata(rdlen
, rdata
, &ptr
);
2017 put_uint32(ttl
, &ptr
);
2019 rref
= malloc(sizeof(DNSRecord
));
2020 if (!rref
) { free(hdr
); return kDNSServiceErr_NoMemory
; }
2021 rref
->AppContext
= NULL
;
2022 rref
->AppCallback
= NULL
;
2023 rref
->record_index
= sdRef
->max_index
++;
2025 rref
->recnext
= NULL
;
2027 hdr
->reg_index
= rref
->record_index
;
2030 while (*p
) p
= &(*p
)->recnext
;
2033 return deliver_request(hdr
, sdRef
); // Will free hdr for us
2036 // DNSRecordRef returned by DNSServiceRegisterRecord or DNSServiceAddRecord
2037 DNSServiceErrorType DNSSD_API DNSServiceUpdateRecord
2039 DNSServiceRef sdRef
,
2040 DNSRecordRef RecordRef
,
2041 DNSServiceFlags flags
,
2051 if (!sdRef
|| (!rdata
&& rdlen
))
2053 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceUpdateRecord called with NULL parameter");
2054 return kDNSServiceErr_BadParam
;
2057 if (!DNSServiceRefValid(sdRef
))
2059 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceUpdateRecord called with invalid DNSServiceRef %p %08X %08X", sdRef
, sdRef
->sockfd
, sdRef
->validator
);
2060 return kDNSServiceErr_BadReference
;
2063 // Note: RecordRef is allowed to be NULL
2065 len
+= sizeof(uint16_t);
2067 len
+= sizeof(uint32_t);
2068 len
+= sizeof(DNSServiceFlags
);
2070 hdr
= create_hdr(update_record_request
, &len
, &ptr
, 1, sdRef
);
2071 if (!hdr
) return kDNSServiceErr_NoMemory
;
2072 hdr
->reg_index
= RecordRef
? RecordRef
->record_index
: TXT_RECORD_INDEX
;
2073 put_flags(flags
, &ptr
);
2074 put_uint16(rdlen
, &ptr
);
2075 put_rdata(rdlen
, rdata
, &ptr
);
2076 put_uint32(ttl
, &ptr
);
2077 return deliver_request(hdr
, sdRef
); // Will free hdr for us
2080 DNSServiceErrorType DNSSD_API DNSServiceRemoveRecord
2082 DNSServiceRef sdRef
,
2083 DNSRecordRef RecordRef
,
2084 DNSServiceFlags flags
2090 DNSServiceErrorType err
;
2092 if (!sdRef
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRemoveRecord called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam
; }
2093 if (!RecordRef
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRemoveRecord called with NULL DNSRecordRef"); return kDNSServiceErr_BadParam
; }
2094 if (!sdRef
->max_index
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRemoveRecord called with bad DNSServiceRef"); return kDNSServiceErr_BadReference
; }
2096 if (!DNSServiceRefValid(sdRef
))
2098 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRemoveRecord called with invalid DNSServiceRef %p %08X %08X", sdRef
, sdRef
->sockfd
, sdRef
->validator
);
2099 return kDNSServiceErr_BadReference
;
2102 len
+= sizeof(flags
);
2103 hdr
= create_hdr(remove_record_request
, &len
, &ptr
, 1, sdRef
);
2104 if (!hdr
) return kDNSServiceErr_NoMemory
;
2105 hdr
->reg_index
= RecordRef
->record_index
;
2106 put_flags(flags
, &ptr
);
2107 err
= deliver_request(hdr
, sdRef
); // Will free hdr for us
2110 // This RecordRef could have been allocated in DNSServiceRegisterRecord or DNSServiceAddRecord.
2111 // If so, delink from the list before freeing
2112 DNSRecord
**p
= &sdRef
->rec
;
2113 while (*p
&& *p
!= RecordRef
) p
= &(*p
)->recnext
;
2114 if (*p
) *p
= RecordRef
->recnext
;
2120 DNSServiceErrorType DNSSD_API DNSServiceReconfirmRecord
2122 DNSServiceFlags flags
,
2123 uint32_t interfaceIndex
,
2124 const char *fullname
,
2131 DNSServiceErrorType err
;
2135 DNSServiceOp
*tmp
= NULL
;
2137 if (!fullname
|| (!rdata
&& rdlen
)) return kDNSServiceErr_BadParam
;
2139 err
= ConnectToServer(&tmp
, flags
, reconfirm_record_request
, NULL
, NULL
, NULL
);
2140 if (err
) return err
;
2142 len
= sizeof(DNSServiceFlags
);
2143 len
+= sizeof(uint32_t);
2144 len
+= strlen(fullname
) + 1;
2145 len
+= 3 * sizeof(uint16_t);
2147 hdr
= create_hdr(reconfirm_record_request
, &len
, &ptr
, 0, tmp
);
2148 if (!hdr
) { DNSServiceRefDeallocate(tmp
); return kDNSServiceErr_NoMemory
; }
2150 put_flags(flags
, &ptr
);
2151 put_uint32(interfaceIndex
, &ptr
);
2152 put_string(fullname
, &ptr
);
2153 put_uint16(rrtype
, &ptr
);
2154 put_uint16(rrclass
, &ptr
);
2155 put_uint16(rdlen
, &ptr
);
2156 put_rdata(rdlen
, rdata
, &ptr
);
2158 err
= deliver_request(hdr
, tmp
); // Will free hdr for us
2159 DNSServiceRefDeallocate(tmp
);
2164 static void handle_port_mapping_response(DNSServiceOp
*const sdr
, const CallbackHeader
*const cbh
, const char *data
, const char *const end
)
2166 union { uint32_t l
; u_char b
[4]; } addr
;
2168 union { uint16_t s
; u_char b
[2]; } internalPort
;
2169 union { uint16_t s
; u_char b
[2]; } externalPort
;
2172 if (!data
|| data
+ 13 > end
) goto fail
;
2174 addr
.b
[0] = *data
++;
2175 addr
.b
[1] = *data
++;
2176 addr
.b
[2] = *data
++;
2177 addr
.b
[3] = *data
++;
2179 internalPort
.b
[0] = *data
++;
2180 internalPort
.b
[1] = *data
++;
2181 externalPort
.b
[0] = *data
++;
2182 externalPort
.b
[1] = *data
++;
2183 ttl
= get_uint32(&data
, end
);
2184 if (!data
) goto fail
;
2186 ((DNSServiceNATPortMappingReply
)sdr
->AppCallback
)(sdr
, cbh
->cb_flags
, cbh
->cb_interface
, cbh
->cb_err
, addr
.l
, protocol
, internalPort
.s
, externalPort
.s
, ttl
, sdr
->AppContext
);
2188 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
2191 syslog(LOG_WARNING
, "dnssd_clientstub handle_port_mapping_response: error reading result from daemon");
2194 DNSServiceErrorType DNSSD_API DNSServiceNATPortMappingCreate
2196 DNSServiceRef
*sdRef
,
2197 DNSServiceFlags flags
,
2198 uint32_t interfaceIndex
,
2199 uint32_t protocol
, /* TCP and/or UDP */
2200 uint16_t internalPortInNetworkByteOrder
,
2201 uint16_t externalPortInNetworkByteOrder
,
2202 uint32_t ttl
, /* time to live in seconds */
2203 DNSServiceNATPortMappingReply callBack
,
2204 void *context
/* may be NULL */
2210 union { uint16_t s
; u_char b
[2]; } internalPort
= { internalPortInNetworkByteOrder
};
2211 union { uint16_t s
; u_char b
[2]; } externalPort
= { externalPortInNetworkByteOrder
};
2213 DNSServiceErrorType err
= ConnectToServer(sdRef
, flags
, port_mapping_request
, handle_port_mapping_response
, callBack
, context
);
2214 if (err
) return err
; // On error ConnectToServer leaves *sdRef set to NULL
2216 len
= sizeof(flags
);
2217 len
+= sizeof(interfaceIndex
);
2218 len
+= sizeof(protocol
);
2219 len
+= sizeof(internalPort
);
2220 len
+= sizeof(externalPort
);
2223 hdr
= create_hdr(port_mapping_request
, &len
, &ptr
, (*sdRef
)->primary
? 1 : 0, *sdRef
);
2224 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
2226 put_flags(flags
, &ptr
);
2227 put_uint32(interfaceIndex
, &ptr
);
2228 put_uint32(protocol
, &ptr
);
2229 *ptr
++ = internalPort
.b
[0];
2230 *ptr
++ = internalPort
.b
[1];
2231 *ptr
++ = externalPort
.b
[0];
2232 *ptr
++ = externalPort
.b
[1];
2233 put_uint32(ttl
, &ptr
);
2235 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
2236 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
2240 #if _DNS_SD_LIBDISPATCH
2241 DNSServiceErrorType DNSSD_API DNSServiceSetDispatchQueue
2243 DNSServiceRef service
,
2244 dispatch_queue_t queue
2247 int dnssd_fd
= DNSServiceRefSockFD(service
);
2248 if (dnssd_fd
== dnssd_InvalidSocket
) return kDNSServiceErr_BadParam
;
2251 syslog(LOG_WARNING
, "dnssd_clientstub: DNSServiceSetDispatchQueue dispatch queue NULL");
2252 return kDNSServiceErr_BadParam
;
2254 if (service
->disp_queue
)
2256 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceSetDispatchQueue dispatch queue set already");
2257 return kDNSServiceErr_BadParam
;
2259 if (service
->disp_source
)
2261 syslog(LOG_WARNING
, "DNSServiceSetDispatchQueue dispatch source set already");
2262 return kDNSServiceErr_BadParam
;
2264 service
->disp_source
= dispatch_source_create(DISPATCH_SOURCE_TYPE_READ
, dnssd_fd
, 0, queue
);
2265 if (!service
->disp_source
)
2267 syslog(LOG_WARNING
, "DNSServiceSetDispatchQueue dispatch_source_create failed");
2268 return kDNSServiceErr_NoMemory
;
2270 service
->disp_queue
= queue
;
2271 dispatch_source_set_event_handler(service
->disp_source
, ^{DNSServiceProcessResult(service
);});
2272 dispatch_source_set_cancel_handler(service
->disp_source
, ^{dnssd_close(dnssd_fd
);});
2273 dispatch_resume(service
->disp_source
);
2274 return kDNSServiceErr_NoError
;
2276 #endif // _DNS_SD_LIBDISPATCH
2278 #if !defined(_WIN32)
2280 static void DNSSD_API
SleepKeepaliveCallback(DNSServiceRef sdRef
, DNSRecordRef rec
, const DNSServiceFlags flags
,
2281 DNSServiceErrorType errorCode
, void *context
)
2283 SleepKAContext
*ka
= (SleepKAContext
*)context
;
2284 (void)rec
; // Unused
2285 (void)flags
; // Unused
2287 if (sdRef
->kacontext
!= context
)
2288 syslog(LOG_WARNING
, "SleepKeepaliveCallback context mismatch");
2290 if (ka
->AppCallback
)
2291 ((DNSServiceSleepKeepaliveReply
)ka
->AppCallback
)(sdRef
, errorCode
, ka
->AppContext
);
2294 DNSServiceErrorType DNSSD_API DNSServiceSleepKeepalive
2296 DNSServiceRef
*sdRef
,
2297 DNSServiceFlags flags
,
2299 unsigned int timeout
,
2300 DNSServiceSleepKeepaliveReply callBack
,
2304 char source_str
[INET6_ADDRSTRLEN
];
2305 char target_str
[INET6_ADDRSTRLEN
];
2306 struct sockaddr_storage lss
;
2307 struct sockaddr_storage rss
;
2308 socklen_t len1
, len2
;
2309 unsigned int len
, proxyreclen
;
2311 DNSServiceErrorType err
;
2312 DNSRecordRef record
= NULL
;
2316 unsigned int i
, unique
;
2319 (void) flags
; //unused
2320 if (!timeout
) return kDNSServiceErr_BadParam
;
2324 if (getsockname(fd
, (struct sockaddr
*)&lss
, &len1
) < 0)
2326 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive: getsockname %d\n", errno
);
2327 return kDNSServiceErr_BadParam
;
2331 if (getpeername(fd
, (struct sockaddr
*)&rss
, &len2
) < 0)
2333 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive: getpeername %d\n", errno
);
2334 return kDNSServiceErr_BadParam
;
2339 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive local/remote info not same");
2340 return kDNSServiceErr_Unknown
;
2344 if (lss
.ss_family
== AF_INET
)
2346 struct sockaddr_in
*sl
= (struct sockaddr_in
*)&lss
;
2347 struct sockaddr_in
*sr
= (struct sockaddr_in
*)&rss
;
2348 unsigned char *ptr
= (unsigned char *)&sl
->sin_addr
;
2350 if (!inet_ntop(AF_INET
, (const void *)&sr
->sin_addr
, target_str
, sizeof (target_str
)))
2352 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive remote info failed %d", errno
);
2353 return kDNSServiceErr_Unknown
;
2355 if (!inet_ntop(AF_INET
, (const void *)&sl
->sin_addr
, source_str
, sizeof (source_str
)))
2357 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive local info failed %d", errno
);
2358 return kDNSServiceErr_Unknown
;
2360 // Sum of all bytes in the local address and port should result in a unique
2361 // number in the local network
2362 for (i
= 0; i
< sizeof(struct in_addr
); i
++)
2364 unique
+= sl
->sin_port
;
2365 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
));
2369 struct sockaddr_in6
*sl6
= (struct sockaddr_in6
*)&lss
;
2370 struct sockaddr_in6
*sr6
= (struct sockaddr_in6
*)&rss
;
2371 unsigned char *ptr
= (unsigned char *)&sl6
->sin6_addr
;
2373 if (!inet_ntop(AF_INET6
, (const void *)&sr6
->sin6_addr
, target_str
, sizeof (target_str
)))
2375 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive remote6 info failed %d", errno
);
2376 return kDNSServiceErr_Unknown
;
2378 if (!inet_ntop(AF_INET6
, (const void *)&sl6
->sin6_addr
, source_str
, sizeof (source_str
)))
2380 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive local6 info failed %d", errno
);
2381 return kDNSServiceErr_Unknown
;
2383 for (i
= 0; i
< sizeof(struct in6_addr
); i
++)
2385 unique
+= sl6
->sin6_port
;
2386 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
));
2389 if (len
>= (sizeof(buf
) - 1))
2391 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive could not fit local/remote info");
2392 return kDNSServiceErr_Unknown
;
2394 // Include the NULL byte also in the first byte. The total length of the record includes the
2397 proxyreclen
= len
+ 2;
2399 len
= snprintf(name
, sizeof(name
), "%u", unique
);
2400 if (len
>= sizeof(name
))
2402 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive could not fit unique");
2403 return kDNSServiceErr_Unknown
;
2406 len
= snprintf(recname
, sizeof(recname
), "%s.%s", name
, "_keepalive._dns-sd._udp.local");
2407 if (len
>= sizeof(recname
))
2409 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive could not fit name");
2410 return kDNSServiceErr_Unknown
;
2413 ka
= malloc(sizeof(SleepKAContext
));
2414 if (!ka
) return kDNSServiceErr_NoMemory
;
2415 ka
->AppCallback
= callBack
;
2416 ka
->AppContext
= context
;
2418 err
= DNSServiceCreateConnection(sdRef
);
2421 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive cannot create connection");
2426 // we don't care about the "record". When sdRef gets deallocated later, it will be freed too
2427 err
= DNSServiceRegisterRecord(*sdRef
, &record
, kDNSServiceFlagsUnique
, 0, recname
,
2428 kDNSServiceType_NULL
, kDNSServiceClass_IN
, proxyreclen
, buf
, kDNSServiceInterfaceIndexAny
, SleepKeepaliveCallback
, ka
);
2431 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive cannot create connection");
2435 (*sdRef
)->kacontext
= ka
;
2436 return kDNSServiceErr_NoError
;