1 /* -*- Mode: C; tab-width: 4 -*-
3 * Copyright (c) 2003-2004, Apple Computer, 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 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.
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 #if APPLE_OSX_mDNSResponder
33 #include <mach-o/dyld.h>
34 #include <uuid/uuid.h>
35 #include <TargetConditionals.h>
38 #include "dnssd_ipc.h"
40 static int gDaemonErr
= kDNSServiceErr_NoError
;
45 #include <CommonServices.h>
46 #include <DebugServices.h>
53 #define sockaddr_mdns sockaddr_in
54 #define AF_MDNS AF_INET
56 // Disable warning: "'type cast' : from data pointer 'void *' to function pointer"
57 #pragma warning(disable:4055)
59 // Disable warning: "nonstandard extension, function/data pointer conversion in expression"
60 #pragma warning(disable:4152)
62 extern BOOL
IsSystemServiceDisabled();
64 #define sleep(X) Sleep((X) * 1000)
66 static int g_initWinsock
= 0;
67 #define LOG_WARNING kDebugLevelWarning
68 #define LOG_INFO kDebugLevelInfo
69 static void syslog( int priority
, const char * message
, ...)
74 DWORD err
= WSAGetLastError();
76 va_start( args
, message
);
77 len
= _vscprintf( message
, args
) + 1;
78 buffer
= malloc( len
* sizeof(char) );
79 if ( buffer
) { vsprintf( buffer
, message
, args
); OutputDebugString( buffer
); free( buffer
); }
80 WSASetLastError( err
);
84 #include <sys/fcntl.h> // For O_RDWR etc.
86 #include <sys/socket.h>
89 #define sockaddr_mdns sockaddr_un
90 #define AF_MDNS AF_LOCAL
94 // <rdar://problem/4096913> Specifies how many times we'll try and connect to the server.
96 #define DNSSD_CLIENT_MAXTRIES 4
98 // Uncomment the line below to use the old error return mechanism of creating a temporary named socket (e.g. in /var/tmp)
99 //#define USE_NAMED_ERROR_RETURN_SOCKET 1
101 // If the UDS client has not received a response from the daemon in 60 secs, it is unlikely to get one
102 // Note: Timeout of 3 secs should be sufficient in normal scenarios, but 60 secs is chosen as a safeguard since
103 // some clients may come up before mDNSResponder itself after a BOOT and on rare ocassions IOPM/Keychain/D2D calls
104 // in mDNSResponder's INIT may take a much longer time to return
105 #define DNSSD_CLIENT_TIMEOUT 60
107 #ifndef CTL_PATH_PREFIX
108 #define CTL_PATH_PREFIX "/var/tmp/dnssd_result_socket."
114 DNSServiceFlags cb_flags
;
115 uint32_t cb_interface
;
116 DNSServiceErrorType cb_err
;
119 typedef struct _DNSServiceRef_t DNSServiceOp
;
120 typedef struct _DNSRecordRef_t DNSRecord
;
125 void *AppCallback
; // Client callback function and context
130 // client stub callback to process message from server and deliver results to client application
131 typedef void (*ProcessReplyFn
)(DNSServiceOp
*const sdr
, const CallbackHeader
*const cbh
, const char *msg
, const char *const end
);
133 #define ValidatorBits 0x12345678
134 #define DNSServiceRefValid(X) (dnssd_SocketValid((X)->sockfd) && (((X)->sockfd ^ (X)->validator) == ValidatorBits))
136 // When using kDNSServiceFlagsShareConnection, there is one primary _DNSServiceOp_t, and zero or more subordinates
137 // For the primary, the 'next' field points to the first subordinate, and its 'next' field points to the next, and so on.
138 // For the primary, the 'primary' field is NULL; for subordinates the 'primary' field points back to the associated primary
140 // _DNS_SD_LIBDISPATCH is defined where libdispatch/GCD is available. This does not mean that the application will use the
141 // DNSServiceSetDispatchQueue API. Hence any new code guarded with _DNS_SD_LIBDISPATCH should still be backwards compatible.
142 struct _DNSServiceRef_t
144 DNSServiceOp
*next
; // For shared connection
145 DNSServiceOp
*primary
; // For shared connection
146 dnssd_sock_t sockfd
; // Connected socket between client and daemon
147 dnssd_sock_t validator
; // Used to detect memory corruption, double disposals, etc.
148 client_context_t uid
; // For shared connection requests, each subordinate DNSServiceRef has its own ID,
149 // unique within the scope of the same shared parent DNSServiceRef
150 uint32_t op
; // request_op_t or reply_op_t
151 uint32_t max_index
; // Largest assigned record index - 0 if no additional records registered
152 uint32_t logcounter
; // Counter used to control number of syslog messages we write
153 int *moreptr
; // Set while DNSServiceProcessResult working on this particular DNSServiceRef
154 ProcessReplyFn ProcessReply
; // Function pointer to the code to handle received messages
155 void *AppCallback
; // Client callback function and context
158 #if _DNS_SD_LIBDISPATCH
159 dispatch_source_t disp_source
;
160 dispatch_queue_t disp_queue
;
165 struct _DNSRecordRef_t
169 DNSServiceRegisterRecordReply AppCallback
;
171 uint32_t record_index
; // index is unique to the ServiceDiscoveryRef
172 client_context_t uid
; // For demultiplexing multiple DNSServiceRegisterRecord calls
176 // Write len bytes. Return 0 on success, -1 on error
177 static int write_all(dnssd_sock_t sd
, char *buf
, size_t len
)
179 // Don't use "MSG_WAITALL"; it returns "Invalid argument" on some Linux versions; use an explicit while() loop instead.
180 //if (send(sd, buf, len, MSG_WAITALL) != len) return -1;
183 ssize_t num_written
= send(sd
, buf
, (long)len
, 0);
184 if (num_written
< 0 || (size_t)num_written
> len
)
186 // Should never happen. If it does, it indicates some OS bug,
187 // or that the mDNSResponder daemon crashed (which should never happen).
188 #if !defined(__ppc__) && defined(SO_ISDEFUNCT)
190 socklen_t dlen
= sizeof (defunct
);
191 if (getsockopt(sd
, SOL_SOCKET
, SO_ISDEFUNCT
, &defunct
, &dlen
) < 0)
192 syslog(LOG_WARNING
, "dnssd_clientstub write_all: SO_ISDEFUNCT failed %d %s", dnssd_errno
, dnssd_strerror(dnssd_errno
));
194 syslog(LOG_WARNING
, "dnssd_clientstub write_all(%d) failed %ld/%ld %d %s", sd
,
195 (long)num_written
, (long)len
,
196 (num_written
< 0) ? dnssd_errno
: 0,
197 (num_written
< 0) ? dnssd_strerror(dnssd_errno
) : "");
199 syslog(LOG_INFO
, "dnssd_clientstub write_all(%d) DEFUNCT", sd
);
201 syslog(LOG_WARNING
, "dnssd_clientstub write_all(%d) failed %ld/%ld %d %s", sd
,
202 (long)num_written
, (long)len
,
203 (num_written
< 0) ? dnssd_errno
: 0,
204 (num_written
< 0) ? dnssd_strerror(dnssd_errno
) : "");
214 enum { read_all_success
= 0, read_all_fail
= -1, read_all_wouldblock
= -2 };
216 // Read len bytes. Return 0 on success, read_all_fail on error, or read_all_wouldblock for
217 static int read_all(dnssd_sock_t sd
, char *buf
, int len
)
219 // Don't use "MSG_WAITALL"; it returns "Invalid argument" on some Linux versions; use an explicit while() loop instead.
220 //if (recv(sd, buf, len, MSG_WAITALL) != len) return -1;
224 ssize_t num_read
= recv(sd
, buf
, len
, 0);
225 // It is valid to get an interrupted system call error e.g., somebody attaching
226 // in a debugger, retry without failing
227 if ((num_read
< 0) && (errno
== EINTR
))
229 syslog(LOG_INFO
, "dnssd_clientstub read_all: EINTR continue");
232 if ((num_read
== 0) || (num_read
< 0) || (num_read
> len
))
236 // Should never happen. If it does, it indicates some OS bug,
237 // or that the mDNSResponder daemon crashed (which should never happen).
239 // <rdar://problem/7481776> Suppress logs for "A non-blocking socket operation
240 // could not be completed immediately"
241 if (WSAGetLastError() != WSAEWOULDBLOCK
)
244 #if !defined(__ppc__) && defined(SO_ISDEFUNCT)
246 socklen_t dlen
= sizeof (defunct
);
247 if (getsockopt(sd
, SOL_SOCKET
, SO_ISDEFUNCT
, &defunct
, &dlen
) < 0)
248 syslog(LOG_WARNING
, "dnssd_clientstub read_all: SO_ISDEFUNCT failed %d %s", dnssd_errno
, dnssd_strerror(dnssd_errno
));
254 syslog(LOG_WARNING
, "dnssd_clientstub read_all(%d) failed %ld/%ld %d %s", sd
,
255 (long)num_read
, (long)len
,
256 (num_read
< 0) ? dnssd_errno
: 0,
257 (num_read
< 0) ? dnssd_strerror(dnssd_errno
) : "");
259 syslog(LOG_INFO
, "dnssd_clientstub read_all(%d) DEFUNCT", sd
);
260 return (num_read
< 0 && dnssd_errno
== dnssd_EWOULDBLOCK
) ? read_all_wouldblock
: read_all_fail
;
265 return read_all_success
;
268 // Returns 1 if more bytes remain to be read on socket descriptor sd, 0 otherwise
269 static int more_bytes(dnssd_sock_t sd
)
271 struct timeval tv
= { 0, 0 };
283 // Compute the number of integers needed for storing "sd". Internally fd_set is stored
284 // as an array of ints with one bit for each fd and hence we need to compute
285 // the number of ints needed rather than the number of bytes. If "sd" is 32, we need
286 // two ints and not just one.
287 int nfdbits
= sizeof (int) * 8;
288 int nints
= (sd
/nfdbits
) + 1;
289 fs
= (fd_set
*)calloc(nints
, sizeof(int));
292 syslog(LOG_WARNING
, "dnssd_clientstub more_bytes: malloc failed");
297 ret
= select((int)sd
+1, fs
, (fd_set
*)NULL
, (fd_set
*)NULL
, &tv
);
303 // set_waitlimit() implements a timeout using select. It is called from deliver_request() before recv() OR accept()
304 // to ensure the UDS clients are not blocked in these system calls indefinitely.
305 // Note: Ideally one should never be blocked here, because it indicates either mDNSResponder daemon is not yet up/hung/
306 // superbusy/crashed or some other OS bug. For eg: On Windows which suffers from 3rd party software
307 // (primarily 3rd party firewall software) interfering with proper functioning of the TCP protocol stack it is possible
308 // the next operation on this socket(recv/accept) is blocked since we depend on TCP to communicate with the system service.
309 static int set_waitlimit(dnssd_sock_t sock
, int timeout
)
311 // To prevent stack corruption since select does not work with timeout if fds > FD_SETSIZE(1024)
312 if (!gDaemonErr
&& sock
< FD_SETSIZE
)
321 if (!select((int)(sock
+ 1), &set
, NULL
, NULL
, &tv
))
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
;
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.
341 static ipc_msg_hdr
*create_hdr(uint32_t op
, size_t *len
, char **data_start
, int SeparateReturnSocket
, DNSServiceOp
*ref
)
346 #if !defined(USE_TCP_LOOPBACK)
347 char ctrl_path
[64] = ""; // "/var/tmp/dnssd_result_socket.xxxxxxxxxx-xxx-xxxxxx"
350 if (SeparateReturnSocket
)
352 #if defined(USE_TCP_LOOPBACK)
353 *len
+= 2; // Allocate space for two-byte port number
354 #elif defined(USE_NAMED_ERROR_RETURN_SOCKET)
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;
362 *len
+= 1; // Allocate space for single zero byte (empty C string)
366 datalen
= (int) *len
;
367 *len
+= sizeof(ipc_msg_hdr
);
369 // Write message to buffer
371 if (!msg
) { syslog(LOG_WARNING
, "dnssd_clientstub create_hdr: malloc failed"); return NULL
; }
373 memset(msg
, 0, *len
);
374 hdr
= (ipc_msg_hdr
*)msg
;
375 hdr
->version
= VERSION
;
376 hdr
->datalen
= datalen
;
379 hdr
->client_context
= ref
->uid
;
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
);
387 if (SeparateReturnSocket
) put_string(ctrl_path
, data_start
);
392 static void FreeDNSRecords(DNSServiceOp
*sdRef
)
394 DNSRecord
*rec
= sdRef
->rec
;
397 DNSRecord
*next
= rec
->recnext
;
403 static void FreeDNSServiceOp(DNSServiceOp
*x
)
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
);
413 x
->sockfd
= dnssd_InvalidSocket
;
414 x
->validator
= 0xDDDDDDDD;
415 x
->op
= request_op_none
;
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
;
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
440 // Return a connected service ref (deallocate with DNSServiceRefDeallocate)
441 static DNSServiceErrorType
ConnectToServer(DNSServiceRef
*ref
, DNSServiceFlags flags
, uint32_t op
, ProcessReplyFn ProcessReply
, void *AppCallback
, void *AppContext
)
445 dnssd_sockaddr_t saddr
;
450 syslog(LOG_WARNING
, "dnssd_clientstub DNSService operation with NULL DNSServiceRef");
451 return kDNSServiceErr_BadParam
;
454 if (flags
& kDNSServiceFlagsShareConnection
)
458 syslog(LOG_WARNING
, "dnssd_clientstub kDNSServiceFlagsShareConnection used with NULL DNSServiceRef");
459 return kDNSServiceErr_BadParam
;
461 if (!DNSServiceRefValid(*ref
) || ((*ref
)->op
!= connection_request
&& (*ref
)->op
!= connection_delegate_request
) || (*ref
)->primary
)
463 syslog(LOG_WARNING
, "dnssd_clientstub kDNSServiceFlagsShareConnection used with invalid DNSServiceRef %p %08X %08X op %d",
464 (*ref
), (*ref
)->sockfd
, (*ref
)->validator
, (*ref
)->op
);
466 return kDNSServiceErr_BadReference
;
475 if (WSAStartup(MAKEWORD(2,2), &wsaData
) != 0) { *ref
= NULL
; return kDNSServiceErr_ServiceNotRunning
; }
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
;
482 sdr
= malloc(sizeof(DNSServiceOp
));
485 syslog(LOG_WARNING
, "dnssd_clientstub ConnectToServer: malloc failed");
487 return kDNSServiceErr_NoMemory
;
491 sdr
->sockfd
= dnssd_InvalidSocket
;
492 sdr
->validator
= sdr
->sockfd
^ ValidatorBits
;
499 sdr
->ProcessReply
= ProcessReply
;
500 sdr
->AppCallback
= AppCallback
;
501 sdr
->AppContext
= AppContext
;
503 #if _DNS_SD_LIBDISPATCH
504 sdr
->disp_source
= NULL
;
505 sdr
->disp_queue
= NULL
;
507 sdr
->kacontext
= NULL
;
509 if (flags
& kDNSServiceFlagsShareConnection
)
511 DNSServiceOp
**p
= &(*ref
)->next
; // Append ourselves to end of primary's list
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);
527 const unsigned long optval
= 1;
530 sdr
->sockfd
= socket(AF_DNSSD
, SOCK_STREAM
, 0);
531 sdr
->validator
= sdr
->sockfd
^ ValidatorBits
;
532 if (!dnssd_SocketValid(sdr
->sockfd
))
534 syslog(LOG_WARNING
, "dnssd_clientstub ConnectToServer: socket failed %d %s", dnssd_errno
, dnssd_strerror(dnssd_errno
));
535 FreeDNSServiceOp(sdr
);
536 return kDNSServiceErr_NoMemory
;
539 // Some environments (e.g. OS X) support turning off SIGPIPE for a socket
540 if (setsockopt(sdr
->sockfd
, SOL_SOCKET
, SO_NOSIGPIPE
, &optval
, sizeof(optval
)) < 0)
541 syslog(LOG_WARNING
, "dnssd_clientstub ConnectToServer: SO_NOSIGPIPE failed %d %s", dnssd_errno
, dnssd_strerror(dnssd_errno
));
543 #if defined(USE_TCP_LOOPBACK)
544 saddr
.sin_family
= AF_INET
;
545 saddr
.sin_addr
.s_addr
= inet_addr(MDNS_TCP_SERVERADDR
);
546 saddr
.sin_port
= htons(MDNS_TCP_SERVERPORT
);
548 saddr
.sun_family
= AF_LOCAL
;
549 strcpy(saddr
.sun_path
, MDNS_UDS_SERVERPATH
);
550 #if !defined(__ppc__) && defined(SO_DEFUNCTOK)
553 if (setsockopt(sdr
->sockfd
, SOL_SOCKET
, SO_DEFUNCTOK
, &defunct
, sizeof(defunct
)) < 0)
554 syslog(LOG_WARNING
, "dnssd_clientstub ConnectToServer: SO_DEFUNCTOK failed %d %s", dnssd_errno
, dnssd_strerror(dnssd_errno
));
561 int err
= connect(sdr
->sockfd
, (struct sockaddr
*) &saddr
, sizeof(saddr
));
563 break; // If we succeeded, return sdr
564 // If we failed, then it may be because the daemon is still launching.
565 // This can happen for processes that launch early in the boot process, while the
566 // daemon is still coming up. Rather than fail here, we wait 1 sec and try again.
567 // If, after DNSSD_CLIENT_MAXTRIES, we still can't connect to the daemon,
568 // then we give up and return a failure code.
569 if (++NumTries
< DNSSD_CLIENT_MAXTRIES
)
571 syslog(LOG_WARNING
, "dnssd_clientstub ConnectToServer: connect()-> No of tries: %d", NumTries
);
572 sleep(1); // Sleep a bit, then try again
576 syslog(LOG_WARNING
, "dnssd_clientstub ConnectToServer: connect() failed Socket:%d Err:%d Errno:%d %s",
577 sdr
->sockfd
, err
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
578 dnssd_close(sdr
->sockfd
);
579 FreeDNSServiceOp(sdr
);
580 return kDNSServiceErr_ServiceNotRunning
;
583 //printf("ConnectToServer opened socket %d\n", sdr->sockfd);
587 return kDNSServiceErr_NoError
;
590 #define deliver_request_bailout(MSG) \
591 do { syslog(LOG_WARNING, "dnssd_clientstub deliver_request: %s failed %d (%s)", (MSG), dnssd_errno, dnssd_strerror(dnssd_errno)); goto cleanup; } while(0)
593 static DNSServiceErrorType
deliver_request(ipc_msg_hdr
*hdr
, DNSServiceOp
*sdr
)
595 uint32_t datalen
= hdr
->datalen
; // We take a copy here because we're going to convert hdr->datalen to network byte order
596 #if defined(USE_TCP_LOOPBACK) || defined(USE_NAMED_ERROR_RETURN_SOCKET)
597 char *const data
= (char *)hdr
+ sizeof(ipc_msg_hdr
);
599 dnssd_sock_t listenfd
= dnssd_InvalidSocket
, errsd
= dnssd_InvalidSocket
;
600 DNSServiceErrorType err
= kDNSServiceErr_Unknown
; // Default for the "goto cleanup" cases
601 int MakeSeparateReturnSocket
= 0;
603 // Note: need to check hdr->op, not sdr->op.
604 // hdr->op contains the code for the specific operation we're currently doing, whereas sdr->op
605 // contains the original parent DNSServiceOp (e.g. for an add_record_request, hdr->op will be
606 // add_record_request but the parent sdr->op will be connection_request or reg_service_request)
608 hdr
->op
== reg_record_request
|| hdr
->op
== add_record_request
|| hdr
->op
== update_record_request
|| hdr
->op
== remove_record_request
)
609 MakeSeparateReturnSocket
= 1;
611 if (!DNSServiceRefValid(sdr
))
615 syslog(LOG_WARNING
, "dnssd_clientstub deliver_request: invalid DNSServiceRef %p %08X %08X", sdr
, sdr
->sockfd
, sdr
->validator
);
616 return kDNSServiceErr_BadReference
;
621 syslog(LOG_WARNING
, "dnssd_clientstub deliver_request: !hdr");
622 return kDNSServiceErr_Unknown
;
625 if (MakeSeparateReturnSocket
)
627 #if defined(USE_TCP_LOOPBACK)
629 union { uint16_t s
; u_char b
[2]; } port
;
630 dnssd_sockaddr_t caddr
;
631 dnssd_socklen_t len
= (dnssd_socklen_t
) sizeof(caddr
);
632 listenfd
= socket(AF_DNSSD
, SOCK_STREAM
, 0);
633 if (!dnssd_SocketValid(listenfd
)) deliver_request_bailout("TCP socket");
635 caddr
.sin_family
= AF_INET
;
637 caddr
.sin_addr
.s_addr
= inet_addr(MDNS_TCP_SERVERADDR
);
638 if (bind(listenfd
, (struct sockaddr
*) &caddr
, sizeof(caddr
)) < 0) deliver_request_bailout("TCP bind");
639 if (getsockname(listenfd
, (struct sockaddr
*) &caddr
, &len
) < 0) deliver_request_bailout("TCP getsockname");
640 if (listen(listenfd
, 1) < 0) deliver_request_bailout("TCP listen");
641 port
.s
= caddr
.sin_port
;
642 data
[0] = port
.b
[0]; // don't switch the byte order, as the
643 data
[1] = port
.b
[1]; // daemon expects it in network byte order
645 #elif defined(USE_NAMED_ERROR_RETURN_SOCKET)
649 dnssd_sockaddr_t caddr
;
650 listenfd
= socket(AF_DNSSD
, SOCK_STREAM
, 0);
651 if (!dnssd_SocketValid(listenfd
)) deliver_request_bailout("USE_NAMED_ERROR_RETURN_SOCKET socket");
653 caddr
.sun_family
= AF_LOCAL
;
654 // According to Stevens (section 3.2), there is no portable way to
655 // determine whether sa_len is defined on a particular platform.
656 #ifndef NOT_HAVE_SA_LEN
657 caddr
.sun_len
= sizeof(struct sockaddr_un
);
659 strcpy(caddr
.sun_path
, data
);
661 bindresult
= bind(listenfd
, (struct sockaddr
*)&caddr
, sizeof(caddr
));
663 if (bindresult
< 0) deliver_request_bailout("USE_NAMED_ERROR_RETURN_SOCKET bind");
664 if (listen(listenfd
, 1) < 0) deliver_request_bailout("USE_NAMED_ERROR_RETURN_SOCKET listen");
669 if (socketpair(AF_DNSSD
, SOCK_STREAM
, 0, sp
) < 0) deliver_request_bailout("socketpair");
672 errsd
= sp
[0]; // We'll read our four-byte error code from sp[0]
673 listenfd
= sp
[1]; // We'll send sp[1] to the daemon
674 #if !defined(__ppc__) && defined(SO_DEFUNCTOK)
677 if (setsockopt(errsd
, SOL_SOCKET
, SO_DEFUNCTOK
, &defunct
, sizeof(defunct
)) < 0)
678 syslog(LOG_WARNING
, "dnssd_clientstub ConnectToServer: SO_DEFUNCTOK failed %d %s", dnssd_errno
, dnssd_strerror(dnssd_errno
));
686 #if !defined(USE_TCP_LOOPBACK) && !defined(USE_NAMED_ERROR_RETURN_SOCKET)
687 // If we're going to make a separate error return socket, and pass it to the daemon
688 // using sendmsg, then we'll hold back one data byte to go with it.
689 // On some versions of Unix (including Leopard) sending a control message without
690 // any associated data does not work reliably -- e.g. one particular issue we ran
691 // into is that if the receiving program is in a kqueue loop waiting to be notified
692 // of the received message, it doesn't get woken up when the control message arrives.
693 if (MakeSeparateReturnSocket
|| sdr
->op
== send_bpf
)
694 datalen
--; // Okay to use sdr->op when checking for op == send_bpf
697 // At this point, our listening socket is set up and waiting, if necessary, for the daemon to connect back to
698 ConvertHeaderBytes(hdr
);
699 //syslog(LOG_WARNING, "dnssd_clientstub deliver_request writing %lu bytes", (unsigned long)(datalen + sizeof(ipc_msg_hdr)));
700 //if (MakeSeparateReturnSocket) syslog(LOG_WARNING, "dnssd_clientstub deliver_request name is %s", data);
701 #if TEST_SENDING_ONE_BYTE_AT_A_TIME
703 for (i
=0; i
<datalen
+ sizeof(ipc_msg_hdr
); i
++)
705 syslog(LOG_WARNING
, "dnssd_clientstub deliver_request writing %d", i
);
706 if (write_all(sdr
->sockfd
, ((char *)hdr
)+i
, 1) < 0)
707 { syslog(LOG_WARNING
, "write_all (byte %u) failed", i
); goto cleanup
; }
711 if (write_all(sdr
->sockfd
, (char *)hdr
, datalen
+ sizeof(ipc_msg_hdr
)) < 0)
713 // write_all already prints an error message if there is an error writing to
714 // the socket except for DEFUNCT. Logging here is unnecessary and also wrong
715 // in the case of DEFUNCT sockets
716 syslog(LOG_INFO
, "dnssd_clientstub deliver_request ERROR: write_all(%d, %lu bytes) failed",
717 sdr
->sockfd
, (unsigned long)(datalen
+ sizeof(ipc_msg_hdr
)));
722 if (!MakeSeparateReturnSocket
)
724 if (MakeSeparateReturnSocket
|| sdr
->op
== send_bpf
) // Okay to use sdr->op when checking for op == send_bpf
726 #if defined(USE_TCP_LOOPBACK) || defined(USE_NAMED_ERROR_RETURN_SOCKET)
727 // At this point we may wait in accept for a few milliseconds waiting for the daemon to connect back to us,
728 // but that's okay -- the daemon should not take more than a few milliseconds to respond.
729 // set_waitlimit() ensures we do not block indefinitely just in case something is wrong
730 dnssd_sockaddr_t daddr
;
731 dnssd_socklen_t len
= sizeof(daddr
);
732 if ((err
= set_waitlimit(listenfd
, DNSSD_CLIENT_TIMEOUT
)) != kDNSServiceErr_NoError
)
734 errsd
= accept(listenfd
, (struct sockaddr
*)&daddr
, &len
);
735 if (!dnssd_SocketValid(errsd
))
736 deliver_request_bailout("accept");
739 struct iovec vec
= { ((char *)hdr
) + sizeof(ipc_msg_hdr
) + datalen
, 1 }; // Send the last byte along with the SCM_RIGHTS
741 struct cmsghdr
*cmsg
;
742 char cbuf
[CMSG_SPACE(4 * sizeof(dnssd_sock_t
))];
749 if (MakeSeparateReturnSocket
|| sdr
->op
== send_bpf
) // Okay to use sdr->op when checking for op == send_bpf
751 if (sdr
->op
== send_bpf
)
754 char p
[12]; // Room for "/dev/bpf999" with terminating null
755 for (i
=0; i
<100; i
++)
757 snprintf(p
, sizeof(p
), "/dev/bpf%d", i
);
758 listenfd
= open(p
, O_RDWR
, 0);
759 //if (dnssd_SocketValid(listenfd)) syslog(LOG_WARNING, "Sending fd %d for %s", listenfd, p);
760 if (!dnssd_SocketValid(listenfd
) && dnssd_errno
!= EBUSY
)
761 syslog(LOG_WARNING
, "Error opening %s %d (%s)", p
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
762 if (dnssd_SocketValid(listenfd
) || dnssd_errno
!= EBUSY
) break;
765 msg
.msg_control
= cbuf
;
766 msg
.msg_controllen
= CMSG_LEN(sizeof(dnssd_sock_t
));
768 cmsg
= CMSG_FIRSTHDR(&msg
);
769 cmsg
->cmsg_len
= CMSG_LEN(sizeof(dnssd_sock_t
));
770 cmsg
->cmsg_level
= SOL_SOCKET
;
771 cmsg
->cmsg_type
= SCM_RIGHTS
;
772 *((dnssd_sock_t
*)CMSG_DATA(cmsg
)) = listenfd
;
775 #if TEST_KQUEUE_CONTROL_MESSAGE_BUG
779 #if DEBUG_64BIT_SCM_RIGHTS
780 syslog(LOG_WARNING
, "dnssd_clientstub sendmsg read sd=%d write sd=%d %ld %ld %ld/%ld/%ld/%ld",
781 errsd
, listenfd
, sizeof(dnssd_sock_t
), sizeof(void*),
782 sizeof(struct cmsghdr
) + sizeof(dnssd_sock_t
),
783 CMSG_LEN(sizeof(dnssd_sock_t
)), (long)CMSG_SPACE(sizeof(dnssd_sock_t
)),
784 (long)((char*)CMSG_DATA(cmsg
) + 4 - cbuf
));
785 #endif // DEBUG_64BIT_SCM_RIGHTS
787 if (sendmsg(sdr
->sockfd
, &msg
, 0) < 0)
789 syslog(LOG_WARNING
, "dnssd_clientstub deliver_request ERROR: sendmsg failed read sd=%d write sd=%d errno %d (%s)",
790 errsd
, listenfd
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
791 err
= kDNSServiceErr_Incompatible
;
795 #if DEBUG_64BIT_SCM_RIGHTS
796 syslog(LOG_WARNING
, "dnssd_clientstub sendmsg read sd=%d write sd=%d okay", errsd
, listenfd
);
797 #endif // DEBUG_64BIT_SCM_RIGHTS
800 // Close our end of the socketpair *before* calling read_all() to get the four-byte error code.
801 // Otherwise, if the daemon closes our socket (or crashes), we will have to wait for a timeout
802 // in read_all() because the socket is not closed (we still have an open reference to it)
803 // Note: listenfd is overwritten in the case of send_bpf above and that will be closed here
804 // for send_bpf operation.
805 dnssd_close(listenfd
);
806 listenfd
= dnssd_InvalidSocket
; // Make sure we don't close it a second time in the cleanup handling below
809 // At this point we may wait in read_all for a few milliseconds waiting for the daemon to send us the error code,
810 // but that's okay -- the daemon should not take more than a few milliseconds to respond.
811 // set_waitlimit() ensures we do not block indefinitely just in case something is wrong
812 if (sdr
->op
== send_bpf
) // Okay to use sdr->op when checking for op == send_bpf
813 err
= kDNSServiceErr_NoError
;
814 else if ((err
= set_waitlimit(errsd
, DNSSD_CLIENT_TIMEOUT
)) == kDNSServiceErr_NoError
)
816 if (read_all(errsd
, (char*)&err
, (int)sizeof(err
)) < 0)
817 err
= kDNSServiceErr_ServiceNotRunning
; // On failure read_all will have written a message to syslog for us
821 //syslog(LOG_WARNING, "dnssd_clientstub deliver_request: retrieved error code %d", err);
824 if (MakeSeparateReturnSocket
)
826 if (dnssd_SocketValid(listenfd
)) dnssd_close(listenfd
);
827 if (dnssd_SocketValid(errsd
)) dnssd_close(errsd
);
828 #if defined(USE_NAMED_ERROR_RETURN_SOCKET)
829 // syslog(LOG_WARNING, "dnssd_clientstub deliver_request: removing UDS: %s", data);
830 if (unlink(data
) != 0)
831 syslog(LOG_WARNING
, "dnssd_clientstub WARNING: unlink(\"%s\") failed errno %d (%s)", data
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
832 // else syslog(LOG_WARNING, "dnssd_clientstub deliver_request: removed UDS: %s", data);
840 int DNSSD_API
DNSServiceRefSockFD(DNSServiceRef sdRef
)
842 if (!sdRef
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRefSockFD called with NULL DNSServiceRef"); return dnssd_InvalidSocket
; }
844 if (!DNSServiceRefValid(sdRef
))
846 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRefSockFD called with invalid DNSServiceRef %p %08X %08X",
847 sdRef
, sdRef
->sockfd
, sdRef
->validator
);
848 return dnssd_InvalidSocket
;
853 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRefSockFD undefined for kDNSServiceFlagsShareConnection subordinate DNSServiceRef %p", sdRef
);
854 return dnssd_InvalidSocket
;
857 return (int) sdRef
->sockfd
;
860 #if _DNS_SD_LIBDISPATCH
861 static void CallbackWithError(DNSServiceRef sdRef
, DNSServiceErrorType error
)
863 DNSServiceOp
*sdr
= sdRef
;
864 DNSServiceOp
*sdrNext
;
871 // We can't touch the sdr after the callback as it can be deallocated in the callback
874 sdr
->moreptr
= &morebytes
;
877 case resolve_request
:
878 if (sdr
->AppCallback
) ((DNSServiceResolveReply
) sdr
->AppCallback
)(sdr
, 0, 0, error
, NULL
, 0, 0, 0, NULL
, sdr
->AppContext
);
881 if (sdr
->AppCallback
) ((DNSServiceQueryRecordReply
)sdr
->AppCallback
)(sdr
, 0, 0, error
, NULL
, 0, 0, 0, NULL
, 0, sdr
->AppContext
);
883 case addrinfo_request
:
884 if (sdr
->AppCallback
) ((DNSServiceGetAddrInfoReply
)sdr
->AppCallback
)(sdr
, 0, 0, error
, NULL
, NULL
, 0, sdr
->AppContext
);
887 if (sdr
->AppCallback
) ((DNSServiceBrowseReply
) sdr
->AppCallback
)(sdr
, 0, 0, error
, NULL
, 0, NULL
, sdr
->AppContext
);
889 case reg_service_request
:
890 if (sdr
->AppCallback
) ((DNSServiceRegisterReply
) sdr
->AppCallback
)(sdr
, 0, error
, NULL
, 0, NULL
, sdr
->AppContext
);
892 case enumeration_request
:
893 if (sdr
->AppCallback
) ((DNSServiceDomainEnumReply
) sdr
->AppCallback
)(sdr
, 0, 0, error
, NULL
, sdr
->AppContext
);
895 case connection_request
:
896 case connection_delegate_request
:
897 // This means Register Record, walk the list of DNSRecords to do the callback
901 recnext
= rec
->recnext
;
902 if (rec
->AppCallback
) ((DNSServiceRegisterRecordReply
)rec
->AppCallback
)(sdr
, 0, 0, error
, rec
->AppContext
);
903 // The Callback can call DNSServiceRefDeallocate which in turn frees sdr and all the records.
904 // Detect that and return early
905 if (!morebytes
) {syslog(LOG_WARNING
, "dnssdclientstub:Record: CallbackwithError morebytes zero"); return;}
909 case port_mapping_request
:
910 if (sdr
->AppCallback
) ((DNSServiceNATPortMappingReply
)sdr
->AppCallback
)(sdr
, 0, 0, error
, 0, 0, 0, 0, 0, sdr
->AppContext
);
913 syslog(LOG_WARNING
, "dnssd_clientstub CallbackWithError called with bad op %d", sdr
->op
);
915 // If DNSServiceRefDeallocate was called in the callback, morebytes will be zero. As the sdRef
916 // (and its subordinates) have been freed, we should not proceed further. Note that when we
917 // call the callback with a subordinate sdRef the application can call DNSServiceRefDeallocate
918 // on the main sdRef and DNSServiceRefDeallocate handles this case by walking all the sdRefs and
919 // clears the moreptr so that we can terminate here.
921 // If DNSServiceRefDeallocate was not called in the callback, then set moreptr to NULL so that
922 // we don't access the stack variable after we return from this function.
923 if (!morebytes
) {syslog(LOG_WARNING
, "dnssdclientstub:sdRef: CallbackwithError morebytes zero sdr %p", sdr
); return;}
924 else {sdr
->moreptr
= NULL
;}
928 #endif // _DNS_SD_LIBDISPATCH
930 // Handle reply from server, calling application client callback. If there is no reply
931 // from the daemon on the socket contained in sdRef, the call will block.
932 DNSServiceErrorType DNSSD_API
DNSServiceProcessResult(DNSServiceRef sdRef
)
936 if (!sdRef
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceProcessResult called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam
; }
938 if (!DNSServiceRefValid(sdRef
))
940 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceProcessResult called with invalid DNSServiceRef %p %08X %08X", sdRef
, sdRef
->sockfd
, sdRef
->validator
);
941 return kDNSServiceErr_BadReference
;
946 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceProcessResult undefined for kDNSServiceFlagsShareConnection subordinate DNSServiceRef %p", sdRef
);
947 return kDNSServiceErr_BadReference
;
950 if (!sdRef
->ProcessReply
)
952 static int num_logs
= 0;
953 if (num_logs
< 10) syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceProcessResult called with DNSServiceRef with no ProcessReply function");
954 if (num_logs
< 1000) num_logs
++;else sleep(1);
955 return kDNSServiceErr_BadReference
;
963 // return NoError on EWOULDBLOCK. This will handle the case
964 // where a non-blocking socket is told there is data, but it was a false positive.
965 // On error, read_all will write a message to syslog for us, so don't need to duplicate that here
966 // Note: If we want to properly support using non-blocking sockets in the future
967 int result
= read_all(sdRef
->sockfd
, (void *)&cbh
.ipc_hdr
, sizeof(cbh
.ipc_hdr
));
968 if (result
== read_all_fail
)
970 // Set the ProcessReply to NULL before callback as the sdRef can get deallocated
972 sdRef
->ProcessReply
= NULL
;
973 #if _DNS_SD_LIBDISPATCH
974 // Call the callbacks with an error if using the dispatch API, as DNSServiceProcessResult
975 // is not called by the application and hence need to communicate the error. Cancel the
976 // source so that we don't get any more events
977 // Note: read_all fails if we could not read from the daemon which can happen if the
978 // daemon dies or the file descriptor is disconnected (defunct).
979 if (sdRef
->disp_source
)
981 dispatch_source_cancel(sdRef
->disp_source
);
982 dispatch_release(sdRef
->disp_source
);
983 sdRef
->disp_source
= NULL
;
984 CallbackWithError(sdRef
, kDNSServiceErr_ServiceNotRunning
);
987 // Don't touch sdRef anymore as it might have been deallocated
988 return kDNSServiceErr_ServiceNotRunning
;
990 else if (result
== read_all_wouldblock
)
992 if (morebytes
&& sdRef
->logcounter
< 100)
995 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceProcessResult error: select indicated data was waiting but read_all returned EWOULDBLOCK");
997 return kDNSServiceErr_NoError
;
1000 ConvertHeaderBytes(&cbh
.ipc_hdr
);
1001 if (cbh
.ipc_hdr
.version
!= VERSION
)
1003 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceProcessResult daemon version %d does not match client version %d", cbh
.ipc_hdr
.version
, VERSION
);
1004 sdRef
->ProcessReply
= NULL
;
1005 return kDNSServiceErr_Incompatible
;
1008 data
= malloc(cbh
.ipc_hdr
.datalen
);
1009 if (!data
) return kDNSServiceErr_NoMemory
;
1010 if (read_all(sdRef
->sockfd
, data
, cbh
.ipc_hdr
.datalen
) < 0) // On error, read_all will write a message to syslog for us
1012 // Set the ProcessReply to NULL before callback as the sdRef can get deallocated
1014 sdRef
->ProcessReply
= NULL
;
1015 #if _DNS_SD_LIBDISPATCH
1016 // Call the callbacks with an error if using the dispatch API, as DNSServiceProcessResult
1017 // is not called by the application and hence need to communicate the error. Cancel the
1018 // source so that we don't get any more events
1019 if (sdRef
->disp_source
)
1021 dispatch_source_cancel(sdRef
->disp_source
);
1022 dispatch_release(sdRef
->disp_source
);
1023 sdRef
->disp_source
= NULL
;
1024 CallbackWithError(sdRef
, kDNSServiceErr_ServiceNotRunning
);
1027 // Don't touch sdRef anymore as it might have been deallocated
1029 return kDNSServiceErr_ServiceNotRunning
;
1033 const char *ptr
= data
;
1034 cbh
.cb_flags
= get_flags (&ptr
, data
+ cbh
.ipc_hdr
.datalen
);
1035 cbh
.cb_interface
= get_uint32 (&ptr
, data
+ cbh
.ipc_hdr
.datalen
);
1036 cbh
.cb_err
= get_error_code(&ptr
, data
+ cbh
.ipc_hdr
.datalen
);
1038 // CAUTION: We have to handle the case where the client calls DNSServiceRefDeallocate from within the callback function.
1039 // To do this we set moreptr to point to morebytes. If the client does call DNSServiceRefDeallocate(),
1040 // then that routine will clear morebytes for us, and cause us to exit our loop.
1041 morebytes
= more_bytes(sdRef
->sockfd
);
1044 cbh
.cb_flags
|= kDNSServiceFlagsMoreComing
;
1045 sdRef
->moreptr
= &morebytes
;
1047 if (ptr
) sdRef
->ProcessReply(sdRef
, &cbh
, ptr
, data
+ cbh
.ipc_hdr
.datalen
);
1048 // Careful code here:
1049 // If morebytes is non-zero, that means we set sdRef->moreptr above, and the operation was not
1050 // cancelled out from under us, so now we need to clear sdRef->moreptr so we don't leave a stray
1051 // dangling pointer pointing to a long-gone stack variable.
1052 // If morebytes is zero, then one of two thing happened:
1053 // (a) morebytes was 0 above, so we didn't set sdRef->moreptr, so we don't need to clear it
1054 // (b) morebytes was 1 above, and we set sdRef->moreptr, but the operation was cancelled (with DNSServiceRefDeallocate()),
1055 // so we MUST NOT try to dereference our stale sdRef pointer.
1056 if (morebytes
) sdRef
->moreptr
= NULL
;
1059 } while (morebytes
);
1061 return kDNSServiceErr_NoError
;
1064 void DNSSD_API
DNSServiceRefDeallocate(DNSServiceRef sdRef
)
1066 if (!sdRef
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRefDeallocate called with NULL DNSServiceRef"); return; }
1068 if (!DNSServiceRefValid(sdRef
)) // Also verifies dnssd_SocketValid(sdRef->sockfd) for us too
1070 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRefDeallocate called with invalid DNSServiceRef %p %08X %08X", sdRef
, sdRef
->sockfd
, sdRef
->validator
);
1074 // 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
1075 if (sdRef
->moreptr
) *(sdRef
->moreptr
) = 0;
1077 if (sdRef
->primary
) // If this is a subordinate DNSServiceOp, just send a 'stop' command
1079 DNSServiceOp
**p
= &sdRef
->primary
->next
;
1080 while (*p
&& *p
!= sdRef
) p
= &(*p
)->next
;
1085 ipc_msg_hdr
*hdr
= create_hdr(cancel_request
, &len
, &ptr
, 0, sdRef
);
1088 ConvertHeaderBytes(hdr
);
1089 write_all(sdRef
->sockfd
, (char *)hdr
, len
);
1093 FreeDNSServiceOp(sdRef
);
1096 else // else, make sure to terminate all subordinates as well
1098 #if _DNS_SD_LIBDISPATCH
1099 // The cancel handler will close the fd if a dispatch source has been set
1100 if (sdRef
->disp_source
)
1102 // By setting the ProcessReply to NULL, we make sure that we never call
1103 // the application callbacks ever, after returning from this function. We
1104 // assume that DNSServiceRefDeallocate is called from the serial queue
1105 // that was passed to DNSServiceSetDispatchQueue. Hence, dispatch_source_cancel
1106 // should cancel all the blocks on the queue and hence there should be no more
1107 // callbacks when we return from this function. Setting ProcessReply to NULL
1108 // provides extra protection.
1109 sdRef
->ProcessReply
= NULL
;
1110 dispatch_source_cancel(sdRef
->disp_source
);
1111 dispatch_release(sdRef
->disp_source
);
1112 sdRef
->disp_source
= NULL
;
1114 // if disp_queue is set, it means it used the DNSServiceSetDispatchQueue API. In that case,
1115 // when the source was cancelled, the fd was closed in the handler. Currently the source
1116 // is cancelled only when the mDNSResponder daemon dies
1117 else if (!sdRef
->disp_queue
) dnssd_close(sdRef
->sockfd
);
1119 dnssd_close(sdRef
->sockfd
);
1121 // Free DNSRecords added in DNSRegisterRecord if they have not
1122 // been freed in DNSRemoveRecord
1125 DNSServiceOp
*p
= sdRef
;
1126 sdRef
= sdRef
->next
;
1127 // When there is an error reading from the daemon e.g., bad fd, CallbackWithError
1128 // is called which sets moreptr. It might set the moreptr on a subordinate sdRef
1129 // but the application might call DNSServiceRefDeallocate with the main sdRef from
1130 // the callback. Hence, when we loop through the subordinate sdRefs, we need
1131 // to clear the moreptr so that CallbackWithError can terminate itself instead of
1132 // walking through the freed sdRefs.
1133 if (p
->moreptr
) *(p
->moreptr
) = 0;
1134 FreeDNSServiceOp(p
);
1139 DNSServiceErrorType DNSSD_API
DNSServiceGetProperty(const char *property
, void *result
, uint32_t *size
)
1142 size_t len
= strlen(property
) + 1;
1145 uint32_t actualsize
;
1147 DNSServiceErrorType err
= ConnectToServer(&tmp
, 0, getproperty_request
, NULL
, NULL
, NULL
);
1148 if (err
) return err
;
1150 hdr
= create_hdr(getproperty_request
, &len
, &ptr
, 0, tmp
);
1151 if (!hdr
) { DNSServiceRefDeallocate(tmp
); return kDNSServiceErr_NoMemory
; }
1153 put_string(property
, &ptr
);
1154 err
= deliver_request(hdr
, tmp
); // Will free hdr for us
1155 if (read_all(tmp
->sockfd
, (char*)&actualsize
, (int)sizeof(actualsize
)) < 0)
1156 { DNSServiceRefDeallocate(tmp
); return kDNSServiceErr_ServiceNotRunning
; }
1158 actualsize
= ntohl(actualsize
);
1159 if (read_all(tmp
->sockfd
, (char*)result
, actualsize
< *size
? actualsize
: *size
) < 0)
1160 { DNSServiceRefDeallocate(tmp
); return kDNSServiceErr_ServiceNotRunning
; }
1161 DNSServiceRefDeallocate(tmp
);
1163 // Swap version result back to local process byte order
1164 if (!strcmp(property
, kDNSServiceProperty_DaemonVersion
) && *size
>= 4)
1165 *(uint32_t*)result
= ntohl(*(uint32_t*)result
);
1168 return kDNSServiceErr_NoError
;
1171 DNSServiceErrorType DNSSD_API
DNSServiceGetPID(const uint16_t srcport
, int32_t *pid
)
1176 size_t len
= sizeof(int32_t);
1178 DNSServiceErrorType err
= ConnectToServer(&tmp
, 0, getpid_request
, NULL
, NULL
, NULL
);
1182 hdr
= create_hdr(getpid_request
, &len
, &ptr
, 0, tmp
);
1185 DNSServiceRefDeallocate(tmp
);
1186 return kDNSServiceErr_NoMemory
;
1189 put_uint16(srcport
, &ptr
);
1190 err
= deliver_request(hdr
, tmp
); // Will free hdr for us
1192 if (read_all(tmp
->sockfd
, (char*)pid
, sizeof(int32_t)) < 0)
1194 DNSServiceRefDeallocate(tmp
);
1195 return kDNSServiceErr_ServiceNotRunning
;
1198 DNSServiceRefDeallocate(tmp
);
1199 return kDNSServiceErr_NoError
;
1202 static void handle_resolve_response(DNSServiceOp
*const sdr
, const CallbackHeader
*const cbh
, const char *data
, const char *end
)
1204 char fullname
[kDNSServiceMaxDomainName
];
1205 char target
[kDNSServiceMaxDomainName
];
1207 union { uint16_t s
; u_char b
[2]; } port
;
1208 unsigned char *txtrecord
;
1210 get_string(&data
, end
, fullname
, kDNSServiceMaxDomainName
);
1211 get_string(&data
, end
, target
, kDNSServiceMaxDomainName
);
1212 if (!data
|| data
+ 2 > end
) goto fail
;
1214 port
.b
[0] = *data
++;
1215 port
.b
[1] = *data
++;
1216 txtlen
= get_uint16(&data
, end
);
1217 txtrecord
= (unsigned char *)get_rdata(&data
, end
, txtlen
);
1219 if (!data
) goto fail
;
1220 ((DNSServiceResolveReply
)sdr
->AppCallback
)(sdr
, cbh
->cb_flags
, cbh
->cb_interface
, cbh
->cb_err
, fullname
, target
, port
.s
, txtlen
, txtrecord
, sdr
->AppContext
);
1222 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1224 syslog(LOG_WARNING
, "dnssd_clientstub handle_resolve_response: error reading result from daemon");
1227 #if APPLE_OSX_mDNSResponder
1229 static int32_t libSystemVersion
= 0;
1231 // Return true if the application linked against a version of libsystem where P2P
1232 // interfaces were included by default when using kDNSServiceInterfaceIndexAny.
1233 // Using 160.0.0 == 0xa00000 as the version threshold.
1234 static int includeP2PWithIndexAny()
1236 if (libSystemVersion
== 0)
1237 libSystemVersion
= NSVersionOfLinkTimeLibrary("System");
1239 if (libSystemVersion
< 0xa00000)
1245 #else // APPLE_OSX_mDNSResponder
1247 // always return false for non Apple platforms
1248 static int includeP2PWithIndexAny()
1253 #endif // APPLE_OSX_mDNSResponder
1255 DNSServiceErrorType DNSSD_API DNSServiceResolve
1257 DNSServiceRef
*sdRef
,
1258 DNSServiceFlags flags
,
1259 uint32_t interfaceIndex
,
1261 const char *regtype
,
1263 DNSServiceResolveReply callBack
,
1270 DNSServiceErrorType err
;
1272 if (!name
|| !regtype
|| !domain
|| !callBack
) return kDNSServiceErr_BadParam
;
1274 // Need a real InterfaceID for WakeOnResolve
1275 if ((flags
& kDNSServiceFlagsWakeOnResolve
) != 0 &&
1276 ((interfaceIndex
== kDNSServiceInterfaceIndexAny
) ||
1277 (interfaceIndex
== kDNSServiceInterfaceIndexLocalOnly
) ||
1278 (interfaceIndex
== kDNSServiceInterfaceIndexUnicast
) ||
1279 (interfaceIndex
== kDNSServiceInterfaceIndexP2P
)))
1281 return kDNSServiceErr_BadParam
;
1284 if ((interfaceIndex
== kDNSServiceInterfaceIndexAny
) && includeP2PWithIndexAny())
1285 flags
|= kDNSServiceFlagsIncludeP2P
;
1287 err
= ConnectToServer(sdRef
, flags
, resolve_request
, handle_resolve_response
, callBack
, context
);
1288 if (err
) return err
; // On error ConnectToServer leaves *sdRef set to NULL
1290 // Calculate total message length
1291 len
= sizeof(flags
);
1292 len
+= sizeof(interfaceIndex
);
1293 len
+= strlen(name
) + 1;
1294 len
+= strlen(regtype
) + 1;
1295 len
+= strlen(domain
) + 1;
1297 hdr
= create_hdr(resolve_request
, &len
, &ptr
, (*sdRef
)->primary
? 1 : 0, *sdRef
);
1298 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
1300 put_flags(flags
, &ptr
);
1301 put_uint32(interfaceIndex
, &ptr
);
1302 put_string(name
, &ptr
);
1303 put_string(regtype
, &ptr
);
1304 put_string(domain
, &ptr
);
1306 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1307 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
1311 static void handle_query_response(DNSServiceOp
*const sdr
, const CallbackHeader
*const cbh
, const char *data
, const char *const end
)
1314 char name
[kDNSServiceMaxDomainName
];
1315 uint16_t rrtype
, rrclass
, rdlen
;
1318 get_string(&data
, end
, name
, kDNSServiceMaxDomainName
);
1319 rrtype
= get_uint16(&data
, end
);
1320 rrclass
= get_uint16(&data
, end
);
1321 rdlen
= get_uint16(&data
, end
);
1322 rdata
= get_rdata(&data
, end
, rdlen
);
1323 ttl
= get_uint32(&data
, end
);
1325 if (!data
) syslog(LOG_WARNING
, "dnssd_clientstub handle_query_response: error reading result from daemon");
1326 else ((DNSServiceQueryRecordReply
)sdr
->AppCallback
)(sdr
, cbh
->cb_flags
, cbh
->cb_interface
, cbh
->cb_err
, name
, rrtype
, rrclass
, rdlen
, rdata
, ttl
, sdr
->AppContext
);
1327 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1330 DNSServiceErrorType DNSSD_API DNSServiceQueryRecord
1332 DNSServiceRef
*sdRef
,
1333 DNSServiceFlags flags
,
1334 uint32_t interfaceIndex
,
1338 DNSServiceQueryRecordReply callBack
,
1345 DNSServiceErrorType err
;
1347 if ((interfaceIndex
== kDNSServiceInterfaceIndexAny
) && includeP2PWithIndexAny())
1348 flags
|= kDNSServiceFlagsIncludeP2P
;
1350 err
= ConnectToServer(sdRef
, flags
, query_request
, handle_query_response
, callBack
, context
);
1351 if (err
) return err
; // On error ConnectToServer leaves *sdRef set to NULL
1353 if (!name
) name
= "\0";
1355 // Calculate total message length
1356 len
= sizeof(flags
);
1357 len
+= sizeof(uint32_t); // interfaceIndex
1358 len
+= strlen(name
) + 1;
1359 len
+= 2 * sizeof(uint16_t); // rrtype, rrclass
1361 hdr
= create_hdr(query_request
, &len
, &ptr
, (*sdRef
)->primary
? 1 : 0, *sdRef
);
1362 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
1364 put_flags(flags
, &ptr
);
1365 put_uint32(interfaceIndex
, &ptr
);
1366 put_string(name
, &ptr
);
1367 put_uint16(rrtype
, &ptr
);
1368 put_uint16(rrclass
, &ptr
);
1370 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1371 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
1375 static void handle_addrinfo_response(DNSServiceOp
*const sdr
, const CallbackHeader
*const cbh
, const char *data
, const char *const end
)
1377 char hostname
[kDNSServiceMaxDomainName
];
1378 uint16_t rrtype
, rrclass
, rdlen
;
1382 get_string(&data
, end
, hostname
, kDNSServiceMaxDomainName
);
1383 rrtype
= get_uint16(&data
, end
);
1384 rrclass
= get_uint16(&data
, end
);
1385 rdlen
= get_uint16(&data
, end
);
1386 rdata
= get_rdata (&data
, end
, rdlen
);
1387 ttl
= get_uint32(&data
, end
);
1389 // We only generate client callbacks for A and AAAA results (including NXDOMAIN results for
1390 // those types, if the client has requested those with the kDNSServiceFlagsReturnIntermediates).
1391 // Other result types, specifically CNAME referrals, are not communicated to the client, because
1392 // the DNSServiceGetAddrInfoReply interface doesn't have any meaningful way to communiate CNAME referrals.
1393 if (!data
) syslog(LOG_WARNING
, "dnssd_clientstub handle_addrinfo_response: error reading result from daemon");
1394 else if (rrtype
== kDNSServiceType_A
|| rrtype
== kDNSServiceType_AAAA
)
1396 struct sockaddr_in sa4
;
1397 struct sockaddr_in6 sa6
;
1398 const struct sockaddr
*const sa
= (rrtype
== kDNSServiceType_A
) ? (struct sockaddr
*)&sa4
: (struct sockaddr
*)&sa6
;
1399 if (rrtype
== kDNSServiceType_A
)
1401 memset(&sa4
, 0, sizeof(sa4
));
1402 #ifndef NOT_HAVE_SA_LEN
1403 sa4
.sin_len
= sizeof(struct sockaddr_in
);
1405 sa4
.sin_family
= AF_INET
;
1407 if (!cbh
->cb_err
) memcpy(&sa4
.sin_addr
, rdata
, rdlen
);
1411 memset(&sa6
, 0, sizeof(sa6
));
1412 #ifndef NOT_HAVE_SA_LEN
1413 sa6
.sin6_len
= sizeof(struct sockaddr_in6
);
1415 sa6
.sin6_family
= AF_INET6
;
1417 // sin6_flowinfo = 0;
1418 // sin6_scope_id = 0;
1421 memcpy(&sa6
.sin6_addr
, rdata
, rdlen
);
1422 if (IN6_IS_ADDR_LINKLOCAL(&sa6
.sin6_addr
)) sa6
.sin6_scope_id
= cbh
->cb_interface
;
1425 // Validation results are always delivered separately from the actual results of the
1426 // DNSServiceGetAddrInfo. Set the "addr" to NULL as per the documentation.
1428 // Note: If we deliver validation results along with the "addr" in the future, we need
1429 // a way to differentiate the negative response from validation-only response as both
1430 // has zero address.
1431 if (!(cbh
->cb_flags
& kDNSServiceFlagsValidate
))
1432 ((DNSServiceGetAddrInfoReply
)sdr
->AppCallback
)(sdr
, cbh
->cb_flags
, cbh
->cb_interface
, cbh
->cb_err
, hostname
, sa
, ttl
, sdr
->AppContext
);
1434 ((DNSServiceGetAddrInfoReply
)sdr
->AppCallback
)(sdr
, cbh
->cb_flags
, cbh
->cb_interface
, cbh
->cb_err
, hostname
, NULL
, 0, sdr
->AppContext
);
1435 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1439 DNSServiceErrorType DNSSD_API DNSServiceGetAddrInfo
1441 DNSServiceRef
*sdRef
,
1442 DNSServiceFlags flags
,
1443 uint32_t interfaceIndex
,
1445 const char *hostname
,
1446 DNSServiceGetAddrInfoReply callBack
,
1447 void *context
/* may be NULL */
1453 DNSServiceErrorType err
;
1455 if (!hostname
) return kDNSServiceErr_BadParam
;
1457 err
= ConnectToServer(sdRef
, flags
, addrinfo_request
, handle_addrinfo_response
, callBack
, context
);
1460 return err
; // On error ConnectToServer leaves *sdRef set to NULL
1463 // Calculate total message length
1464 len
= sizeof(flags
);
1465 len
+= sizeof(uint32_t); // interfaceIndex
1466 len
+= sizeof(uint32_t); // protocol
1467 len
+= strlen(hostname
) + 1;
1469 hdr
= create_hdr(addrinfo_request
, &len
, &ptr
, (*sdRef
)->primary
? 1 : 0, *sdRef
);
1470 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
1472 put_flags(flags
, &ptr
);
1473 put_uint32(interfaceIndex
, &ptr
);
1474 put_uint32(protocol
, &ptr
);
1475 put_string(hostname
, &ptr
);
1477 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1478 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
1482 static void handle_browse_response(DNSServiceOp
*const sdr
, const CallbackHeader
*const cbh
, const char *data
, const char *const end
)
1484 char replyName
[256], replyType
[kDNSServiceMaxDomainName
], replyDomain
[kDNSServiceMaxDomainName
];
1485 get_string(&data
, end
, replyName
, 256);
1486 get_string(&data
, end
, replyType
, kDNSServiceMaxDomainName
);
1487 get_string(&data
, end
, replyDomain
, kDNSServiceMaxDomainName
);
1488 if (!data
) syslog(LOG_WARNING
, "dnssd_clientstub handle_browse_response: error reading result from daemon");
1489 else ((DNSServiceBrowseReply
)sdr
->AppCallback
)(sdr
, cbh
->cb_flags
, cbh
->cb_interface
, cbh
->cb_err
, replyName
, replyType
, replyDomain
, sdr
->AppContext
);
1490 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1493 DNSServiceErrorType DNSSD_API DNSServiceBrowse
1495 DNSServiceRef
*sdRef
,
1496 DNSServiceFlags flags
,
1497 uint32_t interfaceIndex
,
1498 const char *regtype
,
1500 DNSServiceBrowseReply callBack
,
1507 DNSServiceErrorType err
;
1509 if ((interfaceIndex
== kDNSServiceInterfaceIndexAny
) && includeP2PWithIndexAny())
1510 flags
|= kDNSServiceFlagsIncludeP2P
;
1512 err
= ConnectToServer(sdRef
, flags
, browse_request
, handle_browse_response
, callBack
, context
);
1513 if (err
) return err
; // On error ConnectToServer leaves *sdRef set to NULL
1515 if (!domain
) domain
= "";
1516 len
= sizeof(flags
);
1517 len
+= sizeof(interfaceIndex
);
1518 len
+= strlen(regtype
) + 1;
1519 len
+= strlen(domain
) + 1;
1521 hdr
= create_hdr(browse_request
, &len
, &ptr
, (*sdRef
)->primary
? 1 : 0, *sdRef
);
1522 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
1524 put_flags(flags
, &ptr
);
1525 put_uint32(interfaceIndex
, &ptr
);
1526 put_string(regtype
, &ptr
);
1527 put_string(domain
, &ptr
);
1529 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1530 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
1534 DNSServiceErrorType DNSSD_API
DNSServiceSetDefaultDomainForUser(DNSServiceFlags flags
, const char *domain
);
1535 DNSServiceErrorType DNSSD_API
DNSServiceSetDefaultDomainForUser(DNSServiceFlags flags
, const char *domain
)
1539 size_t len
= sizeof(flags
) + strlen(domain
) + 1;
1541 DNSServiceErrorType err
= ConnectToServer(&tmp
, 0, setdomain_request
, NULL
, NULL
, NULL
);
1542 if (err
) return err
;
1544 hdr
= create_hdr(setdomain_request
, &len
, &ptr
, 0, tmp
);
1545 if (!hdr
) { DNSServiceRefDeallocate(tmp
); return kDNSServiceErr_NoMemory
; }
1547 put_flags(flags
, &ptr
);
1548 put_string(domain
, &ptr
);
1549 err
= deliver_request(hdr
, tmp
); // Will free hdr for us
1550 DNSServiceRefDeallocate(tmp
);
1554 static void handle_regservice_response(DNSServiceOp
*const sdr
, const CallbackHeader
*const cbh
, const char *data
, const char *const end
)
1556 char name
[256], regtype
[kDNSServiceMaxDomainName
], domain
[kDNSServiceMaxDomainName
];
1557 get_string(&data
, end
, name
, 256);
1558 get_string(&data
, end
, regtype
, kDNSServiceMaxDomainName
);
1559 get_string(&data
, end
, domain
, kDNSServiceMaxDomainName
);
1560 if (!data
) syslog(LOG_WARNING
, "dnssd_clientstub handle_regservice_response: error reading result from daemon");
1561 else ((DNSServiceRegisterReply
)sdr
->AppCallback
)(sdr
, cbh
->cb_flags
, cbh
->cb_err
, name
, regtype
, domain
, sdr
->AppContext
);
1562 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1565 DNSServiceErrorType DNSSD_API DNSServiceRegister
1567 DNSServiceRef
*sdRef
,
1568 DNSServiceFlags flags
,
1569 uint32_t interfaceIndex
,
1571 const char *regtype
,
1574 uint16_t PortInNetworkByteOrder
,
1576 const void *txtRecord
,
1577 DNSServiceRegisterReply callBack
,
1584 DNSServiceErrorType err
;
1585 union { uint16_t s
; u_char b
[2]; } port
= { PortInNetworkByteOrder
};
1587 if (!name
) name
= "";
1588 if (!regtype
) return kDNSServiceErr_BadParam
;
1589 if (!domain
) domain
= "";
1590 if (!host
) host
= "";
1591 if (!txtRecord
) txtRecord
= (void*)"";
1593 // No callback must have auto-rename
1594 if (!callBack
&& (flags
& kDNSServiceFlagsNoAutoRename
)) return kDNSServiceErr_BadParam
;
1596 if ((interfaceIndex
== kDNSServiceInterfaceIndexAny
) && includeP2PWithIndexAny())
1597 flags
|= kDNSServiceFlagsIncludeP2P
;
1599 err
= ConnectToServer(sdRef
, flags
, reg_service_request
, callBack
? handle_regservice_response
: NULL
, callBack
, context
);
1600 if (err
) return err
; // On error ConnectToServer leaves *sdRef set to NULL
1602 len
= sizeof(DNSServiceFlags
);
1603 len
+= sizeof(uint32_t); // interfaceIndex
1604 len
+= strlen(name
) + strlen(regtype
) + strlen(domain
) + strlen(host
) + 4;
1605 len
+= 2 * sizeof(uint16_t); // port, txtLen
1608 hdr
= create_hdr(reg_service_request
, &len
, &ptr
, (*sdRef
)->primary
? 1 : 0, *sdRef
);
1609 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
1611 // If it is going over a shared connection, then don't set the IPC_FLAGS_NOREPLY
1612 // as it affects all the operations over the shared connection. This is not
1613 // a normal case and hence receiving the response back from the daemon and
1614 // discarding it in ConnectionResponse is okay.
1616 if (!(flags
& kDNSServiceFlagsShareConnection
) && !callBack
) hdr
->ipc_flags
|= IPC_FLAGS_NOREPLY
;
1618 put_flags(flags
, &ptr
);
1619 put_uint32(interfaceIndex
, &ptr
);
1620 put_string(name
, &ptr
);
1621 put_string(regtype
, &ptr
);
1622 put_string(domain
, &ptr
);
1623 put_string(host
, &ptr
);
1626 put_uint16(txtLen
, &ptr
);
1627 put_rdata(txtLen
, txtRecord
, &ptr
);
1629 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1630 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
1634 static void handle_enumeration_response(DNSServiceOp
*const sdr
, const CallbackHeader
*const cbh
, const char *data
, const char *const end
)
1636 char domain
[kDNSServiceMaxDomainName
];
1637 get_string(&data
, end
, domain
, kDNSServiceMaxDomainName
);
1638 if (!data
) syslog(LOG_WARNING
, "dnssd_clientstub handle_enumeration_response: error reading result from daemon");
1639 else ((DNSServiceDomainEnumReply
)sdr
->AppCallback
)(sdr
, cbh
->cb_flags
, cbh
->cb_interface
, cbh
->cb_err
, domain
, sdr
->AppContext
);
1640 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1643 DNSServiceErrorType DNSSD_API DNSServiceEnumerateDomains
1645 DNSServiceRef
*sdRef
,
1646 DNSServiceFlags flags
,
1647 uint32_t interfaceIndex
,
1648 DNSServiceDomainEnumReply callBack
,
1655 DNSServiceErrorType err
;
1657 int f1
= (flags
& kDNSServiceFlagsBrowseDomains
) != 0;
1658 int f2
= (flags
& kDNSServiceFlagsRegistrationDomains
) != 0;
1659 if (f1
+ f2
!= 1) return kDNSServiceErr_BadParam
;
1661 err
= ConnectToServer(sdRef
, flags
, enumeration_request
, handle_enumeration_response
, callBack
, context
);
1662 if (err
) return err
; // On error ConnectToServer leaves *sdRef set to NULL
1664 len
= sizeof(DNSServiceFlags
);
1665 len
+= sizeof(uint32_t);
1667 hdr
= create_hdr(enumeration_request
, &len
, &ptr
, (*sdRef
)->primary
? 1 : 0, *sdRef
);
1668 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
1670 put_flags(flags
, &ptr
);
1671 put_uint32(interfaceIndex
, &ptr
);
1673 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1674 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
1678 static void ConnectionResponse(DNSServiceOp
*const sdr
, const CallbackHeader
*const cbh
, const char *const data
, const char *const end
)
1680 (void)data
; // Unused
1682 //printf("ConnectionResponse got %d\n", cbh->ipc_hdr.op);
1683 if (cbh
->ipc_hdr
.op
!= reg_record_reply_op
)
1685 // When using kDNSServiceFlagsShareConnection, need to search the list of associated DNSServiceOps
1686 // to find the one this response is intended for, and then call through to its ProcessReply handler.
1687 // We start with our first subordinate DNSServiceRef -- don't want to accidentally match the parent DNSServiceRef.
1688 DNSServiceOp
*op
= sdr
->next
;
1689 while (op
&& (op
->uid
.u32
[0] != cbh
->ipc_hdr
.client_context
.u32
[0] || op
->uid
.u32
[1] != cbh
->ipc_hdr
.client_context
.u32
[1]))
1691 // Note: We may sometimes not find a matching DNSServiceOp, in the case where the client has
1692 // cancelled the subordinate DNSServiceOp, but there are still messages in the pipeline from the daemon
1693 if (op
&& op
->ProcessReply
) op
->ProcessReply(op
, cbh
, data
, end
);
1694 // WARNING: Don't touch op or sdr after this -- client may have called DNSServiceRefDeallocate
1700 for (rec
= sdr
->rec
; rec
; rec
= rec
->recnext
)
1702 if (rec
->uid
.u32
[0] == cbh
->ipc_hdr
.client_context
.u32
[0] && rec
->uid
.u32
[1] == cbh
->ipc_hdr
.client_context
.u32
[1])
1705 // The record might have been freed already and hence not an
1706 // error if the record is not found.
1709 syslog(LOG_INFO
, "ConnectionResponse: Record not found");
1712 if (rec
->sdr
!= sdr
)
1714 syslog(LOG_WARNING
, "ConnectionResponse: Record sdr mismatch: rec %p sdr %p", rec
->sdr
, sdr
);
1718 if (sdr
->op
== connection_request
|| sdr
->op
== connection_delegate_request
)
1720 rec
->AppCallback(rec
->sdr
, rec
, cbh
->cb_flags
, cbh
->cb_err
, rec
->AppContext
);
1724 syslog(LOG_WARNING
, "dnssd_clientstub ConnectionResponse: sdr->op != connection_request");
1725 rec
->AppCallback(rec
->sdr
, rec
, 0, kDNSServiceErr_Unknown
, rec
->AppContext
);
1727 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1731 DNSServiceErrorType DNSSD_API
DNSServiceCreateConnection(DNSServiceRef
*sdRef
)
1736 DNSServiceErrorType err
= ConnectToServer(sdRef
, 0, connection_request
, ConnectionResponse
, NULL
, NULL
);
1737 if (err
) return err
; // On error ConnectToServer leaves *sdRef set to NULL
1739 hdr
= create_hdr(connection_request
, &len
, &ptr
, 0, *sdRef
);
1740 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
1742 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1743 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
1747 #if APPLE_OSX_mDNSResponder && !TARGET_IPHONE_SIMULATOR
1748 DNSServiceErrorType DNSSD_API
DNSServiceCreateDelegateConnection(DNSServiceRef
*sdRef
, int32_t pid
, uuid_t uuid
)
1754 DNSServiceErrorType err
= ConnectToServer(sdRef
, 0, connection_delegate_request
, ConnectionResponse
, NULL
, NULL
);
1757 return err
; // On error ConnectToServer leaves *sdRef set to NULL
1760 // Only one of the two options can be set. If pid is zero, uuid is used.
1761 // If both are specified only pid will be used. We send across the pid
1762 // so that the daemon knows what to read from the socket.
1764 len
+= sizeof(int32_t);
1766 hdr
= create_hdr(connection_delegate_request
, &len
, &ptr
, 0, *sdRef
);
1769 DNSServiceRefDeallocate(*sdRef
);
1771 return kDNSServiceErr_NoMemory
;
1774 if (pid
&& setsockopt((*sdRef
)->sockfd
, SOL_SOCKET
, SO_DELEGATED
, &pid
, sizeof(pid
)) == -1)
1776 // Free the hdr in case we return before calling deliver_request()
1779 DNSServiceRefDeallocate(*sdRef
);
1781 return kDNSServiceErr_NoAuth
;
1784 if (!pid
&& setsockopt((*sdRef
)->sockfd
, SOL_SOCKET
, SO_DELEGATED_UUID
, uuid
, sizeof(uuid_t
)) == -1)
1786 // Free the hdr in case we return before calling deliver_request()
1789 DNSServiceRefDeallocate(*sdRef
);
1791 return kDNSServiceErr_NoAuth
;
1794 put_uint32(pid
, &ptr
);
1796 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1799 DNSServiceRefDeallocate(*sdRef
);
1804 #elif TARGET_IPHONE_SIMULATOR // This hack is for Simulator platform only
1805 DNSServiceErrorType DNSSD_API
DNSServiceCreateDelegateConnection(DNSServiceRef
*sdRef
, int32_t pid
, uuid_t uuid
)
1809 return DNSServiceCreateConnection(sdRef
);
1813 DNSServiceErrorType DNSSD_API DNSServiceRegisterRecord
1815 DNSServiceRef sdRef
,
1816 DNSRecordRef
*RecordRef
,
1817 DNSServiceFlags flags
,
1818 uint32_t interfaceIndex
,
1819 const char *fullname
,
1825 DNSServiceRegisterRecordReply callBack
,
1831 ipc_msg_hdr
*hdr
= NULL
;
1832 DNSRecordRef rref
= NULL
;
1834 int f1
= (flags
& kDNSServiceFlagsShared
) != 0;
1835 int f2
= (flags
& kDNSServiceFlagsUnique
) != 0;
1836 if (f1
+ f2
!= 1) return kDNSServiceErr_BadParam
;
1838 if ((interfaceIndex
== kDNSServiceInterfaceIndexAny
) && includeP2PWithIndexAny())
1839 flags
|= kDNSServiceFlagsIncludeP2P
;
1841 if (!sdRef
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRegisterRecord called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam
; }
1843 if (!DNSServiceRefValid(sdRef
))
1845 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRegisterRecord called with invalid DNSServiceRef %p %08X %08X", sdRef
, sdRef
->sockfd
, sdRef
->validator
);
1846 return kDNSServiceErr_BadReference
;
1849 if (sdRef
->op
!= connection_request
&& sdRef
->op
!= connection_delegate_request
)
1851 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRegisterRecord called with non-DNSServiceCreateConnection DNSServiceRef %p %d", sdRef
, sdRef
->op
);
1852 return kDNSServiceErr_BadReference
;
1857 len
= sizeof(DNSServiceFlags
);
1858 len
+= 2 * sizeof(uint32_t); // interfaceIndex, ttl
1859 len
+= 3 * sizeof(uint16_t); // rrtype, rrclass, rdlen
1860 len
+= strlen(fullname
) + 1;
1863 // Bump up the uid. Normally for shared operations (kDNSServiceFlagsShareConnection), this
1864 // is done in ConnectToServer. For DNSServiceRegisterRecord, ConnectToServer has already
1865 // been called. As multiple DNSServiceRegisterRecords can be multiplexed over a single
1866 // connection, we need a way to demultiplex the response so that the callback corresponding
1867 // to the right DNSServiceRegisterRecord instance can be called. Use the same mechanism that
1868 // is used by kDNSServiceFlagsShareConnection. create_hdr copies the uid value to ipc
1869 // hdr->client_context which will be returned in the ipc response.
1870 if (++sdRef
->uid
.u32
[0] == 0)
1871 ++sdRef
->uid
.u32
[1];
1872 hdr
= create_hdr(reg_record_request
, &len
, &ptr
, 1, sdRef
);
1873 if (!hdr
) return kDNSServiceErr_NoMemory
;
1875 put_flags(flags
, &ptr
);
1876 put_uint32(interfaceIndex
, &ptr
);
1877 put_string(fullname
, &ptr
);
1878 put_uint16(rrtype
, &ptr
);
1879 put_uint16(rrclass
, &ptr
);
1880 put_uint16(rdlen
, &ptr
);
1881 put_rdata(rdlen
, rdata
, &ptr
);
1882 put_uint32(ttl
, &ptr
);
1884 rref
= malloc(sizeof(DNSRecord
));
1885 if (!rref
) { free(hdr
); return kDNSServiceErr_NoMemory
; }
1886 rref
->AppContext
= context
;
1887 rref
->AppCallback
= callBack
;
1888 rref
->record_index
= sdRef
->max_index
++;
1890 rref
->recnext
= NULL
;
1892 // Remember the uid that we are sending across so that we can match
1893 // when the response comes back.
1894 rref
->uid
= sdRef
->uid
;
1895 hdr
->reg_index
= rref
->record_index
;
1898 while (*p
) p
= &(*p
)->recnext
;
1901 return deliver_request(hdr
, sdRef
); // Will free hdr for us
1904 // sdRef returned by DNSServiceRegister()
1905 DNSServiceErrorType DNSSD_API DNSServiceAddRecord
1907 DNSServiceRef sdRef
,
1908 DNSRecordRef
*RecordRef
,
1909 DNSServiceFlags flags
,
1922 if (!sdRef
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceAddRecord called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam
; }
1923 if (!RecordRef
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceAddRecord called with NULL DNSRecordRef pointer"); return kDNSServiceErr_BadParam
; }
1924 if (sdRef
->op
!= reg_service_request
)
1926 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceAddRecord called with non-DNSServiceRegister DNSServiceRef %p %d", sdRef
, sdRef
->op
);
1927 return kDNSServiceErr_BadReference
;
1930 if (!DNSServiceRefValid(sdRef
))
1932 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceAddRecord called with invalid DNSServiceRef %p %08X %08X", sdRef
, sdRef
->sockfd
, sdRef
->validator
);
1933 return kDNSServiceErr_BadReference
;
1938 len
+= 2 * sizeof(uint16_t); // rrtype, rdlen
1940 len
+= sizeof(uint32_t);
1941 len
+= sizeof(DNSServiceFlags
);
1943 hdr
= create_hdr(add_record_request
, &len
, &ptr
, 1, sdRef
);
1944 if (!hdr
) return kDNSServiceErr_NoMemory
;
1945 put_flags(flags
, &ptr
);
1946 put_uint16(rrtype
, &ptr
);
1947 put_uint16(rdlen
, &ptr
);
1948 put_rdata(rdlen
, rdata
, &ptr
);
1949 put_uint32(ttl
, &ptr
);
1951 rref
= malloc(sizeof(DNSRecord
));
1952 if (!rref
) { free(hdr
); return kDNSServiceErr_NoMemory
; }
1953 rref
->AppContext
= NULL
;
1954 rref
->AppCallback
= NULL
;
1955 rref
->record_index
= sdRef
->max_index
++;
1957 rref
->recnext
= NULL
;
1959 hdr
->reg_index
= rref
->record_index
;
1962 while (*p
) p
= &(*p
)->recnext
;
1965 return deliver_request(hdr
, sdRef
); // Will free hdr for us
1968 // DNSRecordRef returned by DNSServiceRegisterRecord or DNSServiceAddRecord
1969 DNSServiceErrorType DNSSD_API DNSServiceUpdateRecord
1971 DNSServiceRef sdRef
,
1972 DNSRecordRef RecordRef
,
1973 DNSServiceFlags flags
,
1983 if (!sdRef
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceUpdateRecord called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam
; }
1985 if (!DNSServiceRefValid(sdRef
))
1987 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceUpdateRecord called with invalid DNSServiceRef %p %08X %08X", sdRef
, sdRef
->sockfd
, sdRef
->validator
);
1988 return kDNSServiceErr_BadReference
;
1991 // Note: RecordRef is allowed to be NULL
1993 len
+= sizeof(uint16_t);
1995 len
+= sizeof(uint32_t);
1996 len
+= sizeof(DNSServiceFlags
);
1998 hdr
= create_hdr(update_record_request
, &len
, &ptr
, 1, sdRef
);
1999 if (!hdr
) return kDNSServiceErr_NoMemory
;
2000 hdr
->reg_index
= RecordRef
? RecordRef
->record_index
: TXT_RECORD_INDEX
;
2001 put_flags(flags
, &ptr
);
2002 put_uint16(rdlen
, &ptr
);
2003 put_rdata(rdlen
, rdata
, &ptr
);
2004 put_uint32(ttl
, &ptr
);
2005 return deliver_request(hdr
, sdRef
); // Will free hdr for us
2008 DNSServiceErrorType DNSSD_API DNSServiceRemoveRecord
2010 DNSServiceRef sdRef
,
2011 DNSRecordRef RecordRef
,
2012 DNSServiceFlags flags
2018 DNSServiceErrorType err
;
2020 if (!sdRef
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRemoveRecord called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam
; }
2021 if (!RecordRef
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRemoveRecord called with NULL DNSRecordRef"); return kDNSServiceErr_BadParam
; }
2022 if (!sdRef
->max_index
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRemoveRecord called with bad DNSServiceRef"); return kDNSServiceErr_BadReference
; }
2024 if (!DNSServiceRefValid(sdRef
))
2026 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRemoveRecord called with invalid DNSServiceRef %p %08X %08X", sdRef
, sdRef
->sockfd
, sdRef
->validator
);
2027 return kDNSServiceErr_BadReference
;
2030 len
+= sizeof(flags
);
2031 hdr
= create_hdr(remove_record_request
, &len
, &ptr
, 1, sdRef
);
2032 if (!hdr
) return kDNSServiceErr_NoMemory
;
2033 hdr
->reg_index
= RecordRef
->record_index
;
2034 put_flags(flags
, &ptr
);
2035 err
= deliver_request(hdr
, sdRef
); // Will free hdr for us
2038 // This RecordRef could have been allocated in DNSServiceRegisterRecord or DNSServiceAddRecord.
2039 // If so, delink from the list before freeing
2040 DNSRecord
**p
= &sdRef
->rec
;
2041 while (*p
&& *p
!= RecordRef
) p
= &(*p
)->recnext
;
2042 if (*p
) *p
= RecordRef
->recnext
;
2048 DNSServiceErrorType DNSSD_API DNSServiceReconfirmRecord
2050 DNSServiceFlags flags
,
2051 uint32_t interfaceIndex
,
2052 const char *fullname
,
2064 DNSServiceErrorType err
= ConnectToServer(&tmp
, flags
, reconfirm_record_request
, NULL
, NULL
, NULL
);
2065 if (err
) return err
;
2067 len
= sizeof(DNSServiceFlags
);
2068 len
+= sizeof(uint32_t);
2069 len
+= strlen(fullname
) + 1;
2070 len
+= 3 * sizeof(uint16_t);
2072 hdr
= create_hdr(reconfirm_record_request
, &len
, &ptr
, 0, tmp
);
2073 if (!hdr
) { DNSServiceRefDeallocate(tmp
); return kDNSServiceErr_NoMemory
; }
2075 put_flags(flags
, &ptr
);
2076 put_uint32(interfaceIndex
, &ptr
);
2077 put_string(fullname
, &ptr
);
2078 put_uint16(rrtype
, &ptr
);
2079 put_uint16(rrclass
, &ptr
);
2080 put_uint16(rdlen
, &ptr
);
2081 put_rdata(rdlen
, rdata
, &ptr
);
2083 err
= deliver_request(hdr
, tmp
); // Will free hdr for us
2084 DNSServiceRefDeallocate(tmp
);
2089 static void handle_port_mapping_response(DNSServiceOp
*const sdr
, const CallbackHeader
*const cbh
, const char *data
, const char *const end
)
2091 union { uint32_t l
; u_char b
[4]; } addr
;
2093 union { uint16_t s
; u_char b
[2]; } internalPort
;
2094 union { uint16_t s
; u_char b
[2]; } externalPort
;
2097 if (!data
|| data
+ 13 > end
) goto fail
;
2099 addr
.b
[0] = *data
++;
2100 addr
.b
[1] = *data
++;
2101 addr
.b
[2] = *data
++;
2102 addr
.b
[3] = *data
++;
2104 internalPort
.b
[0] = *data
++;
2105 internalPort
.b
[1] = *data
++;
2106 externalPort
.b
[0] = *data
++;
2107 externalPort
.b
[1] = *data
++;
2108 ttl
= get_uint32(&data
, end
);
2109 if (!data
) goto fail
;
2111 ((DNSServiceNATPortMappingReply
)sdr
->AppCallback
)(sdr
, cbh
->cb_flags
, cbh
->cb_interface
, cbh
->cb_err
, addr
.l
, protocol
, internalPort
.s
, externalPort
.s
, ttl
, sdr
->AppContext
);
2113 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
2116 syslog(LOG_WARNING
, "dnssd_clientstub handle_port_mapping_response: error reading result from daemon");
2119 DNSServiceErrorType DNSSD_API DNSServiceNATPortMappingCreate
2121 DNSServiceRef
*sdRef
,
2122 DNSServiceFlags flags
,
2123 uint32_t interfaceIndex
,
2124 uint32_t protocol
, /* TCP and/or UDP */
2125 uint16_t internalPortInNetworkByteOrder
,
2126 uint16_t externalPortInNetworkByteOrder
,
2127 uint32_t ttl
, /* time to live in seconds */
2128 DNSServiceNATPortMappingReply callBack
,
2129 void *context
/* may be NULL */
2135 union { uint16_t s
; u_char b
[2]; } internalPort
= { internalPortInNetworkByteOrder
};
2136 union { uint16_t s
; u_char b
[2]; } externalPort
= { externalPortInNetworkByteOrder
};
2138 DNSServiceErrorType err
= ConnectToServer(sdRef
, flags
, port_mapping_request
, handle_port_mapping_response
, callBack
, context
);
2139 if (err
) return err
; // On error ConnectToServer leaves *sdRef set to NULL
2141 len
= sizeof(flags
);
2142 len
+= sizeof(interfaceIndex
);
2143 len
+= sizeof(protocol
);
2144 len
+= sizeof(internalPort
);
2145 len
+= sizeof(externalPort
);
2148 hdr
= create_hdr(port_mapping_request
, &len
, &ptr
, (*sdRef
)->primary
? 1 : 0, *sdRef
);
2149 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
2151 put_flags(flags
, &ptr
);
2152 put_uint32(interfaceIndex
, &ptr
);
2153 put_uint32(protocol
, &ptr
);
2154 *ptr
++ = internalPort
.b
[0];
2155 *ptr
++ = internalPort
.b
[1];
2156 *ptr
++ = externalPort
.b
[0];
2157 *ptr
++ = externalPort
.b
[1];
2158 put_uint32(ttl
, &ptr
);
2160 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
2161 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
2165 #if _DNS_SD_LIBDISPATCH
2166 DNSServiceErrorType DNSSD_API DNSServiceSetDispatchQueue
2168 DNSServiceRef service
,
2169 dispatch_queue_t queue
2172 int dnssd_fd
= DNSServiceRefSockFD(service
);
2173 if (dnssd_fd
== dnssd_InvalidSocket
) return kDNSServiceErr_BadParam
;
2176 syslog(LOG_WARNING
, "dnssd_clientstub: DNSServiceSetDispatchQueue dispatch queue NULL");
2177 return kDNSServiceErr_BadParam
;
2179 if (service
->disp_queue
)
2181 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceSetDispatchQueue dispatch queue set already");
2182 return kDNSServiceErr_BadParam
;
2184 if (service
->disp_source
)
2186 syslog(LOG_WARNING
, "DNSServiceSetDispatchQueue dispatch source set already");
2187 return kDNSServiceErr_BadParam
;
2189 service
->disp_source
= dispatch_source_create(DISPATCH_SOURCE_TYPE_READ
, dnssd_fd
, 0, queue
);
2190 if (!service
->disp_source
)
2192 syslog(LOG_WARNING
, "DNSServiceSetDispatchQueue dispatch_source_create failed");
2193 return kDNSServiceErr_NoMemory
;
2195 service
->disp_queue
= queue
;
2196 dispatch_source_set_event_handler(service
->disp_source
, ^{DNSServiceProcessResult(service
);});
2197 dispatch_source_set_cancel_handler(service
->disp_source
, ^{dnssd_close(dnssd_fd
);});
2198 dispatch_resume(service
->disp_source
);
2199 return kDNSServiceErr_NoError
;
2201 #endif // _DNS_SD_LIBDISPATCH
2203 #if !defined(_WIN32)
2205 static void DNSSD_API
SleepKeepaliveCallback(DNSServiceRef sdRef
, DNSRecordRef rec
, const DNSServiceFlags flags
,
2206 DNSServiceErrorType errorCode
, void *context
)
2208 SleepKAContext
*ka
= (SleepKAContext
*)context
;
2209 (void)rec
; // Unused
2210 (void)flags
; // Unused
2212 if (sdRef
->kacontext
!= context
)
2213 syslog(LOG_WARNING
, "SleepKeepaliveCallback context mismatch");
2215 if (ka
->AppCallback
)
2216 ((DNSServiceSleepKeepaliveReply
)ka
->AppCallback
)(sdRef
, errorCode
, ka
->AppContext
);
2219 DNSServiceErrorType DNSSD_API DNSServiceSleepKeepalive
2221 DNSServiceRef
*sdRef
,
2222 DNSServiceFlags flags
,
2224 unsigned int timeout
,
2225 DNSServiceSleepKeepaliveReply callBack
,
2229 char source_str
[INET6_ADDRSTRLEN
];
2230 char target_str
[INET6_ADDRSTRLEN
];
2231 struct sockaddr_storage lss
;
2232 struct sockaddr_storage rss
;
2233 socklen_t len1
, len2
;
2234 unsigned int len
, proxyreclen
;
2236 DNSServiceErrorType err
;
2237 DNSRecordRef record
= NULL
;
2241 unsigned int i
, unique
;
2244 (void) flags
; //unused
2245 if (!timeout
) return kDNSServiceErr_BadParam
;
2249 if (getsockname(fd
, (struct sockaddr
*)&lss
, &len1
) < 0)
2251 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive: getsockname %d\n", errno
);
2252 return kDNSServiceErr_BadParam
;
2256 if (getpeername(fd
, (struct sockaddr
*)&rss
, &len2
) < 0)
2258 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive: getpeername %d\n", errno
);
2259 return kDNSServiceErr_BadParam
;
2264 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive local/remote info not same");
2265 return kDNSServiceErr_Unknown
;
2269 if (lss
.ss_family
== AF_INET
)
2271 struct sockaddr_in
*sl
= (struct sockaddr_in
*)&lss
;
2272 struct sockaddr_in
*sr
= (struct sockaddr_in
*)&rss
;
2273 unsigned char *ptr
= (unsigned char *)&sl
->sin_addr
;
2275 if (!inet_ntop(AF_INET
, (const void *)&sr
->sin_addr
, target_str
, sizeof (target_str
)))
2277 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive remote info failed %d", errno
);
2278 return kDNSServiceErr_Unknown
;
2280 if (!inet_ntop(AF_INET
, (const void *)&sl
->sin_addr
, source_str
, sizeof (source_str
)))
2282 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive local info failed %d", errno
);
2283 return kDNSServiceErr_Unknown
;
2285 // Sum of all bytes in the local address and port should result in a unique
2286 // number in the local network
2287 for (i
= 0; i
< sizeof(struct in_addr
); i
++)
2289 unique
+= sl
->sin_port
;
2290 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
));
2294 struct sockaddr_in6
*sl6
= (struct sockaddr_in6
*)&lss
;
2295 struct sockaddr_in6
*sr6
= (struct sockaddr_in6
*)&rss
;
2296 unsigned char *ptr
= (unsigned char *)&sl6
->sin6_addr
;
2298 if (!inet_ntop(AF_INET6
, (const void *)&sr6
->sin6_addr
, target_str
, sizeof (target_str
)))
2300 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive remote6 info failed %d", errno
);
2301 return kDNSServiceErr_Unknown
;
2303 if (!inet_ntop(AF_INET6
, (const void *)&sl6
->sin6_addr
, source_str
, sizeof (source_str
)))
2305 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive local6 info failed %d", errno
);
2306 return kDNSServiceErr_Unknown
;
2308 for (i
= 0; i
< sizeof(struct in6_addr
); i
++)
2310 unique
+= sl6
->sin6_port
;
2311 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
));
2314 if (len
>= (sizeof(buf
) - 1))
2316 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive could not fit local/remote info");
2317 return kDNSServiceErr_Unknown
;
2319 // Include the NULL byte also in the first byte. The total length of the record includes the
2322 proxyreclen
= len
+ 2;
2324 len
= snprintf(name
, sizeof(name
), "%u", unique
);
2325 if (len
>= sizeof(name
))
2327 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive could not fit unique");
2328 return kDNSServiceErr_Unknown
;
2331 len
= snprintf(recname
, sizeof(recname
), "%s.%s", name
, "_keepalive._dns-sd._udp.local");
2332 if (len
>= sizeof(recname
))
2334 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive could not fit name");
2335 return kDNSServiceErr_Unknown
;
2338 ka
= malloc(sizeof(SleepKAContext
));
2339 if (!ka
) return kDNSServiceErr_NoMemory
;
2340 ka
->AppCallback
= callBack
;
2341 ka
->AppContext
= context
;
2343 err
= DNSServiceCreateConnection(sdRef
);
2346 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive cannot create connection");
2351 // we don't care about the "record". When sdRef gets deallocated later, it will be freed too
2352 err
= DNSServiceRegisterRecord(*sdRef
, &record
, kDNSServiceFlagsUnique
, 0, recname
,
2353 kDNSServiceType_NULL
, kDNSServiceClass_IN
, proxyreclen
, buf
, kDNSServiceInterfaceIndexAny
, SleepKeepaliveCallback
, ka
);
2356 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive cannot create connection");
2360 (*sdRef
)->kacontext
= ka
;
2361 return kDNSServiceErr_NoError
;