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_private.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 // Should never happen. If it does, it indicates some OS bug,
199 // or that the mDNSResponder daemon crashed (which should never happen).
200 #if !defined(__ppc__) && defined(SO_ISDEFUNCT)
202 socklen_t dlen
= sizeof (defunct
);
203 if (getsockopt(sd
, SOL_SOCKET
, SO_ISDEFUNCT
, &defunct
, &dlen
) < 0)
204 syslog(LOG_WARNING
, "dnssd_clientstub write_all: SO_ISDEFUNCT failed %d %s", dnssd_errno
, dnssd_strerror(dnssd_errno
));
206 syslog(LOG_WARNING
, "dnssd_clientstub write_all(%d) failed %ld/%ld %d %s", sd
,
207 (long)num_written
, (long)len
,
208 (num_written
< 0) ? dnssd_errno
: 0,
209 (num_written
< 0) ? dnssd_strerror(dnssd_errno
) : "");
211 syslog(LOG_INFO
, "dnssd_clientstub write_all(%d) DEFUNCT", sd
);
213 syslog(LOG_WARNING
, "dnssd_clientstub write_all(%d) failed %ld/%ld %d %s", sd
,
214 (long)num_written
, (long)len
,
215 (num_written
< 0) ? dnssd_errno
: 0,
216 (num_written
< 0) ? dnssd_strerror(dnssd_errno
) : "");
226 enum { read_all_success
= 0, read_all_fail
= -1, read_all_wouldblock
= -2 };
228 // Read len bytes. Return 0 on success, read_all_fail on error, or read_all_wouldblock for
229 static int read_all(dnssd_sock_t sd
, char *buf
, int len
)
231 // Don't use "MSG_WAITALL"; it returns "Invalid argument" on some Linux versions; use an explicit while() loop instead.
232 //if (recv(sd, buf, len, MSG_WAITALL) != len) return -1;
236 ssize_t num_read
= recv(sd
, buf
, len
, 0);
237 // It is valid to get an interrupted system call error e.g., somebody attaching
238 // in a debugger, retry without failing
239 if ((num_read
< 0) && (errno
== EINTR
))
241 syslog(LOG_INFO
, "dnssd_clientstub read_all: EINTR continue");
244 if ((num_read
== 0) || (num_read
< 0) || (num_read
> len
))
248 // Should never happen. If it does, it indicates some OS bug,
249 // or that the mDNSResponder daemon crashed (which should never happen).
251 // <rdar://problem/7481776> Suppress logs for "A non-blocking socket operation
252 // could not be completed immediately"
253 if (WSAGetLastError() != WSAEWOULDBLOCK
)
256 #if !defined(__ppc__) && defined(SO_ISDEFUNCT)
258 socklen_t dlen
= sizeof (defunct
);
259 if (getsockopt(sd
, SOL_SOCKET
, SO_ISDEFUNCT
, &defunct
, &dlen
) < 0)
260 syslog(LOG_WARNING
, "dnssd_clientstub read_all: SO_ISDEFUNCT failed %d %s", dnssd_errno
, dnssd_strerror(dnssd_errno
));
266 syslog(LOG_WARNING
, "dnssd_clientstub read_all(%d) failed %ld/%ld %d %s", sd
,
267 (long)num_read
, (long)len
,
268 (num_read
< 0) ? dnssd_errno
: 0,
269 (num_read
< 0) ? dnssd_strerror(dnssd_errno
) : "");
271 syslog(LOG_INFO
, "dnssd_clientstub read_all(%d) DEFUNCT", sd
);
272 return (num_read
< 0 && dnssd_errno
== dnssd_EWOULDBLOCK
) ? read_all_wouldblock
: read_all_fail
;
277 return read_all_success
;
280 // Returns 1 if more bytes remain to be read on socket descriptor sd, 0 otherwise
281 static int more_bytes(dnssd_sock_t sd
)
283 struct timeval tv
= { 0, 0 };
292 ret
= select((int)sd
+1, fs
, (fd_set
*)NULL
, (fd_set
*)NULL
, &tv
);
301 // Compute the number of integers needed for storing "sd". Internally fd_set is stored
302 // as an array of ints with one bit for each fd and hence we need to compute
303 // the number of ints needed rather than the number of bytes. If "sd" is 32, we need
304 // two ints and not just one.
305 int nfdbits
= sizeof (int) * 8;
306 int nints
= (sd
/nfdbits
) + 1;
307 fs
= (fd_set
*)calloc(nints
, (size_t)sizeof(int));
310 syslog(LOG_WARNING
, "dnssd_clientstub more_bytes: malloc failed");
315 ret
= select((int)sd
+1, fs
, (fd_set
*)NULL
, (fd_set
*)NULL
, &tv
);
322 // set_waitlimit() implements a timeout using select. It is called from deliver_request() before recv() OR accept()
323 // to ensure the UDS clients are not blocked in these system calls indefinitely.
324 // Note: Ideally one should never be blocked here, because it indicates either mDNSResponder daemon is not yet up/hung/
325 // superbusy/crashed or some other OS bug. For eg: On Windows which suffers from 3rd party software
326 // (primarily 3rd party firewall software) interfering with proper functioning of the TCP protocol stack it is possible
327 // the next operation on this socket(recv/accept) is blocked since we depend on TCP to communicate with the system service.
328 static int set_waitlimit(dnssd_sock_t sock
, int timeout
)
330 int gDaemonErr
= kDNSServiceErr_NoError
;
332 // To prevent stack corruption since select does not work with timeout if fds > FD_SETSIZE(1024)
333 if (!gDaemonErr
&& sock
< FD_SETSIZE
)
342 if (!select((int)(sock
+ 1), &set
, NULL
, NULL
, &tv
))
344 // Ideally one should never hit this case: See comments before set_waitlimit()
345 syslog(LOG_WARNING
, "dnssd_clientstub set_waitlimit:_daemon timed out (%d secs) without any response: Socket %d", timeout
, sock
);
346 gDaemonErr
= kDNSServiceErr_Timeout
;
354 * allocate and initialize an ipc message header. Value of len should initially be the
355 * length of the data, and is set to the value of the data plus the header. data_start
356 * is set to point to the beginning of the data section. SeparateReturnSocket should be
357 * non-zero for calls that can't receive an immediate error return value on their primary
358 * socket, and therefore require a separate return path for the error code result.
359 * if zero, the path to a control socket is appended at the beginning of the message buffer.
360 * data_start is set past this string.
362 static ipc_msg_hdr
*create_hdr(uint32_t op
, size_t *len
, char **data_start
, int SeparateReturnSocket
, DNSServiceOp
*ref
)
367 #if !defined(USE_TCP_LOOPBACK)
368 char ctrl_path
[64] = ""; // "/var/tmp/dnssd_result_socket.xxxxxxxxxx-xxx-xxxxxx"
371 if (SeparateReturnSocket
)
373 #if defined(USE_TCP_LOOPBACK)
374 *len
+= 2; // Allocate space for two-byte port number
375 #elif defined(USE_NAMED_ERROR_RETURN_SOCKET)
377 if (gettimeofday(&tv
, NULL
) < 0)
378 { syslog(LOG_WARNING
, "dnssd_clientstub create_hdr: gettimeofday failed %d %s", dnssd_errno
, dnssd_strerror(dnssd_errno
)); return NULL
; }
379 snprintf(ctrl_path
, sizeof(ctrl_path
), "%s%d-%.3lx-%.6lu", CTL_PATH_PREFIX
, (int)getpid(),
380 (unsigned long)(tv
.tv_sec
& 0xFFF), (unsigned long)(tv
.tv_usec
));
381 *len
+= strlen(ctrl_path
) + 1;
383 *len
+= 1; // Allocate space for single zero byte (empty C string)
387 datalen
= (int) *len
;
388 *len
+= sizeof(ipc_msg_hdr
);
390 // Write message to buffer
392 if (!msg
) { syslog(LOG_WARNING
, "dnssd_clientstub create_hdr: malloc failed"); return NULL
; }
394 memset(msg
, 0, *len
);
395 hdr
= (ipc_msg_hdr
*)msg
;
396 hdr
->version
= VERSION
;
397 hdr
->datalen
= datalen
;
400 hdr
->client_context
= ref
->uid
;
402 *data_start
= msg
+ sizeof(ipc_msg_hdr
);
403 #if defined(USE_TCP_LOOPBACK)
404 // Put dummy data in for the port, since we don't know what it is yet.
405 // The data will get filled in before we send the message. This happens in deliver_request().
406 if (SeparateReturnSocket
) put_uint16(0, data_start
);
408 if (SeparateReturnSocket
) put_string(ctrl_path
, data_start
);
413 static void FreeDNSRecords(DNSServiceOp
*sdRef
)
415 DNSRecord
*rec
= sdRef
->rec
;
418 DNSRecord
*next
= rec
->recnext
;
424 static void FreeDNSServiceOp(DNSServiceOp
*x
)
426 // We don't use our DNSServiceRefValid macro here because if we're cleaning up after a socket() call failed
427 // then sockfd could legitimately contain a failing value (e.g. dnssd_InvalidSocket)
428 if ((x
->sockfd
^ x
->validator
) != ValidatorBits
)
430 static DNSServiceOp
*op_were_not_going_to_free_but_we_need_to_fool_the_analyzer
;
431 syslog(LOG_WARNING
, "dnssd_clientstub attempt to dispose invalid DNSServiceRef %p %08X %08X", x
, x
->sockfd
, x
->validator
);
432 op_were_not_going_to_free_but_we_need_to_fool_the_analyzer
= x
;
438 x
->sockfd
= dnssd_InvalidSocket
;
439 x
->validator
= 0xDDDDDDDD;
440 x
->op
= request_op_none
;
444 x
->ProcessReply
= NULL
;
445 x
->AppCallback
= NULL
;
446 x
->AppContext
= NULL
;
447 #if _DNS_SD_LIBDISPATCH
448 if (x
->disp_source
) dispatch_release(x
->disp_source
);
449 x
->disp_source
= NULL
;
450 x
->disp_queue
= NULL
;
452 // DNSRecords may have been added to subordinate sdRef e.g., DNSServiceRegister/DNSServiceAddRecord
453 // or on the main sdRef e.g., DNSServiceCreateConnection/DNSServiveRegisterRecord. DNSRecords may have
454 // been freed if the application called DNSRemoveRecord
465 // Return a connected service ref (deallocate with DNSServiceRefDeallocate)
466 static DNSServiceErrorType
ConnectToServer(DNSServiceRef
*ref
, DNSServiceFlags flags
, uint32_t op
, ProcessReplyFn ProcessReply
, void *AppCallback
, void *AppContext
)
470 dnssd_sockaddr_t saddr
;
475 syslog(LOG_WARNING
, "dnssd_clientstub DNSService operation with NULL DNSServiceRef");
476 return kDNSServiceErr_BadParam
;
479 if (flags
& kDNSServiceFlagsShareConnection
)
483 syslog(LOG_WARNING
, "dnssd_clientstub kDNSServiceFlagsShareConnection used with NULL DNSServiceRef");
484 return kDNSServiceErr_BadParam
;
486 if (!DNSServiceRefValid(*ref
) || ((*ref
)->op
!= connection_request
&& (*ref
)->op
!= connection_delegate_request
) || (*ref
)->primary
)
488 syslog(LOG_WARNING
, "dnssd_clientstub kDNSServiceFlagsShareConnection used with invalid DNSServiceRef %p %08X %08X op %d",
489 (*ref
), (*ref
)->sockfd
, (*ref
)->validator
, (*ref
)->op
);
491 return kDNSServiceErr_BadReference
;
500 if (WSAStartup(MAKEWORD(2,2), &wsaData
) != 0) { *ref
= NULL
; return kDNSServiceErr_ServiceNotRunning
; }
502 // <rdar://problem/4096913> If the system service is disabled, we only want to try to connect once
503 if (IsSystemServiceDisabled())
504 NumTries
= DNSSD_CLIENT_MAXTRIES
;
507 sdr
= malloc(sizeof(DNSServiceOp
));
510 syslog(LOG_WARNING
, "dnssd_clientstub ConnectToServer: malloc failed");
512 return kDNSServiceErr_NoMemory
;
516 sdr
->sockfd
= dnssd_InvalidSocket
;
517 sdr
->validator
= sdr
->sockfd
^ ValidatorBits
;
524 sdr
->ProcessReply
= ProcessReply
;
525 sdr
->AppCallback
= AppCallback
;
526 sdr
->AppContext
= AppContext
;
528 #if _DNS_SD_LIBDISPATCH
529 sdr
->disp_source
= NULL
;
530 sdr
->disp_queue
= NULL
;
532 sdr
->kacontext
= NULL
;
534 if (flags
& kDNSServiceFlagsShareConnection
)
536 DNSServiceOp
**p
= &(*ref
)->next
; // Append ourselves to end of primary's list
540 // Preincrement counter before we use it -- it helps with debugging if we know the all-zeroes ID should never appear
541 if (++(*ref
)->uid
.u32
[0] == 0)
542 ++(*ref
)->uid
.u32
[1]; // In parent DNSServiceOp increment UID counter
543 sdr
->primary
= *ref
; // Set our primary pointer
544 sdr
->sockfd
= (*ref
)->sockfd
; // Inherit primary's socket
545 sdr
->validator
= (*ref
)->validator
;
546 sdr
->uid
= (*ref
)->uid
;
547 //printf("ConnectToServer sharing socket %d\n", sdr->sockfd);
552 const unsigned long optval
= 1;
554 #ifndef USE_TCP_LOOPBACK
555 char* uds_serverpath
= getenv(MDNS_UDS_SERVERPATH_ENVVAR
);
556 if (uds_serverpath
== NULL
)
557 uds_serverpath
= MDNS_UDS_SERVERPATH
;
558 else if (strlen(uds_serverpath
) >= MAX_CTLPATH
)
560 uds_serverpath
= MDNS_UDS_SERVERPATH
;
561 syslog(LOG_WARNING
, "dnssd_clientstub ConnectToServer: using default path since env len is invalid");
565 sdr
->sockfd
= socket(AF_DNSSD
, SOCK_STREAM
, 0);
566 sdr
->validator
= sdr
->sockfd
^ ValidatorBits
;
567 if (!dnssd_SocketValid(sdr
->sockfd
))
569 syslog(LOG_WARNING
, "dnssd_clientstub ConnectToServer: socket failed %d %s", dnssd_errno
, dnssd_strerror(dnssd_errno
));
570 FreeDNSServiceOp(sdr
);
571 return kDNSServiceErr_NoMemory
;
574 // Some environments (e.g. OS X) support turning off SIGPIPE for a socket
575 if (setsockopt(sdr
->sockfd
, SOL_SOCKET
, SO_NOSIGPIPE
, &optval
, sizeof(optval
)) < 0)
576 syslog(LOG_WARNING
, "dnssd_clientstub ConnectToServer: SO_NOSIGPIPE failed %d %s", dnssd_errno
, dnssd_strerror(dnssd_errno
));
578 #if defined(USE_TCP_LOOPBACK)
579 saddr
.sin_family
= AF_INET
;
580 saddr
.sin_addr
.s_addr
= inet_addr(MDNS_TCP_SERVERADDR
);
581 saddr
.sin_port
= htons(MDNS_TCP_SERVERPORT
);
583 saddr
.sun_family
= AF_LOCAL
;
584 SetUDSPath(&saddr
, uds_serverpath
);
585 #if !defined(__ppc__) && defined(SO_DEFUNCTOK)
588 if (setsockopt(sdr
->sockfd
, SOL_SOCKET
, SO_DEFUNCTOK
, &defunct
, sizeof(defunct
)) < 0)
589 syslog(LOG_WARNING
, "dnssd_clientstub ConnectToServer: SO_DEFUNCTOK failed %d %s", dnssd_errno
, dnssd_strerror(dnssd_errno
));
596 int err
= connect(sdr
->sockfd
, (struct sockaddr
*) &saddr
, sizeof(saddr
));
598 break; // If we succeeded, return sdr
599 // If we failed, then it may be because the daemon is still launching.
600 // This can happen for processes that launch early in the boot process, while the
601 // daemon is still coming up. Rather than fail here, we wait 1 sec and try again.
602 // If, after DNSSD_CLIENT_MAXTRIES, we still can't connect to the daemon,
603 // then we give up and return a failure code.
604 if (++NumTries
< DNSSD_CLIENT_MAXTRIES
)
606 syslog(LOG_WARNING
, "dnssd_clientstub ConnectToServer: connect()-> No of tries: %d", NumTries
);
607 sleep(1); // Sleep a bit, then try again
611 #if !defined(USE_TCP_LOOPBACK)
612 syslog(LOG_WARNING
, "dnssd_clientstub ConnectToServer: connect() failed path:%s Socket:%d Err:%d Errno:%d %s",
613 uds_serverpath
, sdr
->sockfd
, err
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
615 dnssd_close(sdr
->sockfd
);
616 FreeDNSServiceOp(sdr
);
617 return kDNSServiceErr_ServiceNotRunning
;
620 //printf("ConnectToServer opened socket %d\n", sdr->sockfd);
624 return kDNSServiceErr_NoError
;
627 #define deliver_request_bailout(MSG) \
628 do { syslog(LOG_WARNING, "dnssd_clientstub deliver_request: %s failed %d (%s)", (MSG), dnssd_errno, dnssd_strerror(dnssd_errno)); goto cleanup; } while(0)
630 static DNSServiceErrorType
deliver_request(ipc_msg_hdr
*hdr
, DNSServiceOp
*sdr
)
634 syslog(LOG_WARNING
, "dnssd_clientstub deliver_request: !hdr");
635 return kDNSServiceErr_Unknown
;
638 uint32_t datalen
= hdr
->datalen
; // We take a copy here because we're going to convert hdr->datalen to network byte order
639 #if defined(USE_TCP_LOOPBACK) || defined(USE_NAMED_ERROR_RETURN_SOCKET)
640 char *const data
= (char *)hdr
+ sizeof(ipc_msg_hdr
);
642 dnssd_sock_t listenfd
= dnssd_InvalidSocket
, errsd
= dnssd_InvalidSocket
;
643 DNSServiceErrorType err
= kDNSServiceErr_Unknown
; // Default for the "goto cleanup" cases
645 // Note: need to check hdr->op, not sdr->op.
646 // hdr->op contains the code for the specific operation we're currently doing, whereas sdr->op
647 // contains the original parent DNSServiceOp (e.g. for an add_record_request, hdr->op will be
648 // add_record_request but the parent sdr->op will be connection_request or reg_service_request)
649 const int MakeSeparateReturnSocket
= (sdr
->primary
||
650 hdr
->op
== reg_record_request
|| hdr
->op
== add_record_request
|| hdr
->op
== update_record_request
|| hdr
->op
== remove_record_request
);
652 if (!DNSServiceRefValid(sdr
))
656 syslog(LOG_WARNING
, "dnssd_clientstub deliver_request: invalid DNSServiceRef %p %08X %08X", sdr
, sdr
->sockfd
, sdr
->validator
);
657 return kDNSServiceErr_BadReference
;
660 if (MakeSeparateReturnSocket
)
662 #if defined(USE_TCP_LOOPBACK)
664 union { uint16_t s
; u_char b
[2]; } port
;
665 dnssd_sockaddr_t caddr
;
666 dnssd_socklen_t len
= (dnssd_socklen_t
) sizeof(caddr
);
667 listenfd
= socket(AF_DNSSD
, SOCK_STREAM
, 0);
668 if (!dnssd_SocketValid(listenfd
)) deliver_request_bailout("TCP socket");
670 caddr
.sin_family
= AF_INET
;
672 caddr
.sin_addr
.s_addr
= inet_addr(MDNS_TCP_SERVERADDR
);
673 if (bind(listenfd
, (struct sockaddr
*) &caddr
, sizeof(caddr
)) < 0) deliver_request_bailout("TCP bind");
674 if (getsockname(listenfd
, (struct sockaddr
*) &caddr
, &len
) < 0) deliver_request_bailout("TCP getsockname");
675 if (listen(listenfd
, 1) < 0) deliver_request_bailout("TCP listen");
676 port
.s
= caddr
.sin_port
;
677 data
[0] = port
.b
[0]; // don't switch the byte order, as the
678 data
[1] = port
.b
[1]; // daemon expects it in network byte order
680 #elif defined(USE_NAMED_ERROR_RETURN_SOCKET)
684 dnssd_sockaddr_t caddr
;
685 listenfd
= socket(AF_DNSSD
, SOCK_STREAM
, 0);
686 if (!dnssd_SocketValid(listenfd
)) deliver_request_bailout("USE_NAMED_ERROR_RETURN_SOCKET socket");
688 caddr
.sun_family
= AF_LOCAL
;
689 // According to Stevens (section 3.2), there is no portable way to
690 // determine whether sa_len is defined on a particular platform.
691 #ifndef NOT_HAVE_SA_LEN
692 caddr
.sun_len
= sizeof(struct sockaddr_un
);
694 SetUDSPath(&caddr
, data
);
696 bindresult
= bind(listenfd
, (struct sockaddr
*)&caddr
, sizeof(caddr
));
698 if (bindresult
< 0) deliver_request_bailout("USE_NAMED_ERROR_RETURN_SOCKET bind");
699 if (listen(listenfd
, 1) < 0) deliver_request_bailout("USE_NAMED_ERROR_RETURN_SOCKET listen");
704 if (socketpair(AF_DNSSD
, SOCK_STREAM
, 0, sp
) < 0) deliver_request_bailout("socketpair");
707 errsd
= sp
[0]; // We'll read our four-byte error code from sp[0]
708 listenfd
= sp
[1]; // We'll send sp[1] to the daemon
709 #if !defined(__ppc__) && defined(SO_DEFUNCTOK)
712 if (setsockopt(errsd
, SOL_SOCKET
, SO_DEFUNCTOK
, &defunct
, sizeof(defunct
)) < 0)
713 syslog(LOG_WARNING
, "dnssd_clientstub ConnectToServer: SO_DEFUNCTOK failed %d %s", dnssd_errno
, dnssd_strerror(dnssd_errno
));
721 #if !defined(USE_TCP_LOOPBACK) && !defined(USE_NAMED_ERROR_RETURN_SOCKET)
722 // If we're going to make a separate error return socket, and pass it to the daemon
723 // using sendmsg, then we'll hold back one data byte to go with it.
724 // On some versions of Unix (including Leopard) sending a control message without
725 // any associated data does not work reliably -- e.g. one particular issue we ran
726 // into is that if the receiving program is in a kqueue loop waiting to be notified
727 // of the received message, it doesn't get woken up when the control message arrives.
728 if (MakeSeparateReturnSocket
|| sdr
->op
== send_bpf
)
729 datalen
--; // Okay to use sdr->op when checking for op == send_bpf
732 // At this point, our listening socket is set up and waiting, if necessary, for the daemon to connect back to
733 ConvertHeaderBytes(hdr
);
734 //syslog(LOG_WARNING, "dnssd_clientstub deliver_request writing %lu bytes", (unsigned long)(datalen + sizeof(ipc_msg_hdr)));
735 //if (MakeSeparateReturnSocket) syslog(LOG_WARNING, "dnssd_clientstub deliver_request name is %s", data);
736 #if TEST_SENDING_ONE_BYTE_AT_A_TIME
738 for (i
=0; i
<datalen
+ sizeof(ipc_msg_hdr
); i
++)
740 syslog(LOG_WARNING
, "dnssd_clientstub deliver_request writing %d", i
);
741 if (write_all(sdr
->sockfd
, ((char *)hdr
)+i
, 1) < 0)
742 { syslog(LOG_WARNING
, "write_all (byte %u) failed", i
); goto cleanup
; }
746 if (write_all(sdr
->sockfd
, (char *)hdr
, datalen
+ sizeof(ipc_msg_hdr
)) < 0)
748 // write_all already prints an error message if there is an error writing to
749 // the socket except for DEFUNCT. Logging here is unnecessary and also wrong
750 // in the case of DEFUNCT sockets
751 syslog(LOG_INFO
, "dnssd_clientstub deliver_request ERROR: write_all(%d, %lu bytes) failed",
752 sdr
->sockfd
, (unsigned long)(datalen
+ sizeof(ipc_msg_hdr
)));
757 if (!MakeSeparateReturnSocket
)
759 if (MakeSeparateReturnSocket
|| sdr
->op
== send_bpf
) // Okay to use sdr->op when checking for op == send_bpf
761 #if defined(USE_TCP_LOOPBACK) || defined(USE_NAMED_ERROR_RETURN_SOCKET)
762 // At this point we may wait in accept for a few milliseconds waiting for the daemon to connect back to us,
763 // but that's okay -- the daemon should not take more than a few milliseconds to respond.
764 // set_waitlimit() ensures we do not block indefinitely just in case something is wrong
765 dnssd_sockaddr_t daddr
;
766 dnssd_socklen_t len
= sizeof(daddr
);
767 if ((err
= set_waitlimit(listenfd
, DNSSD_CLIENT_TIMEOUT
)) != kDNSServiceErr_NoError
)
769 errsd
= accept(listenfd
, (struct sockaddr
*)&daddr
, &len
);
770 if (!dnssd_SocketValid(errsd
))
771 deliver_request_bailout("accept");
774 struct iovec vec
= { ((char *)hdr
) + sizeof(ipc_msg_hdr
) + datalen
, 1 }; // Send the last byte along with the SCM_RIGHTS
776 struct cmsghdr
*cmsg
;
777 char cbuf
[CMSG_SPACE(4 * sizeof(dnssd_sock_t
))];
784 if (MakeSeparateReturnSocket
|| sdr
->op
== send_bpf
) // Okay to use sdr->op when checking for op == send_bpf
786 if (sdr
->op
== send_bpf
)
789 char p
[12]; // Room for "/dev/bpf999" with terminating null
790 for (i
=0; i
<100; i
++)
792 snprintf(p
, sizeof(p
), "/dev/bpf%d", i
);
793 listenfd
= open(p
, O_RDWR
, 0);
794 //if (dnssd_SocketValid(listenfd)) syslog(LOG_WARNING, "Sending fd %d for %s", listenfd, p);
795 if (!dnssd_SocketValid(listenfd
) && dnssd_errno
!= EBUSY
)
796 syslog(LOG_WARNING
, "Error opening %s %d (%s)", p
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
797 if (dnssd_SocketValid(listenfd
) || dnssd_errno
!= EBUSY
) break;
800 msg
.msg_control
= cbuf
;
801 msg
.msg_controllen
= CMSG_LEN(sizeof(dnssd_sock_t
));
803 cmsg
= CMSG_FIRSTHDR(&msg
);
804 cmsg
->cmsg_len
= CMSG_LEN(sizeof(dnssd_sock_t
));
805 cmsg
->cmsg_level
= SOL_SOCKET
;
806 cmsg
->cmsg_type
= SCM_RIGHTS
;
807 *((dnssd_sock_t
*)CMSG_DATA(cmsg
)) = listenfd
;
810 #if TEST_KQUEUE_CONTROL_MESSAGE_BUG
814 #if DEBUG_64BIT_SCM_RIGHTS
815 syslog(LOG_WARNING
, "dnssd_clientstub sendmsg read sd=%d write sd=%d %ld %ld %ld/%ld/%ld/%ld",
816 errsd
, listenfd
, sizeof(dnssd_sock_t
), sizeof(void*),
817 sizeof(struct cmsghdr
) + sizeof(dnssd_sock_t
),
818 CMSG_LEN(sizeof(dnssd_sock_t
)), (long)CMSG_SPACE(sizeof(dnssd_sock_t
)),
819 (long)((char*)CMSG_DATA(cmsg
) + 4 - cbuf
));
820 #endif // DEBUG_64BIT_SCM_RIGHTS
822 if (sendmsg(sdr
->sockfd
, &msg
, 0) < 0)
824 syslog(LOG_WARNING
, "dnssd_clientstub deliver_request ERROR: sendmsg failed read sd=%d write sd=%d errno %d (%s)",
825 errsd
, listenfd
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
826 err
= kDNSServiceErr_Incompatible
;
830 #if DEBUG_64BIT_SCM_RIGHTS
831 syslog(LOG_WARNING
, "dnssd_clientstub sendmsg read sd=%d write sd=%d okay", errsd
, listenfd
);
832 #endif // DEBUG_64BIT_SCM_RIGHTS
835 // Close our end of the socketpair *before* calling read_all() to get the four-byte error code.
836 // Otherwise, if the daemon closes our socket (or crashes), we will have to wait for a timeout
837 // in read_all() because the socket is not closed (we still have an open reference to it)
838 // Note: listenfd is overwritten in the case of send_bpf above and that will be closed here
839 // for send_bpf operation.
840 dnssd_close(listenfd
);
841 listenfd
= dnssd_InvalidSocket
; // Make sure we don't close it a second time in the cleanup handling below
844 // At this point we may wait in read_all for a few milliseconds waiting for the daemon to send us the error code,
845 // but that's okay -- the daemon should not take more than a few milliseconds to respond.
846 // set_waitlimit() ensures we do not block indefinitely just in case something is wrong
847 if (sdr
->op
== send_bpf
) // Okay to use sdr->op when checking for op == send_bpf
848 err
= kDNSServiceErr_NoError
;
849 else if ((err
= set_waitlimit(errsd
, DNSSD_CLIENT_TIMEOUT
)) == kDNSServiceErr_NoError
)
851 if (read_all(errsd
, (char*)&err
, (int)sizeof(err
)) < 0)
852 err
= kDNSServiceErr_ServiceNotRunning
; // On failure read_all will have written a message to syslog for us
856 //syslog(LOG_WARNING, "dnssd_clientstub deliver_request: retrieved error code %d", err);
859 if (MakeSeparateReturnSocket
)
861 if (dnssd_SocketValid(listenfd
)) dnssd_close(listenfd
);
862 if (dnssd_SocketValid(errsd
)) dnssd_close(errsd
);
863 #if defined(USE_NAMED_ERROR_RETURN_SOCKET)
864 // syslog(LOG_WARNING, "dnssd_clientstub deliver_request: removing UDS: %s", data);
865 if (unlink(data
) != 0)
866 syslog(LOG_WARNING
, "dnssd_clientstub WARNING: unlink(\"%s\") failed errno %d (%s)", data
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
867 // else syslog(LOG_WARNING, "dnssd_clientstub deliver_request: removed UDS: %s", data);
875 dnssd_sock_t DNSSD_API
DNSServiceRefSockFD(DNSServiceRef sdRef
)
877 if (!sdRef
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRefSockFD called with NULL DNSServiceRef"); return dnssd_InvalidSocket
; }
879 if (!DNSServiceRefValid(sdRef
))
881 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRefSockFD called with invalid DNSServiceRef %p %08X %08X",
882 sdRef
, sdRef
->sockfd
, sdRef
->validator
);
883 return dnssd_InvalidSocket
;
888 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRefSockFD undefined for kDNSServiceFlagsShareConnection subordinate DNSServiceRef %p", sdRef
);
889 return dnssd_InvalidSocket
;
892 return sdRef
->sockfd
;
895 #if _DNS_SD_LIBDISPATCH
896 static void CallbackWithError(DNSServiceRef sdRef
, DNSServiceErrorType error
)
898 DNSServiceOp
*sdr
= sdRef
;
899 DNSServiceOp
*sdrNext
;
906 // We can't touch the sdr after the callback as it can be deallocated in the callback
909 sdr
->moreptr
= &morebytes
;
912 case resolve_request
:
913 if (sdr
->AppCallback
) ((DNSServiceResolveReply
) sdr
->AppCallback
)(sdr
, 0, 0, error
, NULL
, 0, 0, 0, NULL
, sdr
->AppContext
);
916 if (sdr
->AppCallback
) ((DNSServiceQueryRecordReply
)sdr
->AppCallback
)(sdr
, 0, 0, error
, NULL
, 0, 0, 0, NULL
, 0, sdr
->AppContext
);
918 case addrinfo_request
:
919 if (sdr
->AppCallback
) ((DNSServiceGetAddrInfoReply
)sdr
->AppCallback
)(sdr
, 0, 0, error
, NULL
, NULL
, 0, sdr
->AppContext
);
922 if (sdr
->AppCallback
) ((DNSServiceBrowseReply
) sdr
->AppCallback
)(sdr
, 0, 0, error
, NULL
, 0, NULL
, sdr
->AppContext
);
924 case reg_service_request
:
925 if (sdr
->AppCallback
) ((DNSServiceRegisterReply
) sdr
->AppCallback
)(sdr
, 0, error
, NULL
, 0, NULL
, sdr
->AppContext
);
927 case enumeration_request
:
928 if (sdr
->AppCallback
) ((DNSServiceDomainEnumReply
) sdr
->AppCallback
)(sdr
, 0, 0, error
, NULL
, sdr
->AppContext
);
930 case connection_request
:
931 case connection_delegate_request
:
932 // This means Register Record, walk the list of DNSRecords to do the callback
936 recnext
= rec
->recnext
;
937 if (rec
->AppCallback
) ((DNSServiceRegisterRecordReply
)rec
->AppCallback
)(sdr
, 0, 0, error
, rec
->AppContext
);
938 // The Callback can call DNSServiceRefDeallocate which in turn frees sdr and all the records.
939 // Detect that and return early
940 if (!morebytes
) {syslog(LOG_WARNING
, "dnssdclientstub:Record: CallbackwithError morebytes zero"); return;}
944 case port_mapping_request
:
945 if (sdr
->AppCallback
) ((DNSServiceNATPortMappingReply
)sdr
->AppCallback
)(sdr
, 0, 0, error
, 0, 0, 0, 0, 0, sdr
->AppContext
);
948 syslog(LOG_WARNING
, "dnssd_clientstub CallbackWithError called with bad op %d", sdr
->op
);
950 // If DNSServiceRefDeallocate was called in the callback, morebytes will be zero. As the sdRef
951 // (and its subordinates) have been freed, we should not proceed further. Note that when we
952 // call the callback with a subordinate sdRef the application can call DNSServiceRefDeallocate
953 // on the main sdRef and DNSServiceRefDeallocate handles this case by walking all the sdRefs and
954 // clears the moreptr so that we can terminate here.
956 // If DNSServiceRefDeallocate was not called in the callback, then set moreptr to NULL so that
957 // we don't access the stack variable after we return from this function.
958 if (!morebytes
) {syslog(LOG_WARNING
, "dnssdclientstub:sdRef: CallbackwithError morebytes zero sdr %p", sdr
); return;}
959 else {sdr
->moreptr
= NULL
;}
963 #endif // _DNS_SD_LIBDISPATCH
965 // Handle reply from server, calling application client callback. If there is no reply
966 // from the daemon on the socket contained in sdRef, the call will block.
967 DNSServiceErrorType DNSSD_API
DNSServiceProcessResult(DNSServiceRef sdRef
)
971 if (!sdRef
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceProcessResult called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam
; }
973 if (!DNSServiceRefValid(sdRef
))
975 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceProcessResult called with invalid DNSServiceRef %p %08X %08X", sdRef
, sdRef
->sockfd
, sdRef
->validator
);
976 return kDNSServiceErr_BadReference
;
981 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceProcessResult undefined for kDNSServiceFlagsShareConnection subordinate DNSServiceRef %p", sdRef
);
982 return kDNSServiceErr_BadReference
;
985 if (!sdRef
->ProcessReply
)
987 static int num_logs
= 0;
988 if (num_logs
< 10) syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceProcessResult called with DNSServiceRef with no ProcessReply function");
989 if (num_logs
< 1000) num_logs
++;else sleep(1);
990 return kDNSServiceErr_BadReference
;
998 // return NoError on EWOULDBLOCK. This will handle the case
999 // where a non-blocking socket is told there is data, but it was a false positive.
1000 // On error, read_all will write a message to syslog for us, so don't need to duplicate that here
1001 // Note: If we want to properly support using non-blocking sockets in the future
1002 int result
= read_all(sdRef
->sockfd
, (void *)&cbh
.ipc_hdr
, sizeof(cbh
.ipc_hdr
));
1003 if (result
== read_all_fail
)
1005 // Set the ProcessReply to NULL before callback as the sdRef can get deallocated
1007 sdRef
->ProcessReply
= NULL
;
1008 #if _DNS_SD_LIBDISPATCH
1009 // Call the callbacks with an error if using the dispatch API, as DNSServiceProcessResult
1010 // is not called by the application and hence need to communicate the error. Cancel the
1011 // source so that we don't get any more events
1012 // Note: read_all fails if we could not read from the daemon which can happen if the
1013 // daemon dies or the file descriptor is disconnected (defunct).
1014 if (sdRef
->disp_source
)
1016 dispatch_source_cancel(sdRef
->disp_source
);
1017 dispatch_release(sdRef
->disp_source
);
1018 sdRef
->disp_source
= NULL
;
1019 CallbackWithError(sdRef
, kDNSServiceErr_ServiceNotRunning
);
1022 // Don't touch sdRef anymore as it might have been deallocated
1023 return kDNSServiceErr_ServiceNotRunning
;
1025 else if (result
== read_all_wouldblock
)
1027 if (morebytes
&& sdRef
->logcounter
< 100)
1029 sdRef
->logcounter
++;
1030 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceProcessResult error: select indicated data was waiting but read_all returned EWOULDBLOCK");
1032 return kDNSServiceErr_NoError
;
1035 ConvertHeaderBytes(&cbh
.ipc_hdr
);
1036 if (cbh
.ipc_hdr
.version
!= VERSION
)
1038 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceProcessResult daemon version %d does not match client version %d", cbh
.ipc_hdr
.version
, VERSION
);
1039 sdRef
->ProcessReply
= NULL
;
1040 return kDNSServiceErr_Incompatible
;
1043 data
= malloc(cbh
.ipc_hdr
.datalen
);
1044 if (!data
) return kDNSServiceErr_NoMemory
;
1045 if (read_all(sdRef
->sockfd
, data
, cbh
.ipc_hdr
.datalen
) < 0) // On error, read_all will write a message to syslog for us
1047 // Set the ProcessReply to NULL before callback as the sdRef can get deallocated
1049 sdRef
->ProcessReply
= NULL
;
1050 #if _DNS_SD_LIBDISPATCH
1051 // Call the callbacks with an error if using the dispatch API, as DNSServiceProcessResult
1052 // is not called by the application and hence need to communicate the error. Cancel the
1053 // source so that we don't get any more events
1054 if (sdRef
->disp_source
)
1056 dispatch_source_cancel(sdRef
->disp_source
);
1057 dispatch_release(sdRef
->disp_source
);
1058 sdRef
->disp_source
= NULL
;
1059 CallbackWithError(sdRef
, kDNSServiceErr_ServiceNotRunning
);
1062 // Don't touch sdRef anymore as it might have been deallocated
1064 return kDNSServiceErr_ServiceNotRunning
;
1068 const char *ptr
= data
;
1069 cbh
.cb_flags
= get_flags (&ptr
, data
+ cbh
.ipc_hdr
.datalen
);
1070 cbh
.cb_interface
= get_uint32 (&ptr
, data
+ cbh
.ipc_hdr
.datalen
);
1071 cbh
.cb_err
= get_error_code(&ptr
, data
+ cbh
.ipc_hdr
.datalen
);
1073 // CAUTION: We have to handle the case where the client calls DNSServiceRefDeallocate from within the callback function.
1074 // To do this we set moreptr to point to morebytes. If the client does call DNSServiceRefDeallocate(),
1075 // then that routine will clear morebytes for us, and cause us to exit our loop.
1076 morebytes
= more_bytes(sdRef
->sockfd
);
1079 cbh
.cb_flags
|= kDNSServiceFlagsMoreComing
;
1080 sdRef
->moreptr
= &morebytes
;
1082 if (ptr
) sdRef
->ProcessReply(sdRef
, &cbh
, ptr
, data
+ cbh
.ipc_hdr
.datalen
);
1083 // Careful code here:
1084 // If morebytes is non-zero, that means we set sdRef->moreptr above, and the operation was not
1085 // cancelled out from under us, so now we need to clear sdRef->moreptr so we don't leave a stray
1086 // dangling pointer pointing to a long-gone stack variable.
1087 // If morebytes is zero, then one of two thing happened:
1088 // (a) morebytes was 0 above, so we didn't set sdRef->moreptr, so we don't need to clear it
1089 // (b) morebytes was 1 above, and we set sdRef->moreptr, but the operation was cancelled (with DNSServiceRefDeallocate()),
1090 // so we MUST NOT try to dereference our stale sdRef pointer.
1091 if (morebytes
) sdRef
->moreptr
= NULL
;
1094 } while (morebytes
);
1096 return kDNSServiceErr_NoError
;
1099 void DNSSD_API
DNSServiceRefDeallocate(DNSServiceRef sdRef
)
1101 if (!sdRef
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRefDeallocate called with NULL DNSServiceRef"); return; }
1103 if (!DNSServiceRefValid(sdRef
)) // Also verifies dnssd_SocketValid(sdRef->sockfd) for us too
1105 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRefDeallocate called with invalid DNSServiceRef %p %08X %08X", sdRef
, sdRef
->sockfd
, sdRef
->validator
);
1109 // If we're in the middle of a DNSServiceProcessResult() invocation for this DNSServiceRef, clear its morebytes flag to break it out of its while loop
1110 if (sdRef
->moreptr
) *(sdRef
->moreptr
) = 0;
1112 if (sdRef
->primary
) // If this is a subordinate DNSServiceOp, just send a 'stop' command
1114 DNSServiceOp
**p
= &sdRef
->primary
->next
;
1115 while (*p
&& *p
!= sdRef
) p
= &(*p
)->next
;
1120 ipc_msg_hdr
*hdr
= create_hdr(cancel_request
, &len
, &ptr
, 0, sdRef
);
1123 ConvertHeaderBytes(hdr
);
1124 write_all(sdRef
->sockfd
, (char *)hdr
, len
);
1128 FreeDNSServiceOp(sdRef
);
1131 else // else, make sure to terminate all subordinates as well
1133 #if _DNS_SD_LIBDISPATCH
1134 // The cancel handler will close the fd if a dispatch source has been set
1135 if (sdRef
->disp_source
)
1137 // By setting the ProcessReply to NULL, we make sure that we never call
1138 // the application callbacks ever, after returning from this function. We
1139 // assume that DNSServiceRefDeallocate is called from the serial queue
1140 // that was passed to DNSServiceSetDispatchQueue. Hence, dispatch_source_cancel
1141 // should cancel all the blocks on the queue and hence there should be no more
1142 // callbacks when we return from this function. Setting ProcessReply to NULL
1143 // provides extra protection.
1144 sdRef
->ProcessReply
= NULL
;
1145 shutdown(sdRef
->sockfd
, SHUT_WR
);
1146 dispatch_source_cancel(sdRef
->disp_source
);
1147 dispatch_release(sdRef
->disp_source
);
1148 sdRef
->disp_source
= NULL
;
1150 // if disp_queue is set, it means it used the DNSServiceSetDispatchQueue API. In that case,
1151 // when the source was cancelled, the fd was closed in the handler. Currently the source
1152 // is cancelled only when the mDNSResponder daemon dies
1153 else if (!sdRef
->disp_queue
) dnssd_close(sdRef
->sockfd
);
1155 dnssd_close(sdRef
->sockfd
);
1157 // Free DNSRecords added in DNSRegisterRecord if they have not
1158 // been freed in DNSRemoveRecord
1161 DNSServiceOp
*p
= sdRef
;
1162 sdRef
= sdRef
->next
;
1163 // When there is an error reading from the daemon e.g., bad fd, CallbackWithError
1164 // is called which sets moreptr. It might set the moreptr on a subordinate sdRef
1165 // but the application might call DNSServiceRefDeallocate with the main sdRef from
1166 // the callback. Hence, when we loop through the subordinate sdRefs, we need
1167 // to clear the moreptr so that CallbackWithError can terminate itself instead of
1168 // walking through the freed sdRefs.
1169 if (p
->moreptr
) *(p
->moreptr
) = 0;
1170 FreeDNSServiceOp(p
);
1175 DNSServiceErrorType DNSSD_API
DNSServiceGetProperty(const char *property
, void *result
, uint32_t *size
)
1177 DNSServiceErrorType err
;
1182 uint32_t actualsize
;
1184 if (!property
|| !result
|| !size
)
1185 return kDNSServiceErr_BadParam
;
1187 len
= strlen(property
) + 1;
1188 err
= ConnectToServer(&tmp
, 0, getproperty_request
, NULL
, NULL
, NULL
);
1189 if (err
) return err
;
1191 hdr
= create_hdr(getproperty_request
, &len
, &ptr
, 0, tmp
);
1192 if (!hdr
) { DNSServiceRefDeallocate(tmp
); return kDNSServiceErr_NoMemory
; }
1194 put_string(property
, &ptr
);
1195 err
= deliver_request(hdr
, tmp
); // Will free hdr for us
1196 if (err
) { DNSServiceRefDeallocate(tmp
); return err
; }
1198 if (read_all(tmp
->sockfd
, (char*)&actualsize
, (int)sizeof(actualsize
)) < 0)
1199 { DNSServiceRefDeallocate(tmp
); return kDNSServiceErr_ServiceNotRunning
; }
1201 actualsize
= ntohl(actualsize
);
1202 if (read_all(tmp
->sockfd
, (char*)result
, actualsize
< *size
? actualsize
: *size
) < 0)
1203 { DNSServiceRefDeallocate(tmp
); return kDNSServiceErr_ServiceNotRunning
; }
1204 DNSServiceRefDeallocate(tmp
);
1206 // Swap version result back to local process byte order
1207 if (!strcmp(property
, kDNSServiceProperty_DaemonVersion
) && *size
>= 4)
1208 *(uint32_t*)result
= ntohl(*(uint32_t*)result
);
1211 return kDNSServiceErr_NoError
;
1214 DNSServiceErrorType DNSSD_API
DNSServiceGetPID(const uint16_t srcport
, int32_t *pid
)
1219 size_t len
= sizeof(int32_t);
1221 DNSServiceErrorType err
= ConnectToServer(&tmp
, 0, getpid_request
, NULL
, NULL
, NULL
);
1222 if (err
) return err
;
1224 hdr
= create_hdr(getpid_request
, &len
, &ptr
, 0, tmp
);
1225 if (!hdr
) { DNSServiceRefDeallocate(tmp
); return kDNSServiceErr_NoMemory
; }
1227 put_uint16(srcport
, &ptr
);
1228 err
= deliver_request(hdr
, tmp
); // Will free hdr for us
1229 if (err
) { DNSServiceRefDeallocate(tmp
); return err
; }
1231 if (read_all(tmp
->sockfd
, (char*)pid
, sizeof(int32_t)) < 0)
1232 { DNSServiceRefDeallocate(tmp
); return kDNSServiceErr_ServiceNotRunning
; }
1234 DNSServiceRefDeallocate(tmp
);
1235 return kDNSServiceErr_NoError
;
1238 static void handle_resolve_response(DNSServiceOp
*const sdr
, const CallbackHeader
*const cbh
, const char *data
, const char *end
)
1240 char fullname
[kDNSServiceMaxDomainName
];
1241 char target
[kDNSServiceMaxDomainName
];
1243 union { uint16_t s
; u_char b
[2]; } port
;
1244 unsigned char *txtrecord
;
1246 get_string(&data
, end
, fullname
, kDNSServiceMaxDomainName
);
1247 get_string(&data
, end
, target
, kDNSServiceMaxDomainName
);
1248 if (!data
|| data
+ 2 > end
) goto fail
;
1250 port
.b
[0] = *data
++;
1251 port
.b
[1] = *data
++;
1252 txtlen
= get_uint16(&data
, end
);
1253 txtrecord
= (unsigned char *)get_rdata(&data
, end
, txtlen
);
1255 if (!data
) goto fail
;
1256 ((DNSServiceResolveReply
)sdr
->AppCallback
)(sdr
, cbh
->cb_flags
, cbh
->cb_interface
, cbh
->cb_err
, fullname
, target
, port
.s
, txtlen
, txtrecord
, sdr
->AppContext
);
1258 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1260 syslog(LOG_WARNING
, "dnssd_clientstub handle_resolve_response: error reading result from daemon");
1263 #if TARGET_OS_EMBEDDED
1265 static int32_t libSystemVersion
= 0;
1267 // Return true if the iOS application linked against a version of libsystem where P2P
1268 // interfaces were included by default when using kDNSServiceInterfaceIndexAny.
1269 // Using 160.0.0 == 0xa00000 as the version threshold.
1270 static int includeP2PWithIndexAny()
1272 if (libSystemVersion
== 0)
1273 libSystemVersion
= NSVersionOfLinkTimeLibrary("System");
1275 if (libSystemVersion
< 0xa00000)
1281 #else // TARGET_OS_EMBEDDED
1283 // always return false for non iOS platforms
1284 static int includeP2PWithIndexAny()
1289 #endif // TARGET_OS_EMBEDDED
1291 DNSServiceErrorType DNSSD_API DNSServiceResolve
1293 DNSServiceRef
*sdRef
,
1294 DNSServiceFlags flags
,
1295 uint32_t interfaceIndex
,
1297 const char *regtype
,
1299 DNSServiceResolveReply callBack
,
1306 DNSServiceErrorType err
;
1308 if (!sdRef
|| !name
|| !regtype
|| !domain
|| !callBack
) return kDNSServiceErr_BadParam
;
1310 // Need a real InterfaceID for WakeOnResolve
1311 if ((flags
& kDNSServiceFlagsWakeOnResolve
) != 0 &&
1312 ((interfaceIndex
== kDNSServiceInterfaceIndexAny
) ||
1313 (interfaceIndex
== kDNSServiceInterfaceIndexLocalOnly
) ||
1314 (interfaceIndex
== kDNSServiceInterfaceIndexUnicast
) ||
1315 (interfaceIndex
== kDNSServiceInterfaceIndexP2P
)))
1317 return kDNSServiceErr_BadParam
;
1320 if ((interfaceIndex
== kDNSServiceInterfaceIndexAny
) && includeP2PWithIndexAny())
1321 flags
|= kDNSServiceFlagsIncludeP2P
;
1323 err
= ConnectToServer(sdRef
, flags
, resolve_request
, handle_resolve_response
, callBack
, context
);
1324 if (err
) return err
; // On error ConnectToServer leaves *sdRef set to NULL
1326 // Calculate total message length
1327 len
= sizeof(flags
);
1328 len
+= sizeof(interfaceIndex
);
1329 len
+= strlen(name
) + 1;
1330 len
+= strlen(regtype
) + 1;
1331 len
+= strlen(domain
) + 1;
1333 hdr
= create_hdr(resolve_request
, &len
, &ptr
, (*sdRef
)->primary
? 1 : 0, *sdRef
);
1334 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
1336 put_flags(flags
, &ptr
);
1337 put_uint32(interfaceIndex
, &ptr
);
1338 put_string(name
, &ptr
);
1339 put_string(regtype
, &ptr
);
1340 put_string(domain
, &ptr
);
1342 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1343 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
1347 static void handle_query_response(DNSServiceOp
*const sdr
, const CallbackHeader
*const cbh
, const char *data
, const char *const end
)
1350 char name
[kDNSServiceMaxDomainName
];
1351 uint16_t rrtype
, rrclass
, rdlen
;
1354 get_string(&data
, end
, name
, kDNSServiceMaxDomainName
);
1355 rrtype
= get_uint16(&data
, end
);
1356 rrclass
= get_uint16(&data
, end
);
1357 rdlen
= get_uint16(&data
, end
);
1358 rdata
= get_rdata(&data
, end
, rdlen
);
1359 ttl
= get_uint32(&data
, end
);
1361 if (!data
) syslog(LOG_WARNING
, "dnssd_clientstub handle_query_response: error reading result from daemon");
1362 else ((DNSServiceQueryRecordReply
)sdr
->AppCallback
)(sdr
, cbh
->cb_flags
, cbh
->cb_interface
, cbh
->cb_err
, name
, rrtype
, rrclass
, rdlen
, rdata
, ttl
, sdr
->AppContext
);
1363 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1366 DNSServiceErrorType DNSSD_API DNSServiceQueryRecord
1368 DNSServiceRef
*sdRef
,
1369 DNSServiceFlags flags
,
1370 uint32_t interfaceIndex
,
1374 DNSServiceQueryRecordReply callBack
,
1381 DNSServiceErrorType err
;
1383 // NULL name handled below.
1384 if (!sdRef
|| !callBack
) return kDNSServiceErr_BadParam
;
1386 if ((interfaceIndex
== kDNSServiceInterfaceIndexAny
) && includeP2PWithIndexAny())
1387 flags
|= kDNSServiceFlagsIncludeP2P
;
1389 err
= ConnectToServer(sdRef
, flags
, query_request
, handle_query_response
, callBack
, context
);
1390 if (err
) return err
; // On error ConnectToServer leaves *sdRef set to NULL
1392 if (!name
) name
= "\0";
1394 // Calculate total message length
1395 len
= sizeof(flags
);
1396 len
+= sizeof(uint32_t); // interfaceIndex
1397 len
+= strlen(name
) + 1;
1398 len
+= 2 * sizeof(uint16_t); // rrtype, rrclass
1400 hdr
= create_hdr(query_request
, &len
, &ptr
, (*sdRef
)->primary
? 1 : 0, *sdRef
);
1401 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
1403 put_flags(flags
, &ptr
);
1404 put_uint32(interfaceIndex
, &ptr
);
1405 put_string(name
, &ptr
);
1406 put_uint16(rrtype
, &ptr
);
1407 put_uint16(rrclass
, &ptr
);
1409 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1410 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
1414 static void handle_addrinfo_response(DNSServiceOp
*const sdr
, const CallbackHeader
*const cbh
, const char *data
, const char *const end
)
1416 char hostname
[kDNSServiceMaxDomainName
];
1417 uint16_t rrtype
, rrclass
, rdlen
;
1421 get_string(&data
, end
, hostname
, kDNSServiceMaxDomainName
);
1422 rrtype
= get_uint16(&data
, end
);
1423 rrclass
= get_uint16(&data
, end
);
1424 rdlen
= get_uint16(&data
, end
);
1425 rdata
= get_rdata (&data
, end
, rdlen
);
1426 ttl
= get_uint32(&data
, end
);
1427 (void)rrclass
; // Unused
1429 // We only generate client callbacks for A and AAAA results (including NXDOMAIN results for
1430 // those types, if the client has requested those with the kDNSServiceFlagsReturnIntermediates).
1431 // Other result types, specifically CNAME referrals, are not communicated to the client, because
1432 // the DNSServiceGetAddrInfoReply interface doesn't have any meaningful way to communiate CNAME referrals.
1433 if (!data
) syslog(LOG_WARNING
, "dnssd_clientstub handle_addrinfo_response: error reading result from daemon");
1434 else if (rrtype
== kDNSServiceType_A
|| rrtype
== kDNSServiceType_AAAA
)
1436 struct sockaddr_in sa4
;
1437 struct sockaddr_in6 sa6
;
1438 const struct sockaddr
*const sa
= (rrtype
== kDNSServiceType_A
) ? (struct sockaddr
*)&sa4
: (struct sockaddr
*)&sa6
;
1439 if (rrtype
== kDNSServiceType_A
)
1441 memset(&sa4
, 0, sizeof(sa4
));
1442 #ifndef NOT_HAVE_SA_LEN
1443 sa4
.sin_len
= sizeof(struct sockaddr_in
);
1445 sa4
.sin_family
= AF_INET
;
1447 if (!cbh
->cb_err
) memcpy(&sa4
.sin_addr
, rdata
, rdlen
);
1451 memset(&sa6
, 0, sizeof(sa6
));
1452 #ifndef NOT_HAVE_SA_LEN
1453 sa6
.sin6_len
= sizeof(struct sockaddr_in6
);
1455 sa6
.sin6_family
= AF_INET6
;
1457 // sin6_flowinfo = 0;
1458 // sin6_scope_id = 0;
1461 memcpy(&sa6
.sin6_addr
, rdata
, rdlen
);
1462 if (IN6_IS_ADDR_LINKLOCAL(&sa6
.sin6_addr
)) sa6
.sin6_scope_id
= cbh
->cb_interface
;
1465 // Validation results are always delivered separately from the actual results of the
1466 // DNSServiceGetAddrInfo. Set the "addr" to NULL as per the documentation.
1468 // Note: If we deliver validation results along with the "addr" in the future, we need
1469 // a way to differentiate the negative response from validation-only response as both
1470 // has zero address.
1471 if (!(cbh
->cb_flags
& kDNSServiceFlagsValidate
))
1472 ((DNSServiceGetAddrInfoReply
)sdr
->AppCallback
)(sdr
, cbh
->cb_flags
, cbh
->cb_interface
, cbh
->cb_err
, hostname
, sa
, ttl
, sdr
->AppContext
);
1474 ((DNSServiceGetAddrInfoReply
)sdr
->AppCallback
)(sdr
, cbh
->cb_flags
, cbh
->cb_interface
, cbh
->cb_err
, hostname
, NULL
, 0, sdr
->AppContext
);
1475 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1479 DNSServiceErrorType DNSSD_API DNSServiceGetAddrInfo
1481 DNSServiceRef
*sdRef
,
1482 DNSServiceFlags flags
,
1483 uint32_t interfaceIndex
,
1485 const char *hostname
,
1486 DNSServiceGetAddrInfoReply callBack
,
1487 void *context
/* may be NULL */
1493 DNSServiceErrorType err
;
1495 if (!sdRef
|| !hostname
|| !callBack
) return kDNSServiceErr_BadParam
;
1497 err
= ConnectToServer(sdRef
, flags
, addrinfo_request
, handle_addrinfo_response
, callBack
, context
);
1500 return err
; // On error ConnectToServer leaves *sdRef set to NULL
1503 // Calculate total message length
1504 len
= sizeof(flags
);
1505 len
+= sizeof(uint32_t); // interfaceIndex
1506 len
+= sizeof(uint32_t); // protocol
1507 len
+= strlen(hostname
) + 1;
1509 hdr
= create_hdr(addrinfo_request
, &len
, &ptr
, (*sdRef
)->primary
? 1 : 0, *sdRef
);
1510 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
1512 put_flags(flags
, &ptr
);
1513 put_uint32(interfaceIndex
, &ptr
);
1514 put_uint32(protocol
, &ptr
);
1515 put_string(hostname
, &ptr
);
1517 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1518 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
1522 static void handle_browse_response(DNSServiceOp
*const sdr
, const CallbackHeader
*const cbh
, const char *data
, const char *const end
)
1524 char replyName
[256], replyType
[kDNSServiceMaxDomainName
], replyDomain
[kDNSServiceMaxDomainName
];
1525 get_string(&data
, end
, replyName
, 256);
1526 get_string(&data
, end
, replyType
, kDNSServiceMaxDomainName
);
1527 get_string(&data
, end
, replyDomain
, kDNSServiceMaxDomainName
);
1528 if (!data
) syslog(LOG_WARNING
, "dnssd_clientstub handle_browse_response: error reading result from daemon");
1529 else ((DNSServiceBrowseReply
)sdr
->AppCallback
)(sdr
, cbh
->cb_flags
, cbh
->cb_interface
, cbh
->cb_err
, replyName
, replyType
, replyDomain
, sdr
->AppContext
);
1530 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1533 DNSServiceErrorType DNSSD_API DNSServiceBrowse
1535 DNSServiceRef
*sdRef
,
1536 DNSServiceFlags flags
,
1537 uint32_t interfaceIndex
,
1538 const char *regtype
,
1540 DNSServiceBrowseReply callBack
,
1547 DNSServiceErrorType err
;
1549 // NULL domain handled below
1550 if (!sdRef
|| !regtype
|| !callBack
) return kDNSServiceErr_BadParam
;
1552 if ((interfaceIndex
== kDNSServiceInterfaceIndexAny
) && includeP2PWithIndexAny())
1553 flags
|= kDNSServiceFlagsIncludeP2P
;
1555 err
= ConnectToServer(sdRef
, flags
, browse_request
, handle_browse_response
, callBack
, context
);
1556 if (err
) return err
; // On error ConnectToServer leaves *sdRef set to NULL
1558 if (!domain
) domain
= "";
1559 len
= sizeof(flags
);
1560 len
+= sizeof(interfaceIndex
);
1561 len
+= strlen(regtype
) + 1;
1562 len
+= strlen(domain
) + 1;
1564 hdr
= create_hdr(browse_request
, &len
, &ptr
, (*sdRef
)->primary
? 1 : 0, *sdRef
);
1565 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
1567 put_flags(flags
, &ptr
);
1568 put_uint32(interfaceIndex
, &ptr
);
1569 put_string(regtype
, &ptr
);
1570 put_string(domain
, &ptr
);
1572 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1573 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
1577 DNSServiceErrorType DNSSD_API
DNSServiceSetDefaultDomainForUser(DNSServiceFlags flags
, const char *domain
);
1578 DNSServiceErrorType DNSSD_API
DNSServiceSetDefaultDomainForUser(DNSServiceFlags flags
, const char *domain
)
1580 DNSServiceErrorType err
;
1586 if (!domain
) return kDNSServiceErr_BadParam
;
1587 len
= sizeof(flags
) + strlen(domain
) + 1;
1589 err
= ConnectToServer(&tmp
, 0, setdomain_request
, NULL
, NULL
, NULL
);
1590 if (err
) return err
;
1592 hdr
= create_hdr(setdomain_request
, &len
, &ptr
, 0, tmp
);
1593 if (!hdr
) { DNSServiceRefDeallocate(tmp
); return kDNSServiceErr_NoMemory
; }
1595 put_flags(flags
, &ptr
);
1596 put_string(domain
, &ptr
);
1597 err
= deliver_request(hdr
, tmp
); // Will free hdr for us
1598 DNSServiceRefDeallocate(tmp
);
1602 static void handle_regservice_response(DNSServiceOp
*const sdr
, const CallbackHeader
*const cbh
, const char *data
, const char *const end
)
1604 char name
[256], regtype
[kDNSServiceMaxDomainName
], domain
[kDNSServiceMaxDomainName
];
1605 get_string(&data
, end
, name
, 256);
1606 get_string(&data
, end
, regtype
, kDNSServiceMaxDomainName
);
1607 get_string(&data
, end
, domain
, kDNSServiceMaxDomainName
);
1608 if (!data
) syslog(LOG_WARNING
, "dnssd_clientstub handle_regservice_response: error reading result from daemon");
1609 else ((DNSServiceRegisterReply
)sdr
->AppCallback
)(sdr
, cbh
->cb_flags
, cbh
->cb_err
, name
, regtype
, domain
, sdr
->AppContext
);
1610 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1613 DNSServiceErrorType DNSSD_API DNSServiceRegister
1615 DNSServiceRef
*sdRef
,
1616 DNSServiceFlags flags
,
1617 uint32_t interfaceIndex
,
1619 const char *regtype
,
1622 uint16_t PortInNetworkByteOrder
,
1624 const void *txtRecord
,
1625 DNSServiceRegisterReply callBack
,
1632 DNSServiceErrorType err
;
1633 union { uint16_t s
; u_char b
[2]; } port
= { PortInNetworkByteOrder
};
1635 if (!sdRef
|| !regtype
) return kDNSServiceErr_BadParam
;
1636 if (!name
) name
= "";
1637 if (!domain
) domain
= "";
1638 if (!host
) host
= "";
1639 if (!txtRecord
) txtRecord
= (void*)"";
1641 // No callback must have auto-rename
1642 if (!callBack
&& (flags
& kDNSServiceFlagsNoAutoRename
)) return kDNSServiceErr_BadParam
;
1644 if ((interfaceIndex
== kDNSServiceInterfaceIndexAny
) && includeP2PWithIndexAny())
1645 flags
|= kDNSServiceFlagsIncludeP2P
;
1647 err
= ConnectToServer(sdRef
, flags
, reg_service_request
, callBack
? handle_regservice_response
: NULL
, callBack
, context
);
1648 if (err
) return err
; // On error ConnectToServer leaves *sdRef set to NULL
1650 len
= sizeof(DNSServiceFlags
);
1651 len
+= sizeof(uint32_t); // interfaceIndex
1652 len
+= strlen(name
) + strlen(regtype
) + strlen(domain
) + strlen(host
) + 4;
1653 len
+= 2 * sizeof(uint16_t); // port, txtLen
1656 hdr
= create_hdr(reg_service_request
, &len
, &ptr
, (*sdRef
)->primary
? 1 : 0, *sdRef
);
1657 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
1658 if (!callBack
) hdr
->ipc_flags
|= IPC_FLAGS_NOREPLY
;
1660 put_flags(flags
, &ptr
);
1661 put_uint32(interfaceIndex
, &ptr
);
1662 put_string(name
, &ptr
);
1663 put_string(regtype
, &ptr
);
1664 put_string(domain
, &ptr
);
1665 put_string(host
, &ptr
);
1668 put_uint16(txtLen
, &ptr
);
1669 put_rdata(txtLen
, txtRecord
, &ptr
);
1671 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1672 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
1676 static void handle_enumeration_response(DNSServiceOp
*const sdr
, const CallbackHeader
*const cbh
, const char *data
, const char *const end
)
1678 char domain
[kDNSServiceMaxDomainName
];
1679 get_string(&data
, end
, domain
, kDNSServiceMaxDomainName
);
1680 if (!data
) syslog(LOG_WARNING
, "dnssd_clientstub handle_enumeration_response: error reading result from daemon");
1681 else ((DNSServiceDomainEnumReply
)sdr
->AppCallback
)(sdr
, cbh
->cb_flags
, cbh
->cb_interface
, cbh
->cb_err
, domain
, sdr
->AppContext
);
1682 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1685 DNSServiceErrorType DNSSD_API DNSServiceEnumerateDomains
1687 DNSServiceRef
*sdRef
,
1688 DNSServiceFlags flags
,
1689 uint32_t interfaceIndex
,
1690 DNSServiceDomainEnumReply callBack
,
1697 DNSServiceErrorType err
;
1701 if (!sdRef
|| !callBack
) return kDNSServiceErr_BadParam
;
1703 f1
= (flags
& kDNSServiceFlagsBrowseDomains
) != 0;
1704 f2
= (flags
& kDNSServiceFlagsRegistrationDomains
) != 0;
1705 if (f1
+ f2
!= 1) return kDNSServiceErr_BadParam
;
1707 err
= ConnectToServer(sdRef
, flags
, enumeration_request
, handle_enumeration_response
, callBack
, context
);
1708 if (err
) return err
; // On error ConnectToServer leaves *sdRef set to NULL
1710 len
= sizeof(DNSServiceFlags
);
1711 len
+= sizeof(uint32_t);
1713 hdr
= create_hdr(enumeration_request
, &len
, &ptr
, (*sdRef
)->primary
? 1 : 0, *sdRef
);
1714 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
1716 put_flags(flags
, &ptr
);
1717 put_uint32(interfaceIndex
, &ptr
);
1719 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1720 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
1724 static void ConnectionResponse(DNSServiceOp
*const sdr
, const CallbackHeader
*const cbh
, const char *const data
, const char *const end
)
1726 (void)data
; // Unused
1728 //printf("ConnectionResponse got %d\n", cbh->ipc_hdr.op);
1729 if (cbh
->ipc_hdr
.op
!= reg_record_reply_op
)
1731 // When using kDNSServiceFlagsShareConnection, need to search the list of associated DNSServiceOps
1732 // to find the one this response is intended for, and then call through to its ProcessReply handler.
1733 // We start with our first subordinate DNSServiceRef -- don't want to accidentally match the parent DNSServiceRef.
1734 DNSServiceOp
*op
= sdr
->next
;
1735 while (op
&& (op
->uid
.u32
[0] != cbh
->ipc_hdr
.client_context
.u32
[0] || op
->uid
.u32
[1] != cbh
->ipc_hdr
.client_context
.u32
[1]))
1737 // Note: We may sometimes not find a matching DNSServiceOp, in the case where the client has
1738 // cancelled the subordinate DNSServiceOp, but there are still messages in the pipeline from the daemon
1739 if (op
&& op
->ProcessReply
) op
->ProcessReply(op
, cbh
, data
, end
);
1740 // WARNING: Don't touch op or sdr after this -- client may have called DNSServiceRefDeallocate
1746 for (rec
= sdr
->rec
; rec
; rec
= rec
->recnext
)
1748 if (rec
->uid
.u32
[0] == cbh
->ipc_hdr
.client_context
.u32
[0] && rec
->uid
.u32
[1] == cbh
->ipc_hdr
.client_context
.u32
[1])
1751 // The record might have been freed already and hence not an
1752 // error if the record is not found.
1755 syslog(LOG_INFO
, "ConnectionResponse: Record not found");
1758 if (rec
->sdr
!= sdr
)
1760 syslog(LOG_WARNING
, "ConnectionResponse: Record sdr mismatch: rec %p sdr %p", rec
->sdr
, sdr
);
1764 if (sdr
->op
== connection_request
|| sdr
->op
== connection_delegate_request
)
1766 rec
->AppCallback(rec
->sdr
, rec
, cbh
->cb_flags
, cbh
->cb_err
, rec
->AppContext
);
1770 syslog(LOG_WARNING
, "dnssd_clientstub ConnectionResponse: sdr->op != connection_request");
1771 rec
->AppCallback(rec
->sdr
, rec
, 0, kDNSServiceErr_Unknown
, rec
->AppContext
);
1773 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1777 DNSServiceErrorType DNSSD_API
DNSServiceCreateConnection(DNSServiceRef
*sdRef
)
1779 DNSServiceErrorType err
;
1784 if (!sdRef
) return kDNSServiceErr_BadParam
;
1785 err
= ConnectToServer(sdRef
, 0, connection_request
, ConnectionResponse
, NULL
, NULL
);
1786 if (err
) return err
; // On error ConnectToServer leaves *sdRef set to NULL
1788 hdr
= create_hdr(connection_request
, &len
, &ptr
, 0, *sdRef
);
1789 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
1791 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1792 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
1796 #if APPLE_OSX_mDNSResponder && !TARGET_IPHONE_SIMULATOR
1797 DNSServiceErrorType DNSSD_API
DNSServiceCreateDelegateConnection(DNSServiceRef
*sdRef
, int32_t pid
, uuid_t uuid
)
1803 if (!sdRef
) return kDNSServiceErr_BadParam
;
1804 DNSServiceErrorType err
= ConnectToServer(sdRef
, 0, connection_delegate_request
, ConnectionResponse
, NULL
, NULL
);
1807 return err
; // On error ConnectToServer leaves *sdRef set to NULL
1810 // Only one of the two options can be set. If pid is zero, uuid is used.
1811 // If both are specified only pid will be used. We send across the pid
1812 // so that the daemon knows what to read from the socket.
1814 len
+= sizeof(int32_t);
1816 hdr
= create_hdr(connection_delegate_request
, &len
, &ptr
, 0, *sdRef
);
1819 DNSServiceRefDeallocate(*sdRef
);
1821 return kDNSServiceErr_NoMemory
;
1824 if (pid
&& setsockopt((*sdRef
)->sockfd
, SOL_SOCKET
, SO_DELEGATED
, &pid
, sizeof(pid
)) == -1)
1826 syslog(LOG_WARNING
, "dnssdclientstub: Could not setsockopt() for PID[%d], no entitlements or process(pid) invalid errno:%d (%s)", pid
, errno
, strerror(errno
));
1827 // Free the hdr in case we return before calling deliver_request()
1830 DNSServiceRefDeallocate(*sdRef
);
1832 return kDNSServiceErr_NoAuth
;
1835 if (!pid
&& setsockopt((*sdRef
)->sockfd
, SOL_SOCKET
, SO_DELEGATED_UUID
, uuid
, sizeof(uuid_t
)) == -1)
1837 syslog(LOG_WARNING
, "dnssdclientstub: Could not setsockopt() for UUID, no entitlements or process(uuid) invalid errno:%d (%s) ", errno
, strerror(errno
));
1838 // Free the hdr in case we return before calling deliver_request()
1841 DNSServiceRefDeallocate(*sdRef
);
1843 return kDNSServiceErr_NoAuth
;
1846 put_uint32(pid
, &ptr
);
1848 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1851 DNSServiceRefDeallocate(*sdRef
);
1856 #elif TARGET_IPHONE_SIMULATOR // This hack is for Simulator platform only
1857 DNSServiceErrorType DNSSD_API
DNSServiceCreateDelegateConnection(DNSServiceRef
*sdRef
, int32_t pid
, uuid_t uuid
)
1861 return DNSServiceCreateConnection(sdRef
);
1865 DNSServiceErrorType DNSSD_API DNSServiceRegisterRecord
1867 DNSServiceRef sdRef
,
1868 DNSRecordRef
*RecordRef
,
1869 DNSServiceFlags flags
,
1870 uint32_t interfaceIndex
,
1871 const char *fullname
,
1877 DNSServiceRegisterRecordReply callBack
,
1883 ipc_msg_hdr
*hdr
= NULL
;
1884 DNSRecordRef rref
= NULL
;
1886 int f1
= (flags
& kDNSServiceFlagsShared
) != 0;
1887 int f2
= (flags
& kDNSServiceFlagsUnique
) != 0;
1888 if (f1
+ f2
!= 1) return kDNSServiceErr_BadParam
;
1890 if ((interfaceIndex
== kDNSServiceInterfaceIndexAny
) && includeP2PWithIndexAny())
1891 flags
|= kDNSServiceFlagsIncludeP2P
;
1893 if (!sdRef
|| !RecordRef
|| !fullname
|| (!rdata
&& rdlen
) || !callBack
)
1895 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRegisterRecord called with NULL parameter");
1896 return kDNSServiceErr_BadParam
;
1899 if (!DNSServiceRefValid(sdRef
))
1901 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRegisterRecord called with invalid DNSServiceRef %p %08X %08X", sdRef
, sdRef
->sockfd
, sdRef
->validator
);
1902 return kDNSServiceErr_BadReference
;
1905 if (sdRef
->op
!= connection_request
&& sdRef
->op
!= connection_delegate_request
)
1907 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRegisterRecord called with non-DNSServiceCreateConnection DNSServiceRef %p %d", sdRef
, sdRef
->op
);
1908 return kDNSServiceErr_BadReference
;
1913 len
= sizeof(DNSServiceFlags
);
1914 len
+= 2 * sizeof(uint32_t); // interfaceIndex, ttl
1915 len
+= 3 * sizeof(uint16_t); // rrtype, rrclass, rdlen
1916 len
+= strlen(fullname
) + 1;
1919 // Bump up the uid. Normally for shared operations (kDNSServiceFlagsShareConnection), this
1920 // is done in ConnectToServer. For DNSServiceRegisterRecord, ConnectToServer has already
1921 // been called. As multiple DNSServiceRegisterRecords can be multiplexed over a single
1922 // connection, we need a way to demultiplex the response so that the callback corresponding
1923 // to the right DNSServiceRegisterRecord instance can be called. Use the same mechanism that
1924 // is used by kDNSServiceFlagsShareConnection. create_hdr copies the uid value to ipc
1925 // hdr->client_context which will be returned in the ipc response.
1926 if (++sdRef
->uid
.u32
[0] == 0)
1927 ++sdRef
->uid
.u32
[1];
1928 hdr
= create_hdr(reg_record_request
, &len
, &ptr
, 1, sdRef
);
1929 if (!hdr
) return kDNSServiceErr_NoMemory
;
1931 put_flags(flags
, &ptr
);
1932 put_uint32(interfaceIndex
, &ptr
);
1933 put_string(fullname
, &ptr
);
1934 put_uint16(rrtype
, &ptr
);
1935 put_uint16(rrclass
, &ptr
);
1936 put_uint16(rdlen
, &ptr
);
1937 put_rdata(rdlen
, rdata
, &ptr
);
1938 put_uint32(ttl
, &ptr
);
1940 rref
= malloc(sizeof(DNSRecord
));
1941 if (!rref
) { free(hdr
); return kDNSServiceErr_NoMemory
; }
1942 rref
->AppContext
= context
;
1943 rref
->AppCallback
= callBack
;
1944 rref
->record_index
= sdRef
->max_index
++;
1946 rref
->recnext
= NULL
;
1948 // Remember the uid that we are sending across so that we can match
1949 // when the response comes back.
1950 rref
->uid
= sdRef
->uid
;
1951 hdr
->reg_index
= rref
->record_index
;
1954 while (*p
) p
= &(*p
)->recnext
;
1957 return deliver_request(hdr
, sdRef
); // Will free hdr for us
1960 // sdRef returned by DNSServiceRegister()
1961 DNSServiceErrorType DNSSD_API DNSServiceAddRecord
1963 DNSServiceRef sdRef
,
1964 DNSRecordRef
*RecordRef
,
1965 DNSServiceFlags flags
,
1978 if (!sdRef
|| !RecordRef
|| (!rdata
&& rdlen
))
1980 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceAddRecord called with NULL parameter");
1981 return kDNSServiceErr_BadParam
;
1983 if (sdRef
->op
!= reg_service_request
)
1985 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceAddRecord called with non-DNSServiceRegister DNSServiceRef %p %d", sdRef
, sdRef
->op
);
1986 return kDNSServiceErr_BadReference
;
1989 if (!DNSServiceRefValid(sdRef
))
1991 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceAddRecord called with invalid DNSServiceRef %p %08X %08X", sdRef
, sdRef
->sockfd
, sdRef
->validator
);
1992 return kDNSServiceErr_BadReference
;
1997 len
+= 2 * sizeof(uint16_t); // rrtype, rdlen
1999 len
+= sizeof(uint32_t);
2000 len
+= sizeof(DNSServiceFlags
);
2002 hdr
= create_hdr(add_record_request
, &len
, &ptr
, 1, sdRef
);
2003 if (!hdr
) return kDNSServiceErr_NoMemory
;
2004 put_flags(flags
, &ptr
);
2005 put_uint16(rrtype
, &ptr
);
2006 put_uint16(rdlen
, &ptr
);
2007 put_rdata(rdlen
, rdata
, &ptr
);
2008 put_uint32(ttl
, &ptr
);
2010 rref
= malloc(sizeof(DNSRecord
));
2011 if (!rref
) { free(hdr
); return kDNSServiceErr_NoMemory
; }
2012 rref
->AppContext
= NULL
;
2013 rref
->AppCallback
= NULL
;
2014 rref
->record_index
= sdRef
->max_index
++;
2016 rref
->recnext
= NULL
;
2018 hdr
->reg_index
= rref
->record_index
;
2021 while (*p
) p
= &(*p
)->recnext
;
2024 return deliver_request(hdr
, sdRef
); // Will free hdr for us
2027 // DNSRecordRef returned by DNSServiceRegisterRecord or DNSServiceAddRecord
2028 DNSServiceErrorType DNSSD_API DNSServiceUpdateRecord
2030 DNSServiceRef sdRef
,
2031 DNSRecordRef RecordRef
,
2032 DNSServiceFlags flags
,
2042 if (!sdRef
|| (!rdata
&& rdlen
))
2044 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceUpdateRecord called with NULL parameter");
2045 return kDNSServiceErr_BadParam
;
2048 if (!DNSServiceRefValid(sdRef
))
2050 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceUpdateRecord called with invalid DNSServiceRef %p %08X %08X", sdRef
, sdRef
->sockfd
, sdRef
->validator
);
2051 return kDNSServiceErr_BadReference
;
2054 // Note: RecordRef is allowed to be NULL
2056 len
+= sizeof(uint16_t);
2058 len
+= sizeof(uint32_t);
2059 len
+= sizeof(DNSServiceFlags
);
2061 hdr
= create_hdr(update_record_request
, &len
, &ptr
, 1, sdRef
);
2062 if (!hdr
) return kDNSServiceErr_NoMemory
;
2063 hdr
->reg_index
= RecordRef
? RecordRef
->record_index
: TXT_RECORD_INDEX
;
2064 put_flags(flags
, &ptr
);
2065 put_uint16(rdlen
, &ptr
);
2066 put_rdata(rdlen
, rdata
, &ptr
);
2067 put_uint32(ttl
, &ptr
);
2068 return deliver_request(hdr
, sdRef
); // Will free hdr for us
2071 DNSServiceErrorType DNSSD_API DNSServiceRemoveRecord
2073 DNSServiceRef sdRef
,
2074 DNSRecordRef RecordRef
,
2075 DNSServiceFlags flags
2081 DNSServiceErrorType err
;
2083 if (!sdRef
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRemoveRecord called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam
; }
2084 if (!RecordRef
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRemoveRecord called with NULL DNSRecordRef"); return kDNSServiceErr_BadParam
; }
2085 if (!sdRef
->max_index
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRemoveRecord called with bad DNSServiceRef"); return kDNSServiceErr_BadReference
; }
2087 if (!DNSServiceRefValid(sdRef
))
2089 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRemoveRecord called with invalid DNSServiceRef %p %08X %08X", sdRef
, sdRef
->sockfd
, sdRef
->validator
);
2090 return kDNSServiceErr_BadReference
;
2093 len
+= sizeof(flags
);
2094 hdr
= create_hdr(remove_record_request
, &len
, &ptr
, 1, sdRef
);
2095 if (!hdr
) return kDNSServiceErr_NoMemory
;
2096 hdr
->reg_index
= RecordRef
->record_index
;
2097 put_flags(flags
, &ptr
);
2098 err
= deliver_request(hdr
, sdRef
); // Will free hdr for us
2101 // This RecordRef could have been allocated in DNSServiceRegisterRecord or DNSServiceAddRecord.
2102 // If so, delink from the list before freeing
2103 DNSRecord
**p
= &sdRef
->rec
;
2104 while (*p
&& *p
!= RecordRef
) p
= &(*p
)->recnext
;
2105 if (*p
) *p
= RecordRef
->recnext
;
2111 DNSServiceErrorType DNSSD_API DNSServiceReconfirmRecord
2113 DNSServiceFlags flags
,
2114 uint32_t interfaceIndex
,
2115 const char *fullname
,
2122 DNSServiceErrorType err
;
2128 if (!fullname
|| (!rdata
&& rdlen
)) return kDNSServiceErr_BadParam
;
2130 err
= ConnectToServer(&tmp
, flags
, reconfirm_record_request
, NULL
, NULL
, NULL
);
2131 if (err
) return err
;
2133 len
= sizeof(DNSServiceFlags
);
2134 len
+= sizeof(uint32_t);
2135 len
+= strlen(fullname
) + 1;
2136 len
+= 3 * sizeof(uint16_t);
2138 hdr
= create_hdr(reconfirm_record_request
, &len
, &ptr
, 0, tmp
);
2139 if (!hdr
) { DNSServiceRefDeallocate(tmp
); return kDNSServiceErr_NoMemory
; }
2141 put_flags(flags
, &ptr
);
2142 put_uint32(interfaceIndex
, &ptr
);
2143 put_string(fullname
, &ptr
);
2144 put_uint16(rrtype
, &ptr
);
2145 put_uint16(rrclass
, &ptr
);
2146 put_uint16(rdlen
, &ptr
);
2147 put_rdata(rdlen
, rdata
, &ptr
);
2149 err
= deliver_request(hdr
, tmp
); // Will free hdr for us
2150 DNSServiceRefDeallocate(tmp
);
2155 static void handle_port_mapping_response(DNSServiceOp
*const sdr
, const CallbackHeader
*const cbh
, const char *data
, const char *const end
)
2157 union { uint32_t l
; u_char b
[4]; } addr
;
2159 union { uint16_t s
; u_char b
[2]; } internalPort
;
2160 union { uint16_t s
; u_char b
[2]; } externalPort
;
2163 if (!data
|| data
+ 13 > end
) goto fail
;
2165 addr
.b
[0] = *data
++;
2166 addr
.b
[1] = *data
++;
2167 addr
.b
[2] = *data
++;
2168 addr
.b
[3] = *data
++;
2170 internalPort
.b
[0] = *data
++;
2171 internalPort
.b
[1] = *data
++;
2172 externalPort
.b
[0] = *data
++;
2173 externalPort
.b
[1] = *data
++;
2174 ttl
= get_uint32(&data
, end
);
2175 if (!data
) goto fail
;
2177 ((DNSServiceNATPortMappingReply
)sdr
->AppCallback
)(sdr
, cbh
->cb_flags
, cbh
->cb_interface
, cbh
->cb_err
, addr
.l
, protocol
, internalPort
.s
, externalPort
.s
, ttl
, sdr
->AppContext
);
2179 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
2182 syslog(LOG_WARNING
, "dnssd_clientstub handle_port_mapping_response: error reading result from daemon");
2185 DNSServiceErrorType DNSSD_API DNSServiceNATPortMappingCreate
2187 DNSServiceRef
*sdRef
,
2188 DNSServiceFlags flags
,
2189 uint32_t interfaceIndex
,
2190 uint32_t protocol
, /* TCP and/or UDP */
2191 uint16_t internalPortInNetworkByteOrder
,
2192 uint16_t externalPortInNetworkByteOrder
,
2193 uint32_t ttl
, /* time to live in seconds */
2194 DNSServiceNATPortMappingReply callBack
,
2195 void *context
/* may be NULL */
2201 union { uint16_t s
; u_char b
[2]; } internalPort
= { internalPortInNetworkByteOrder
};
2202 union { uint16_t s
; u_char b
[2]; } externalPort
= { externalPortInNetworkByteOrder
};
2204 DNSServiceErrorType err
= ConnectToServer(sdRef
, flags
, port_mapping_request
, handle_port_mapping_response
, callBack
, context
);
2205 if (err
) return err
; // On error ConnectToServer leaves *sdRef set to NULL
2207 len
= sizeof(flags
);
2208 len
+= sizeof(interfaceIndex
);
2209 len
+= sizeof(protocol
);
2210 len
+= sizeof(internalPort
);
2211 len
+= sizeof(externalPort
);
2214 hdr
= create_hdr(port_mapping_request
, &len
, &ptr
, (*sdRef
)->primary
? 1 : 0, *sdRef
);
2215 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
2217 put_flags(flags
, &ptr
);
2218 put_uint32(interfaceIndex
, &ptr
);
2219 put_uint32(protocol
, &ptr
);
2220 *ptr
++ = internalPort
.b
[0];
2221 *ptr
++ = internalPort
.b
[1];
2222 *ptr
++ = externalPort
.b
[0];
2223 *ptr
++ = externalPort
.b
[1];
2224 put_uint32(ttl
, &ptr
);
2226 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
2227 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
2231 #if _DNS_SD_LIBDISPATCH
2232 DNSServiceErrorType DNSSD_API DNSServiceSetDispatchQueue
2234 DNSServiceRef service
,
2235 dispatch_queue_t queue
2238 int dnssd_fd
= DNSServiceRefSockFD(service
);
2239 if (dnssd_fd
== dnssd_InvalidSocket
) return kDNSServiceErr_BadParam
;
2242 syslog(LOG_WARNING
, "dnssd_clientstub: DNSServiceSetDispatchQueue dispatch queue NULL");
2243 return kDNSServiceErr_BadParam
;
2245 if (service
->disp_queue
)
2247 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceSetDispatchQueue dispatch queue set already");
2248 return kDNSServiceErr_BadParam
;
2250 if (service
->disp_source
)
2252 syslog(LOG_WARNING
, "DNSServiceSetDispatchQueue dispatch source set already");
2253 return kDNSServiceErr_BadParam
;
2255 service
->disp_source
= dispatch_source_create(DISPATCH_SOURCE_TYPE_READ
, dnssd_fd
, 0, queue
);
2256 if (!service
->disp_source
)
2258 syslog(LOG_WARNING
, "DNSServiceSetDispatchQueue dispatch_source_create failed");
2259 return kDNSServiceErr_NoMemory
;
2261 service
->disp_queue
= queue
;
2262 dispatch_source_set_event_handler(service
->disp_source
, ^{DNSServiceProcessResult(service
);});
2263 dispatch_source_set_cancel_handler(service
->disp_source
, ^{dnssd_close(dnssd_fd
);});
2264 dispatch_resume(service
->disp_source
);
2265 return kDNSServiceErr_NoError
;
2267 #endif // _DNS_SD_LIBDISPATCH
2269 #if !defined(_WIN32)
2271 static void DNSSD_API
SleepKeepaliveCallback(DNSServiceRef sdRef
, DNSRecordRef rec
, const DNSServiceFlags flags
,
2272 DNSServiceErrorType errorCode
, void *context
)
2274 SleepKAContext
*ka
= (SleepKAContext
*)context
;
2275 (void)rec
; // Unused
2276 (void)flags
; // Unused
2278 if (sdRef
->kacontext
!= context
)
2279 syslog(LOG_WARNING
, "SleepKeepaliveCallback context mismatch");
2281 if (ka
->AppCallback
)
2282 ((DNSServiceSleepKeepaliveReply
)ka
->AppCallback
)(sdRef
, errorCode
, ka
->AppContext
);
2285 DNSServiceErrorType DNSSD_API DNSServiceSleepKeepalive
2287 DNSServiceRef
*sdRef
,
2288 DNSServiceFlags flags
,
2290 unsigned int timeout
,
2291 DNSServiceSleepKeepaliveReply callBack
,
2295 char source_str
[INET6_ADDRSTRLEN
];
2296 char target_str
[INET6_ADDRSTRLEN
];
2297 struct sockaddr_storage lss
;
2298 struct sockaddr_storage rss
;
2299 socklen_t len1
, len2
;
2300 unsigned int len
, proxyreclen
;
2302 DNSServiceErrorType err
;
2303 DNSRecordRef record
= NULL
;
2307 unsigned int i
, unique
;
2310 (void) flags
; //unused
2311 if (!timeout
) return kDNSServiceErr_BadParam
;
2315 if (getsockname(fd
, (struct sockaddr
*)&lss
, &len1
) < 0)
2317 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive: getsockname %d\n", errno
);
2318 return kDNSServiceErr_BadParam
;
2322 if (getpeername(fd
, (struct sockaddr
*)&rss
, &len2
) < 0)
2324 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive: getpeername %d\n", errno
);
2325 return kDNSServiceErr_BadParam
;
2330 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive local/remote info not same");
2331 return kDNSServiceErr_Unknown
;
2335 if (lss
.ss_family
== AF_INET
)
2337 struct sockaddr_in
*sl
= (struct sockaddr_in
*)&lss
;
2338 struct sockaddr_in
*sr
= (struct sockaddr_in
*)&rss
;
2339 unsigned char *ptr
= (unsigned char *)&sl
->sin_addr
;
2341 if (!inet_ntop(AF_INET
, (const void *)&sr
->sin_addr
, target_str
, sizeof (target_str
)))
2343 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive remote info failed %d", errno
);
2344 return kDNSServiceErr_Unknown
;
2346 if (!inet_ntop(AF_INET
, (const void *)&sl
->sin_addr
, source_str
, sizeof (source_str
)))
2348 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive local info failed %d", errno
);
2349 return kDNSServiceErr_Unknown
;
2351 // Sum of all bytes in the local address and port should result in a unique
2352 // number in the local network
2353 for (i
= 0; i
< sizeof(struct in_addr
); i
++)
2355 unique
+= sl
->sin_port
;
2356 len
= snprintf(buf
+1, sizeof(buf
) - 1, "t=%u h=%s d=%s l=%u r=%u", timeout
, source_str
, target_str
, ntohs(sl
->sin_port
), ntohs(sr
->sin_port
));
2360 struct sockaddr_in6
*sl6
= (struct sockaddr_in6
*)&lss
;
2361 struct sockaddr_in6
*sr6
= (struct sockaddr_in6
*)&rss
;
2362 unsigned char *ptr
= (unsigned char *)&sl6
->sin6_addr
;
2364 if (!inet_ntop(AF_INET6
, (const void *)&sr6
->sin6_addr
, target_str
, sizeof (target_str
)))
2366 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive remote6 info failed %d", errno
);
2367 return kDNSServiceErr_Unknown
;
2369 if (!inet_ntop(AF_INET6
, (const void *)&sl6
->sin6_addr
, source_str
, sizeof (source_str
)))
2371 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive local6 info failed %d", errno
);
2372 return kDNSServiceErr_Unknown
;
2374 for (i
= 0; i
< sizeof(struct in6_addr
); i
++)
2376 unique
+= sl6
->sin6_port
;
2377 len
= snprintf(buf
+1, sizeof(buf
) - 1, "t=%u H=%s D=%s l=%u r=%u", timeout
, source_str
, target_str
, ntohs(sl6
->sin6_port
), ntohs(sr6
->sin6_port
));
2380 if (len
>= (sizeof(buf
) - 1))
2382 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive could not fit local/remote info");
2383 return kDNSServiceErr_Unknown
;
2385 // Include the NULL byte also in the first byte. The total length of the record includes the
2388 proxyreclen
= len
+ 2;
2390 len
= snprintf(name
, sizeof(name
), "%u", unique
);
2391 if (len
>= sizeof(name
))
2393 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive could not fit unique");
2394 return kDNSServiceErr_Unknown
;
2397 len
= snprintf(recname
, sizeof(recname
), "%s.%s", name
, "_keepalive._dns-sd._udp.local");
2398 if (len
>= sizeof(recname
))
2400 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive could not fit name");
2401 return kDNSServiceErr_Unknown
;
2404 ka
= malloc(sizeof(SleepKAContext
));
2405 if (!ka
) return kDNSServiceErr_NoMemory
;
2406 ka
->AppCallback
= callBack
;
2407 ka
->AppContext
= context
;
2409 err
= DNSServiceCreateConnection(sdRef
);
2412 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive cannot create connection");
2417 // we don't care about the "record". When sdRef gets deallocated later, it will be freed too
2418 err
= DNSServiceRegisterRecord(*sdRef
, &record
, kDNSServiceFlagsUnique
, 0, recname
,
2419 kDNSServiceType_NULL
, kDNSServiceClass_IN
, proxyreclen
, buf
, kDNSServiceInterfaceIndexAny
, SleepKeepaliveCallback
, ka
);
2422 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive cannot create connection");
2426 (*sdRef
)->kacontext
= ka
;
2427 return kDNSServiceErr_NoError
;