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.
28 Change History (most recent first):
30 $Log: dnssd_clientstub.c,v $
31 Revision 1.102 2008/02/25 19:16:19 cheshire
32 <rdar://problem/5708953> Problems with DNSServiceGetAddrInfo API
33 Was returning a bogus result (NULL pointer) when following a CNAME referral
35 Revision 1.101 2008/02/20 21:18:21 cheshire
36 <rdar://problem/5708953> DNSServiceGetAddrInfo doesn't set the scope ID of returned IPv6 link local addresses
38 Revision 1.100 2007/11/02 17:56:37 cheshire
39 <rdar://problem/5565787> Bonjour API broken for 64-bit apps (SCM_RIGHTS sendmsg fails)
40 Wrap hack code in "#if APPLE_OSX_mDNSResponder" since (as far as we know right now)
41 we don't want to do this on 64-bit Linux, Solaris, etc.
43 Revision 1.99 2007/11/02 17:29:40 cheshire
44 <rdar://problem/5565787> Bonjour API broken for 64-bit apps (SCM_RIGHTS sendmsg fails)
45 To get 64-bit code that works, we need to NOT use the standard CMSG_* macros
47 Revision 1.98 2007/11/01 19:52:43 cheshire
48 Wrap debugging messages in "#if DEBUG_64BIT_SCM_RIGHTS"
50 Revision 1.97 2007/11/01 19:45:55 cheshire
51 Added "DEBUG_64BIT_SCM_RIGHTS" debugging code
52 See <rdar://problem/5565787> Bonjour API broken for 64-bit apps (SCM_RIGHTS sendmsg fails)
54 Revision 1.96 2007/11/01 15:59:33 cheshire
55 umask not being set and restored properly in USE_NAMED_ERROR_RETURN_SOCKET code
56 (no longer used on OS X, but relevant for other platforms)
58 Revision 1.95 2007/10/31 20:07:16 cheshire
59 <rdar://problem/5541498> Set SO_NOSIGPIPE on client socket
60 Refinement: the cleanup code still needs to close listenfd when necesssary
62 Revision 1.94 2007/10/15 22:34:27 cheshire
63 <rdar://problem/5541498> Set SO_NOSIGPIPE on client socket
65 Revision 1.93 2007/10/10 00:48:54 cheshire
66 <rdar://problem/5526379> Daemon spins in an infinite loop when it doesn't get the control message it's expecting
68 Revision 1.92 2007/10/06 03:44:44 cheshire
69 Testing code for <rdar://problem/5526374> kqueue does not get a kevent to wake it up when a control message arrives on a socket
71 Revision 1.91 2007/10/04 20:53:59 cheshire
72 Improved debugging message when sendmsg fails
74 Revision 1.90 2007/09/30 00:09:27 cheshire
75 <rdar://problem/5492315> Pass socket fd via SCM_RIGHTS sendmsg instead of using named UDS in the filesystem
77 Revision 1.89 2007/09/19 23:53:12 cheshire
78 Fixed spelling mistake in comment
80 Revision 1.88 2007/09/07 23:18:27 cheshire
81 <rdar://problem/5467542> Change "client_context" to be an incrementing 64-bit counter
83 Revision 1.87 2007/09/07 22:50:09 cheshire
84 Added comment explaining moreptr field in DNSServiceOp structure
86 Revision 1.86 2007/09/07 20:21:22 cheshire
87 <rdar://problem/5462371> Make DNSSD library more resilient
88 Add more comments explaining the moreptr/morebytes logic; don't allow DNSServiceRefSockFD or
89 DNSServiceProcessResult for subordinate DNSServiceRefs created using kDNSServiceFlagsShareConnection
91 Revision 1.85 2007/09/06 21:43:23 cheshire
92 <rdar://problem/5462371> Make DNSSD library more resilient
93 Allow DNSServiceRefDeallocate from within DNSServiceProcessResult callback
95 Revision 1.84 2007/09/06 18:31:47 cheshire
96 <rdar://problem/5462371> Make DNSSD library more resilient against client programming errors
98 Revision 1.83 2007/08/28 20:45:45 cheshire
99 Typo: ctrl_path needs to be 64 bytes, not 44 bytes
101 Revision 1.82 2007/08/28 19:53:52 cheshire
102 <rdar://problem/5437423> Bonjour failures when /tmp is not writable (e.g. when booted from installer disc)
104 Revision 1.81 2007/07/27 00:03:20 cheshire
105 Fixed compiler warnings that showed up now we're building optimized ("-Os")
107 Revision 1.80 2007/07/23 22:12:53 cheshire
108 <rdar://problem/5352299> Make mDNSResponder more defensive against malicious local clients
110 Revision 1.79 2007/07/23 19:58:24 cheshire
111 <rdar://problem/5351640> Library: Leak in DNSServiceRefDeallocate
113 Revision 1.78 2007/07/12 20:42:27 cheshire
114 <rdar://problem/5280735> If daemon is killed, return kDNSServiceErr_ServiceNotRunning
115 to clients instead of kDNSServiceErr_Unknown
117 Revision 1.77 2007/07/02 23:07:13 cheshire
118 <rdar://problem/5308280> Reduce DNS-SD client syslog error messages
120 Revision 1.76 2007/06/22 20:12:18 cheshire
121 <rdar://problem/5277024> Leak in DNSServiceRefDeallocate
123 Revision 1.75 2007/05/23 18:59:22 cheshire
124 Remove unnecessary IPC_FLAGS_REUSE_SOCKET
126 Revision 1.74 2007/05/22 18:28:38 cheshire
127 Fixed compile errors in posix build
129 Revision 1.73 2007/05/22 01:20:47 cheshire
130 To determine current operation, need to check hdr->op, not sdr->op
132 Revision 1.72 2007/05/22 01:07:42 cheshire
133 <rdar://problem/3563675> API: Need a way to get version/feature information
135 Revision 1.71 2007/05/18 23:55:22 cheshire
136 <rdar://problem/4454655> Allow multiple register/browse/resolve operations to share single Unix Domain Socket
138 Revision 1.70 2007/05/17 20:58:22 cheshire
139 <rdar://problem/4647145> DNSServiceQueryRecord should return useful information with NXDOMAIN
141 Revision 1.69 2007/05/16 16:58:27 cheshire
142 <rdar://problem/4471320> Improve reliability of kDNSServiceFlagsMoreComing flag on multiprocessor machines
143 As long as select indicates that data is waiting, loop within DNSServiceProcessResult delivering additional results
145 Revision 1.68 2007/05/16 01:06:52 cheshire
146 <rdar://problem/4471320> Improve reliability of kDNSServiceFlagsMoreComing flag on multiprocessor machines
148 Revision 1.67 2007/05/15 21:57:16 cheshire
149 <rdar://problem/4608220> Use dnssd_SocketValid(x) macro instead of just
150 assuming that all negative values (or zero!) are invalid socket numbers
152 Revision 1.66 2007/03/27 22:23:04 cheshire
153 Add "dnssd_clientstub" prefix onto syslog messages
155 Revision 1.65 2007/03/21 22:25:23 cheshire
156 <rdar://problem/4172796> Remove client retry logic now that mDNSResponder uses launchd for its Unix Domain Socket
158 Revision 1.64 2007/03/21 19:01:56 cheshire
159 <rdar://problem/5078494> IPC code not 64-bit-savvy: assumes long=32bits, and short=16bits
161 Revision 1.63 2007/03/12 21:48:21 cheshire
162 <rdar://problem/5000162> Scary unlink errors in system.log
163 Code was using memory after it had been freed
165 Revision 1.62 2007/02/28 01:44:30 cheshire
166 <rdar://problem/5027863> Byte order bugs in uDNS.c, uds_daemon.c, dnssd_clientstub.c
168 Revision 1.61 2007/02/09 03:09:42 cheshire
169 <rdar://problem/3869251> Cleanup: Stop returning kDNSServiceErr_Unknown so often
170 <rdar://problem/4177924> API: Should return kDNSServiceErr_ServiceNotRunning
172 Revision 1.60 2007/02/08 20:33:44 cheshire
173 <rdar://problem/4985095> Leak on error path in DNSServiceProcessResult
175 Revision 1.59 2007/01/05 08:30:55 cheshire
176 Trim excessive "$Log" checkin history from before 2006
177 (checkin history still available via "cvs log ..." of course)
179 Revision 1.58 2006/10/27 00:38:22 cheshire
180 Strip accidental trailing whitespace from lines
182 Revision 1.57 2006/09/30 01:06:54 cheshire
183 Protocol field should be uint32_t
185 Revision 1.56 2006/09/27 00:44:16 herscher
186 <rdar://problem/4249761> API: Need DNSServiceGetAddrInfo()
188 Revision 1.55 2006/09/26 01:52:01 herscher
189 <rdar://problem/4245016> NAT Port Mapping API (for both NAT-PMP and UPnP Gateway Protocol)
191 Revision 1.54 2006/09/21 21:34:09 cheshire
192 <rdar://problem/4100000> Allow empty string name when using kDNSServiceFlagsNoAutoRename
194 Revision 1.53 2006/09/07 04:43:12 herscher
195 Fix compile error on Win32 platform by moving inclusion of syslog.h
197 Revision 1.52 2006/08/15 23:04:21 mkrochma
198 <rdar://problem/4090354> Client should be able to specify service name w/o callback
200 Revision 1.51 2006/07/24 23:45:55 cheshire
201 <rdar://problem/4605276> DNSServiceReconfirmRecord() should return error code
203 Revision 1.50 2006/06/28 08:22:27 cheshire
204 <rdar://problem/4605264> dnssd_clientstub.c needs to report unlink failures in syslog
206 Revision 1.49 2006/06/28 07:58:59 cheshire
207 Minor textual tidying
214 #include "dnssd_ipc.h"
218 #include <winsock2.h>
219 #include <ws2tcpip.h>
222 #define sockaddr_mdns sockaddr_in
223 #define AF_MDNS AF_INET
225 // Disable warning: "'type cast' : from data pointer 'void *' to function pointer"
226 #pragma warning(disable:4055)
228 // Disable warning: "nonstandard extension, function/data pointer conversion in expression"
229 #pragma warning(disable:4152)
231 extern BOOL
IsSystemServiceDisabled();
233 #define sleep(X) Sleep((X) * 1000)
235 static int g_initWinsock
= 0;
239 #include <sys/time.h>
240 #include <sys/socket.h>
243 #define sockaddr_mdns sockaddr_un
244 #define AF_MDNS AF_LOCAL
248 // <rdar://problem/4096913> Specifies how many times we'll try and connect to the server.
250 #define DNSSD_CLIENT_MAXTRIES 4
252 // Uncomment the line below to use the old error return mechanism of creating a temporary named socket (e.g. in /var/tmp)
253 //#define USE_NAMED_ERROR_RETURN_SOCKET 1
255 #ifndef CTL_PATH_PREFIX
256 #define CTL_PATH_PREFIX "/var/tmp/dnssd_result_socket."
262 DNSServiceFlags cb_flags
;
263 uint32_t cb_interface
;
264 DNSServiceErrorType cb_err
;
267 typedef struct _DNSServiceRef_t DNSServiceOp
;
268 typedef struct _DNSRecordRef_t DNSRecord
;
270 // client stub callback to process message from server and deliver results to client application
271 typedef void (*ProcessReplyFn
)(DNSServiceOp
*sdr
, CallbackHeader
*cbh
, char *msg
, char *end
);
273 #define ValidatorBits 0x12345678
274 #define DNSServiceRefValid(X) (dnssd_SocketValid((X)->sockfd) && (((X)->sockfd ^ (X)->validator) == ValidatorBits))
276 // When using kDNSServiceFlagsShareConnection, there is one primary _DNSServiceOp_t, and zero or more subordinates
277 // For the primary, the 'next' field points to the first subordinate, and its 'next' field points to the next, and so on.
278 // For the primary, the 'primary' field is NULL; for subordinates the 'primary' field points back to the associated primary
279 struct _DNSServiceRef_t
281 DNSServiceOp
*next
; // For shared connection
282 DNSServiceOp
*primary
; // For shared connection
283 dnssd_sock_t sockfd
; // Connected socket between client and daemon
284 dnssd_sock_t validator
; // Used to detect memory corruption, double disposals, etc.
285 client_context_t uid
; // For shared connection requests, each subordinate DNSServiceRef has its own ID,
286 // unique within the scope of the same shared parent DNSServiceRef
287 uint32_t op
; // request_op_t or reply_op_t
288 uint32_t max_index
; // Largest assigned record index - 0 if no additional records registered
289 uint32_t logcounter
; // Counter used to control number of syslog messages we write
290 int *moreptr
; // Set while DNSServiceProcessResult working on this particular DNSServiceRef
291 ProcessReplyFn ProcessReply
; // Function pointer to the code to handle received messages
292 void *AppCallback
; // Client callback function and context
296 struct _DNSRecordRef_t
299 DNSServiceRegisterRecordReply AppCallback
;
301 uint32_t record_index
; // index is unique to the ServiceDiscoveryRef
305 // Write len bytes. Return 0 on success, -1 on error
306 static int write_all(dnssd_sock_t sd
, char *buf
, int len
)
308 // Don't use "MSG_WAITALL"; it returns "Invalid argument" on some Linux versions; use an explicit while() loop instead.
309 //if (send(sd, buf, len, MSG_WAITALL) != len) return -1;
312 ssize_t num_written
= send(sd
, buf
, len
, 0);
313 if (num_written
< 0 || num_written
> len
)
315 // Should never happen. If it does, it indicates some OS bug,
316 // or that the mDNSResponder daemon crashed (which should never happen).
317 syslog(LOG_WARNING
, "dnssd_clientstub write_all(%d) failed %d/%d %d %s", sd
, num_written
, len
,
318 (num_written
< 0) ? errno
: 0,
319 (num_written
< 0) ? strerror(errno
) : "");
328 // Read len bytes. Return 0 on success, -1 on error
329 static int read_all(dnssd_sock_t sd
, char *buf
, int len
)
331 // Don't use "MSG_WAITALL"; it returns "Invalid argument" on some Linux versions; use an explicit while() loop instead.
332 //if (recv(sd, buf, len, MSG_WAITALL) != len) return -1;
336 ssize_t num_read
= recv(sd
, buf
, len
, 0);
337 if ((num_read
== 0) || (num_read
< 0) || (num_read
> len
))
339 // Should never happen. If it does, it indicates some OS bug,
340 // or that the mDNSResponder daemon crashed (which should never happen).
341 syslog(LOG_WARNING
, "dnssd_clientstub read_all(%d) failed %d/%d %d %s", sd
, num_read
, len
,
342 (num_read
< 0) ? errno
: 0,
343 (num_read
< 0) ? strerror(errno
) : "");
352 // Returns 1 if more bytes remain to be read on socket descriptor sd, 0 otherwise
353 static int more_bytes(dnssd_sock_t sd
)
355 struct timeval tv
= { 0, 0 };
358 FD_SET(sd
, &readfds
);
359 return(select(sd
+1, &readfds
, (fd_set
*)NULL
, (fd_set
*)NULL
, &tv
) > 0);
364 * allocate and initialize an ipc message header. Value of len should initially be the
365 * length of the data, and is set to the value of the data plus the header. data_start
366 * is set to point to the beginning of the data section. SeparateReturnSocket should be
367 * non-zero for calls that can't receive an immediate error return value on their primary
368 * socket, and therefore require a separate return path for the error code result.
369 * if zero, the path to a control socket is appended at the beginning of the message buffer.
370 * data_start is set past this string.
372 static ipc_msg_hdr
*create_hdr(uint32_t op
, size_t *len
, char **data_start
, int SeparateReturnSocket
, DNSServiceOp
*ref
)
377 #if !defined(USE_TCP_LOOPBACK)
378 char ctrl_path
[64] = ""; // "/var/tmp/dnssd_result_socket.xxxxxxxxxx-xxx-xxxxxx"
381 if (SeparateReturnSocket
)
383 #if defined(USE_TCP_LOOPBACK)
384 *len
+= 2; // Allocate space for two-byte port number
385 #elif defined(USE_NAMED_ERROR_RETURN_SOCKET)
387 if (gettimeofday(&time
, NULL
) < 0)
388 { syslog(LOG_WARNING
, "dnssd_clientstub create_hdr: gettimeofday failed %d %s", errno
, strerror(errno
)); return NULL
; }
389 sprintf(ctrl_path
, "%s%d-%.3lx-%.6lu", CTL_PATH_PREFIX
, (int)getpid(),
390 (unsigned long)(time
.tv_sec
& 0xFFF), (unsigned long)(time
.tv_usec
));
391 *len
+= strlen(ctrl_path
) + 1;
393 *len
+= 1; // Allocate space for single zero byte (empty C string)
397 datalen
= (int) *len
;
398 *len
+= sizeof(ipc_msg_hdr
);
400 // Write message to buffer
402 if (!msg
) { syslog(LOG_WARNING
, "dnssd_clientstub create_hdr: malloc failed"); return NULL
; }
405 hdr
= (ipc_msg_hdr
*)msg
;
406 hdr
->version
= VERSION
;
407 hdr
->datalen
= datalen
;
410 hdr
->client_context
= ref
->uid
;
412 *data_start
= msg
+ sizeof(ipc_msg_hdr
);
413 #if defined(USE_TCP_LOOPBACK)
414 // Put dummy data in for the port, since we don't know what it is yet.
415 // The data will get filled in before we send the message. This happens in deliver_request().
416 if (SeparateReturnSocket
) put_uint16(0, data_start
);
418 if (SeparateReturnSocket
) put_string(ctrl_path
, data_start
);
423 static void FreeDNSServiceOp(DNSServiceOp
*x
)
425 // We don't use our DNSServiceRefValid macro here because if we're cleaning up after a socket() call failed
426 // then sockfd could legitimately contain a failing value (e.g. dnssd_InvalidSocket)
427 if ((x
->sockfd
^ x
->validator
) != ValidatorBits
)
428 syslog(LOG_WARNING
, "dnssd_clientstub attempt to dispose invalid DNSServiceRef %p %08X %08X", x
, x
->sockfd
, x
->validator
);
433 x
->sockfd
= dnssd_InvalidSocket
;
434 x
->validator
= 0xDDDDDDDD;
435 x
->op
= request_op_none
;
439 x
->ProcessReply
= NULL
;
440 x
->AppCallback
= NULL
;
441 x
->AppContext
= NULL
;
446 // Return a connected service ref (deallocate with DNSServiceRefDeallocate)
447 static DNSServiceErrorType
ConnectToServer(DNSServiceRef
*ref
, DNSServiceFlags flags
, uint32_t op
, ProcessReplyFn ProcessReply
, void *AppCallback
, void *AppContext
)
449 #if APPLE_OSX_mDNSResponder
450 int NumTries
= DNSSD_CLIENT_MAXTRIES
;
455 dnssd_sockaddr_t saddr
;
458 if (!ref
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSService operation with NULL DNSServiceRef"); return kDNSServiceErr_BadParam
; }
460 if (flags
& kDNSServiceFlagsShareConnection
)
464 syslog(LOG_WARNING
, "dnssd_clientstub kDNSServiceFlagsShareConnection used with NULL DNSServiceRef");
465 return kDNSServiceErr_BadParam
;
467 if (!DNSServiceRefValid(*ref
))
469 syslog(LOG_WARNING
, "dnssd_clientstub kDNSServiceFlagsShareConnection used with invalid DNSServiceRef %p %08X %08X",
470 (*ref
), (*ref
)->sockfd
, (*ref
)->validator
);
472 return kDNSServiceErr_BadReference
;
481 if (WSAStartup(MAKEWORD(2,2), &wsaData
) != 0) { *ref
= NULL
; return kDNSServiceErr_ServiceNotRunning
; }
483 // <rdar://problem/4096913> If the system service is disabled, we only want to try to connect once
484 if (IsSystemServiceDisabled()) NumTries
= DNSSD_CLIENT_MAXTRIES
;
487 sdr
= malloc(sizeof(DNSServiceOp
));
488 if (!sdr
) { syslog(LOG_WARNING
, "dnssd_clientstub ConnectToServer: malloc failed"); *ref
= NULL
; 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 (flags
& kDNSServiceFlagsShareConnection
)
505 DNSServiceOp
**p
= &(*ref
)->next
; // Append ourselves to end of primary's list
506 while (*p
) p
= &(*p
)->next
;
508 sdr
->primary
= *ref
; // Set our primary pointer
509 sdr
->sockfd
= (*ref
)->sockfd
; // Inherit primary's socket
510 sdr
->validator
= (*ref
)->validator
;
511 sdr
->uid
= (*ref
)->uid
;
512 if (++(*ref
)->uid
.u32
[0] == 0) ++(*ref
)->uid
.u32
[1]; // In parent DNSServiceOp increment UID counter
513 //printf("ConnectToServer sharing socket %d\n", sdr->sockfd);
518 const unsigned long optval
= 1;
521 sdr
->sockfd
= socket(AF_DNSSD
, SOCK_STREAM
, 0);
522 sdr
->validator
= sdr
->sockfd
^ ValidatorBits
;
523 if (!dnssd_SocketValid(sdr
->sockfd
))
525 syslog(LOG_WARNING
, "dnssd_clientstub ConnectToServer: socket failed %d %s", errno
, strerror(errno
));
526 FreeDNSServiceOp(sdr
);
527 return kDNSServiceErr_NoMemory
;
530 // Some environments (e.g. OS X) support turning off SIGPIPE for a socket
531 if (setsockopt(sdr
->sockfd
, SOL_SOCKET
, SO_NOSIGPIPE
, &optval
, sizeof(optval
)) < 0)
532 syslog(LOG_WARNING
, "dnssd_clientstub ConnectToServer: SO_NOSIGPIPE failed %d %s", errno
, strerror(errno
));
534 #if defined(USE_TCP_LOOPBACK)
535 saddr
.sin_family
= AF_INET
;
536 saddr
.sin_addr
.s_addr
= inet_addr(MDNS_TCP_SERVERADDR
);
537 saddr
.sin_port
= htons(MDNS_TCP_SERVERPORT
);
539 saddr
.sun_family
= AF_LOCAL
;
540 strcpy(saddr
.sun_path
, MDNS_UDS_SERVERPATH
);
545 int err
= connect(sdr
->sockfd
, (struct sockaddr
*) &saddr
, sizeof(saddr
));
546 if (!err
) break; // If we succeeded, return sdr
547 // If we failed, then it may be because the daemon is still launching.
548 // This can happen for processes that launch early in the boot process, while the
549 // daemon is still coming up. Rather than fail here, we'll wait a bit and try again.
550 // If, after four seconds, we still can't connect to the daemon,
551 // then we give up and return a failure code.
552 if (++NumTries
< DNSSD_CLIENT_MAXTRIES
) sleep(1); // Sleep a bit, then try again
553 else { dnssd_close(sdr
->sockfd
); FreeDNSServiceOp(sdr
); return kDNSServiceErr_ServiceNotRunning
; }
555 //printf("ConnectToServer opened socket %d\n", sdr->sockfd);
559 return kDNSServiceErr_NoError
;
562 static DNSServiceErrorType
deliver_request(ipc_msg_hdr
*hdr
, DNSServiceOp
*sdr
)
564 uint32_t datalen
= hdr
->datalen
; // We take a copy here because we're going to convert hdr->datalen to network byte order
565 #if defined(USE_TCP_LOOPBACK) || defined(USE_NAMED_ERROR_RETURN_SOCKET)
566 char *const data
= (char *)hdr
+ sizeof(ipc_msg_hdr
);
568 dnssd_sock_t listenfd
= dnssd_InvalidSocket
, errsd
= dnssd_InvalidSocket
;
569 DNSServiceErrorType err
;
570 int MakeSeparateReturnSocket
= 0;
572 // Note: need to check hdr->op, not sdr->op.
573 // hdr->op contains the code for the specific operation we're currently doing, whereas sdr->op
574 // contains the original parent DNSServiceOp (e.g. for an add_record_request, hdr->op will be
575 // add_record_request but the parent sdr->op will be connection_request or reg_service_request)
577 hdr
->op
== reg_record_request
|| hdr
->op
== add_record_request
|| hdr
->op
== update_record_request
|| hdr
->op
== remove_record_request
)
578 MakeSeparateReturnSocket
= 1;
580 if (!DNSServiceRefValid(sdr
))
582 syslog(LOG_WARNING
, "dnssd_clientstub deliver_request: invalid DNSServiceRef %p %08X %08X", sdr
, sdr
->sockfd
, sdr
->validator
);
583 return kDNSServiceErr_BadReference
;
586 if (!hdr
) { syslog(LOG_WARNING
, "dnssd_clientstub deliver_request: !hdr"); return kDNSServiceErr_Unknown
; }
588 if (MakeSeparateReturnSocket
)
590 #if defined(USE_TCP_LOOPBACK)
592 union { uint16_t s
; u_char b
[2]; } port
;
593 dnssd_sockaddr_t caddr
;
594 dnssd_socklen_t len
= (dnssd_socklen_t
) sizeof(caddr
);
595 listenfd
= socket(AF_DNSSD
, SOCK_STREAM
, 0);
596 if (!dnssd_SocketValid(listenfd
)) goto cleanup
;
598 caddr
.sin_family
= AF_INET
;
600 caddr
.sin_addr
.s_addr
= inet_addr(MDNS_TCP_SERVERADDR
);
601 if (bind(listenfd
, (struct sockaddr
*) &caddr
, sizeof(caddr
)) < 0) goto cleanup
;
602 if (getsockname(listenfd
, (struct sockaddr
*) &caddr
, &len
) < 0) goto cleanup
;
604 port
.s
= caddr
.sin_port
;
605 data
[0] = port
.b
[0]; // don't switch the byte order, as the
606 data
[1] = port
.b
[1]; // daemon expects it in network byte order
608 #elif defined(USE_NAMED_ERROR_RETURN_SOCKET)
612 dnssd_sockaddr_t caddr
;
613 listenfd
= socket(AF_DNSSD
, SOCK_STREAM
, 0);
614 if (!dnssd_SocketValid(listenfd
)) goto cleanup
;
616 caddr
.sun_family
= AF_LOCAL
;
617 // According to Stevens (section 3.2), there is no portable way to
618 // determine whether sa_len is defined on a particular platform.
619 #ifndef NOT_HAVE_SA_LEN
620 caddr
.sun_len
= sizeof(struct sockaddr_un
);
622 strcpy(caddr
.sun_path
, data
);
624 bindresult
= bind(listenfd
, (struct sockaddr
*)&caddr
, sizeof(caddr
));
626 if (bindresult
< 0) goto cleanup
;
633 // syslog(LOG_WARNING, "dnssd_clientstub ERROR: pipe() failed errno %d (%s)", errno, strerror(errno));
634 if (socketpair(AF_DNSSD
, SOCK_STREAM
, 0, sp
) < 0)
635 syslog(LOG_WARNING
, "dnssd_clientstub ERROR: socketpair() failed errno %d (%s)", errno
, strerror(errno
));
638 errsd
= sp
[0]; // We'll read our four-byte error code from sp[0]
639 listenfd
= sp
[1]; // We'll send sp[1] to the daemon
645 #if !defined(USE_TCP_LOOPBACK) && !defined(USE_NAMED_ERROR_RETURN_SOCKET)
646 // If we're going to make a separate error return socket, and pass it to the daemon
647 // using sendmsg, then we'll hold back one data byte to go with it.
648 // On some versions of Unix (including Leopard) sending a control message without
649 // any associated data does not work reliably -- e.g. one particular issue we ran
650 // into is that if the receiving program is in a kqueue loop waiting to be notified
651 // of the received message, it doesn't get woken up when the control message arrives.
652 if (MakeSeparateReturnSocket
) datalen
--;
655 // At this point, our listening socket is set up and waiting, if necessary, for the daemon to connect back to
656 ConvertHeaderBytes(hdr
);
657 //syslog(LOG_WARNING, "dnssd_clientstub deliver_request writing %ld bytes", datalen + sizeof(ipc_msg_hdr));
658 //if (MakeSeparateReturnSocket) syslog(LOG_WARNING, "dnssd_clientstub deliver_request name is %s", data);
659 #if TEST_SENDING_ONE_BYTE_AT_A_TIME
661 for (i
=0; i
<datalen
+ sizeof(ipc_msg_hdr
); i
++)
663 syslog(LOG_WARNING
, "dnssd_clientstub writing %d", i
);
664 if (write_all(sdr
->sockfd
, ((char *)hdr
)+i
, 1) < 0) goto cleanup
;
668 if (write_all(sdr
->sockfd
, (char *)hdr
, datalen
+ sizeof(ipc_msg_hdr
)) < 0) goto cleanup
;
671 if (!MakeSeparateReturnSocket
) errsd
= sdr
->sockfd
;
674 #if defined(USE_TCP_LOOPBACK) || defined(USE_NAMED_ERROR_RETURN_SOCKET)
675 // At this point we may block in accept for a few milliseconds waiting for the daemon to connect back to us,
676 // but that's okay -- the daemon is a trusted service and we know if won't take more than a few milliseconds to respond.
677 dnssd_sockaddr_t daddr
;
678 dnssd_socklen_t len
= sizeof(daddr
);
679 errsd
= accept(listenfd
, (struct sockaddr
*)&daddr
, &len
);
680 if (!dnssd_SocketValid(errsd
)) goto cleanup
;
683 #if APPLE_OSX_mDNSResponder
684 // On Leopard, the stock definitions of the CMSG_* macros in /usr/include/sys/socket.h,
685 // while arguably correct in theory, nonetheless in practice produce code that doesn't work on 64-bit machines
686 // For details see <rdar://problem/5565787> Bonjour API broken for 64-bit apps (SCM_RIGHTS sendmsg fails)
688 #define CMSG_DATA(cmsg) ((unsigned char *)(cmsg) + (sizeof(struct cmsghdr)))
690 #define CMSG_SPACE(l) ((sizeof(struct cmsghdr)) + (l))
692 #define CMSG_LEN(l) ((sizeof(struct cmsghdr)) + (l))
695 struct iovec vec
= { ((char *)hdr
) + sizeof(ipc_msg_hdr
) + datalen
, 1 }; // Send the last byte along with the SCM_RIGHTS
697 struct cmsghdr
*cmsg
;
698 char cbuf
[CMSG_SPACE(sizeof(dnssd_sock_t
))];
703 msg
.msg_control
= cbuf
;
704 msg
.msg_controllen
= CMSG_LEN(sizeof(dnssd_sock_t
));
706 cmsg
= CMSG_FIRSTHDR(&msg
);
707 cmsg
->cmsg_len
= CMSG_LEN(sizeof(dnssd_sock_t
));
708 cmsg
->cmsg_level
= SOL_SOCKET
;
709 cmsg
->cmsg_type
= SCM_RIGHTS
;
710 *((dnssd_sock_t
*)CMSG_DATA(cmsg
)) = listenfd
;
712 #if TEST_KQUEUE_CONTROL_MESSAGE_BUG
716 #if DEBUG_64BIT_SCM_RIGHTS
717 syslog(LOG_WARNING
, "dnssd_clientstub sendmsg read sd=%d write sd=%d %ld %ld %ld/%ld/%ld/%ld",
718 errsd
, listenfd
, sizeof(dnssd_sock_t
), sizeof(void*),
719 sizeof(struct cmsghdr
) + sizeof(dnssd_sock_t
),
720 CMSG_LEN(sizeof(dnssd_sock_t
)), (long)CMSG_SPACE(sizeof(dnssd_sock_t
)),
721 (long)((char*)CMSG_DATA(cmsg
) + 4 - cbuf
));
722 #endif DEBUG_64BIT_SCM_RIGHTS
724 if (sendmsg(sdr
->sockfd
, &msg
, 0) < 0)
726 syslog(LOG_WARNING
, "dnssd_clientstub ERROR: sendmsg failed read sd=%d write sd=%d errno %d (%s)",
727 errsd
, listenfd
, errno
, strerror(errno
));
728 err
= kDNSServiceErr_Incompatible
;
732 #if DEBUG_64BIT_SCM_RIGHTS
733 syslog(LOG_WARNING
, "dnssd_clientstub sendmsg read sd=%d write sd=%d okay", errsd
, listenfd
);
734 #endif DEBUG_64BIT_SCM_RIGHTS
737 // Close our end of the socketpair *before* blocking in read_all to get the four-byte error code.
738 // Otherwise, if the daemon closes our socket (or crashes), we block in read_all() forever
739 // because the socket is not closed (we still have an open reference to it ourselves).
740 dnssd_close(listenfd
);
741 listenfd
= dnssd_InvalidSocket
; // Make sure we don't close it a second time in the cleanup handling below
744 // At this point we may block in read_all for a few milliseconds waiting for the daemon to send us the error code,
745 // but that's okay -- the daemon is a trusted service and we know if won't take more than a few milliseconds to respond.
746 if (read_all(errsd
, (char*)&err
, (int)sizeof(err
)) < 0)
747 err
= kDNSServiceErr_ServiceNotRunning
; // On failure read_all will have written a message to syslog for us
751 //syslog(LOG_WARNING, "dnssd_clientstub deliver_request: retrieved error code %d", err);
754 if (MakeSeparateReturnSocket
)
756 if (dnssd_SocketValid(listenfd
)) dnssd_close(listenfd
);
757 if (dnssd_SocketValid(errsd
)) dnssd_close(errsd
);
758 #if defined(USE_NAMED_ERROR_RETURN_SOCKET)
759 // syslog(LOG_WARNING, "dnssd_clientstub deliver_request: removing UDS: %s", data);
760 if (unlink(data
) != 0)
761 syslog(LOG_WARNING
, "dnssd_clientstub WARNING: unlink(\"%s\") failed errno %d (%s)", data
, errno
, strerror(errno
));
762 // else syslog(LOG_WARNING, "dnssd_clientstub deliver_request: removed UDS: %s", data);
769 int DNSSD_API
DNSServiceRefSockFD(DNSServiceRef sdRef
)
771 if (!sdRef
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRefSockFD called with NULL DNSServiceRef"); return dnssd_InvalidSocket
; }
773 if (!DNSServiceRefValid(sdRef
))
775 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRefSockFD called with invalid DNSServiceRef %p %08X %08X",
776 sdRef
, sdRef
->sockfd
, sdRef
->validator
);
777 return dnssd_InvalidSocket
;
782 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRefSockFD undefined for kDNSServiceFlagsShareConnection subordinate DNSServiceRef %p", sdRef
);
783 return dnssd_InvalidSocket
;
786 return (int) sdRef
->sockfd
;
789 // Handle reply from server, calling application client callback. If there is no reply
790 // from the daemon on the socket contained in sdRef, the call will block.
791 DNSServiceErrorType DNSSD_API
DNSServiceProcessResult(DNSServiceRef sdRef
)
795 if (!sdRef
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceProcessResult called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam
; }
797 if (!DNSServiceRefValid(sdRef
))
799 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceProcessResult called with invalid DNSServiceRef %p %08X %08X", sdRef
, sdRef
->sockfd
, sdRef
->validator
);
800 return kDNSServiceErr_BadReference
;
805 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceProcessResult undefined for kDNSServiceFlagsShareConnection subordinate DNSServiceRef %p", sdRef
);
806 return kDNSServiceErr_BadReference
;
809 if (!sdRef
->ProcessReply
)
811 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceProcessResult called with DNSServiceRef with no ProcessReply function");
812 return kDNSServiceErr_BadReference
;
820 // return NoError on EWOULDBLOCK. This will handle the case
821 // where a non-blocking socket is told there is data, but it was a false positive.
822 // On error, read_all will write a message to syslog for us, so don't need to duplicate that here
823 if (read_all(sdRef
->sockfd
, (void *)&cbh
.ipc_hdr
, sizeof(cbh
.ipc_hdr
)) < 0)
825 if (dnssd_errno() != dnssd_EWOULDBLOCK
)
827 sdRef
->ProcessReply
= NULL
;
828 return kDNSServiceErr_ServiceNotRunning
;
832 if (morebytes
&& sdRef
->logcounter
< 100)
835 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceProcessResult error: select indicated data was waiting but read_all returned EWOULDBLOCK");
837 return kDNSServiceErr_NoError
;
841 ConvertHeaderBytes(&cbh
.ipc_hdr
);
842 if (cbh
.ipc_hdr
.version
!= VERSION
)
844 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceProcessResult daemon version %d does not match client version %d", cbh
.ipc_hdr
.version
, VERSION
);
845 sdRef
->ProcessReply
= NULL
;
846 return kDNSServiceErr_Incompatible
;
849 data
= malloc(cbh
.ipc_hdr
.datalen
);
850 if (!data
) return kDNSServiceErr_NoMemory
;
851 if (read_all(sdRef
->sockfd
, data
, cbh
.ipc_hdr
.datalen
) < 0) // On error, read_all will write a message to syslog for us
854 sdRef
->ProcessReply
= NULL
;
855 return kDNSServiceErr_ServiceNotRunning
;
860 cbh
.cb_flags
= get_flags (&ptr
, data
+ cbh
.ipc_hdr
.datalen
);
861 cbh
.cb_interface
= get_uint32 (&ptr
, data
+ cbh
.ipc_hdr
.datalen
);
862 cbh
.cb_err
= get_error_code(&ptr
, data
+ cbh
.ipc_hdr
.datalen
);
864 // CAUTION: We have to handle the case where the client calls DNSServiceRefDeallocate from within the callback function.
865 // To do this we set moreptr to point to morebytes. If the client does call DNSServiceRefDeallocate(),
866 // then that routine will clear morebytes for us, and cause us to exit our loop.
867 morebytes
= more_bytes(sdRef
->sockfd
);
870 cbh
.cb_flags
|= kDNSServiceFlagsMoreComing
;
871 sdRef
->moreptr
= &morebytes
;
873 if (ptr
) sdRef
->ProcessReply(sdRef
, &cbh
, ptr
, data
+ cbh
.ipc_hdr
.datalen
);
874 // Careful code here:
875 // If morebytes is non-zero, that means we set sdRef->moreptr above, and the operation was not
876 // cancelled out from under us, so now we need to clear sdRef->moreptr so we don't leave a stray
877 // dangling pointer pointing to a long-gone stack variable.
878 // If morebytes is zero, then one of two thing happened:
879 // (a) morebytes was 0 above, so we didn't set sdRef->moreptr, so we don't need to clear it
880 // (b) morebytes was 1 above, and we set sdRef->moreptr, but the operation was cancelled (with DNSServiceRefDeallocate()),
881 // so we MUST NOT try to dereference our stale sdRef pointer.
882 if (morebytes
) sdRef
->moreptr
= NULL
;
887 return kDNSServiceErr_NoError
;
890 void DNSSD_API
DNSServiceRefDeallocate(DNSServiceRef sdRef
)
892 if (!sdRef
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRefDeallocate called with NULL DNSServiceRef"); return; }
894 if (!DNSServiceRefValid(sdRef
)) // Also verifies dnssd_SocketValid(sdRef->sockfd) for us too
896 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRefDeallocate called with invalid DNSServiceRef %p %08X %08X", sdRef
, sdRef
->sockfd
, sdRef
->validator
);
900 // 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
901 if (sdRef
->moreptr
) *(sdRef
->moreptr
) = 0;
903 if (sdRef
->primary
) // If this is a subordinate DNSServiceOp, just send a 'stop' command
905 DNSServiceOp
**p
= &sdRef
->primary
->next
;
906 while (*p
&& *p
!= sdRef
) p
= &(*p
)->next
;
911 ipc_msg_hdr
*hdr
= create_hdr(cancel_request
, &len
, &ptr
, 0, sdRef
);
912 ConvertHeaderBytes(hdr
);
913 write_all(sdRef
->sockfd
, (char *)hdr
, len
);
916 FreeDNSServiceOp(sdRef
);
919 else // else, make sure to terminate all subordinates as well
921 dnssd_close(sdRef
->sockfd
);
924 DNSServiceOp
*p
= sdRef
;
931 DNSServiceErrorType DNSSD_API
DNSServiceGetProperty(const char *property
, void *result
, uint32_t *size
)
934 size_t len
= strlen(property
) + 1;
939 DNSServiceErrorType err
= ConnectToServer(&tmp
, 0, getproperty_request
, NULL
, NULL
, NULL
);
942 hdr
= create_hdr(getproperty_request
, &len
, &ptr
, 0, tmp
);
943 if (!hdr
) { DNSServiceRefDeallocate(tmp
); return kDNSServiceErr_NoMemory
; }
945 put_string(property
, &ptr
);
946 err
= deliver_request(hdr
, tmp
); // Will free hdr for us
947 if (read_all(tmp
->sockfd
, (char*)&actualsize
, (int)sizeof(actualsize
)) < 0)
948 { DNSServiceRefDeallocate(tmp
); return kDNSServiceErr_ServiceNotRunning
; }
950 actualsize
= ntohl(actualsize
);
951 if (read_all(tmp
->sockfd
, (char*)result
, actualsize
< *size
? actualsize
: *size
) < 0)
952 { DNSServiceRefDeallocate(tmp
); return kDNSServiceErr_ServiceNotRunning
; }
953 DNSServiceRefDeallocate(tmp
);
955 // Swap version result back to local process byte order
956 if (!strcmp(property
, kDNSServiceProperty_DaemonVersion
) && *size
>= 4)
957 *(uint32_t*)result
= ntohl(*(uint32_t*)result
);
960 return kDNSServiceErr_NoError
;
963 static void handle_resolve_response(DNSServiceOp
*sdr
, CallbackHeader
*cbh
, char *data
, char *end
)
965 char fullname
[kDNSServiceMaxDomainName
];
966 char target
[kDNSServiceMaxDomainName
];
968 union { uint16_t s
; u_char b
[2]; } port
;
969 unsigned char *txtrecord
;
971 get_string(&data
, end
, fullname
, kDNSServiceMaxDomainName
);
972 get_string(&data
, end
, target
, kDNSServiceMaxDomainName
);
973 if (data
+ 2 > end
) data
= NULL
;
979 txtlen
= get_uint16(&data
, end
);
980 txtrecord
= (unsigned char *)get_rdata(&data
, end
, txtlen
);
982 if (!data
) syslog(LOG_WARNING
, "dnssd_clientstub handle_resolve_response: error reading result from daemon");
983 else ((DNSServiceResolveReply
)sdr
->AppCallback
)(sdr
, cbh
->cb_flags
, cbh
->cb_interface
, cbh
->cb_err
, fullname
, target
, port
.s
, txtlen
, txtrecord
, sdr
->AppContext
);
984 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
987 DNSServiceErrorType DNSSD_API DNSServiceResolve
989 DNSServiceRef
*sdRef
,
990 DNSServiceFlags flags
,
991 uint32_t interfaceIndex
,
995 DNSServiceResolveReply callBack
,
1002 DNSServiceErrorType err
;
1004 if (!name
|| !regtype
|| !domain
|| !callBack
) return kDNSServiceErr_BadParam
;
1006 err
= ConnectToServer(sdRef
, flags
, resolve_request
, handle_resolve_response
, callBack
, context
);
1007 if (err
) return err
; // On error ConnectToServer leaves *sdRef set to NULL
1009 // Calculate total message length
1010 len
= sizeof(flags
);
1011 len
+= sizeof(interfaceIndex
);
1012 len
+= strlen(name
) + 1;
1013 len
+= strlen(regtype
) + 1;
1014 len
+= strlen(domain
) + 1;
1016 hdr
= create_hdr(resolve_request
, &len
, &ptr
, (*sdRef
)->primary
? 1 : 0, *sdRef
);
1017 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
1019 put_flags(flags
, &ptr
);
1020 put_uint32(interfaceIndex
, &ptr
);
1021 put_string(name
, &ptr
);
1022 put_string(regtype
, &ptr
);
1023 put_string(domain
, &ptr
);
1025 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1026 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
1030 static void handle_query_response(DNSServiceOp
*sdr
, CallbackHeader
*cbh
, char *data
, char *end
)
1033 char name
[kDNSServiceMaxDomainName
];
1034 uint16_t rrtype
, rrclass
, rdlen
;
1037 get_string(&data
, end
, name
, kDNSServiceMaxDomainName
);
1038 rrtype
= get_uint16(&data
, end
);
1039 rrclass
= get_uint16(&data
, end
);
1040 rdlen
= get_uint16(&data
, end
);
1041 rdata
= get_rdata(&data
, end
, rdlen
);
1042 ttl
= get_uint32(&data
, end
);
1044 if (!data
) syslog(LOG_WARNING
, "dnssd_clientstub handle_query_response: error reading result from daemon");
1045 else ((DNSServiceQueryRecordReply
)sdr
->AppCallback
)(sdr
, cbh
->cb_flags
, cbh
->cb_interface
, cbh
->cb_err
, name
, rrtype
, rrclass
, rdlen
, rdata
, ttl
, sdr
->AppContext
);
1046 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1049 DNSServiceErrorType DNSSD_API DNSServiceQueryRecord
1051 DNSServiceRef
*sdRef
,
1052 DNSServiceFlags flags
,
1053 uint32_t interfaceIndex
,
1057 DNSServiceQueryRecordReply callBack
,
1064 DNSServiceErrorType err
= ConnectToServer(sdRef
, flags
, query_request
, handle_query_response
, callBack
, context
);
1065 if (err
) return err
; // On error ConnectToServer leaves *sdRef set to NULL
1067 if (!name
) name
= "\0";
1069 // Calculate total message length
1070 len
= sizeof(flags
);
1071 len
+= sizeof(uint32_t); // interfaceIndex
1072 len
+= strlen(name
) + 1;
1073 len
+= 2 * sizeof(uint16_t); // rrtype, rrclass
1075 hdr
= create_hdr(query_request
, &len
, &ptr
, (*sdRef
)->primary
? 1 : 0, *sdRef
);
1076 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
1078 put_flags(flags
, &ptr
);
1079 put_uint32(interfaceIndex
, &ptr
);
1080 put_string(name
, &ptr
);
1081 put_uint16(rrtype
, &ptr
);
1082 put_uint16(rrclass
, &ptr
);
1084 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1085 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
1089 static void handle_addrinfo_response(DNSServiceOp
*sdr
, CallbackHeader
*cbh
, char *data
, char *end
)
1091 char hostname
[kDNSServiceMaxDomainName
];
1092 uint16_t rrtype
, rrclass
, rdlen
;
1096 get_string(&data
, end
, hostname
, kDNSServiceMaxDomainName
);
1097 rrtype
= get_uint16(&data
, end
);
1098 rrclass
= get_uint16(&data
, end
);
1099 rdlen
= get_uint16(&data
, end
);
1100 rdata
= get_rdata (&data
, end
, rdlen
);
1101 ttl
= get_uint32(&data
, end
);
1103 // We only generate client callbacks for A and AAAA results (including NXDOMAIN results for
1104 // those types, if the client has requested those with the kDNSServiceFlagsReturnIntermediates).
1105 // Other result types, specifically CNAME referrals, are not communicated to the client, because
1106 // the DNSServiceGetAddrInfoReply interface doesn't have any meaningful way to communiate CNAME referrals.
1107 if (!data
) syslog(LOG_WARNING
, "dnssd_clientstub handle_addrinfo_response: error reading result from daemon");
1108 else if (rrtype
== kDNSServiceType_A
|| rrtype
== kDNSServiceType_AAAA
)
1110 struct sockaddr_in sa4
;
1111 struct sockaddr_in6 sa6
;
1112 const struct sockaddr
*const sa
= (rrtype
== kDNSServiceType_A
) ? (struct sockaddr
*)&sa4
: (struct sockaddr
*)&sa6
;
1113 if (rrtype
== kDNSServiceType_A
)
1115 bzero(&sa4
, sizeof(sa4
));
1116 #ifndef NOT_HAVE_SA_LEN
1117 sa4
.sin_len
= sizeof(struct sockaddr_in
);
1119 sa4
.sin_family
= AF_INET
;
1121 if (!cbh
->cb_err
) memcpy(&sa4
.sin_addr
, rdata
, rdlen
);
1125 bzero(&sa6
, sizeof(sa6
));
1126 #ifndef NOT_HAVE_SA_LEN
1127 sa6
.sin6_len
= sizeof(struct sockaddr_in6
);
1129 sa6
.sin6_family
= AF_INET6
;
1131 // sin6_flowinfo = 0;
1132 // sin6_scope_id = 0;
1135 memcpy(&sa6
.sin6_addr
, rdata
, rdlen
);
1136 if (IN6_IS_ADDR_LINKLOCAL(&sa6
.sin6_addr
)) sa6
.sin6_scope_id
= cbh
->cb_interface
;
1139 ((DNSServiceGetAddrInfoReply
)sdr
->AppCallback
)(sdr
, cbh
->cb_flags
, cbh
->cb_interface
, cbh
->cb_err
, hostname
, sa
, ttl
, sdr
->AppContext
);
1140 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1144 DNSServiceErrorType DNSSD_API DNSServiceGetAddrInfo
1146 DNSServiceRef
*sdRef
,
1147 DNSServiceFlags flags
,
1148 uint32_t interfaceIndex
,
1150 const char *hostname
,
1151 DNSServiceGetAddrInfoReply callBack
,
1152 void *context
/* may be NULL */
1158 DNSServiceErrorType err
;
1160 if (!hostname
) return kDNSServiceErr_BadParam
;
1162 err
= ConnectToServer(sdRef
, flags
, addrinfo_request
, handle_addrinfo_response
, callBack
, context
);
1163 if (err
) return err
; // On error ConnectToServer leaves *sdRef set to NULL
1165 // Calculate total message length
1166 len
= sizeof(flags
);
1167 len
+= sizeof(uint32_t); // interfaceIndex
1168 len
+= sizeof(uint32_t); // protocol
1169 len
+= strlen(hostname
) + 1;
1171 hdr
= create_hdr(addrinfo_request
, &len
, &ptr
, (*sdRef
)->primary
? 1 : 0, *sdRef
);
1172 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
1174 put_flags(flags
, &ptr
);
1175 put_uint32(interfaceIndex
, &ptr
);
1176 put_uint32(protocol
, &ptr
);
1177 put_string(hostname
, &ptr
);
1179 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1180 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
1184 static void handle_browse_response(DNSServiceOp
*sdr
, CallbackHeader
*cbh
, char *data
, char *end
)
1186 char replyName
[256], replyType
[kDNSServiceMaxDomainName
], replyDomain
[kDNSServiceMaxDomainName
];
1187 get_string(&data
, end
, replyName
, 256);
1188 get_string(&data
, end
, replyType
, kDNSServiceMaxDomainName
);
1189 get_string(&data
, end
, replyDomain
, kDNSServiceMaxDomainName
);
1190 if (!data
) syslog(LOG_WARNING
, "dnssd_clientstub handle_browse_response: error reading result from daemon");
1191 else ((DNSServiceBrowseReply
)sdr
->AppCallback
)(sdr
, cbh
->cb_flags
, cbh
->cb_interface
, cbh
->cb_err
, replyName
, replyType
, replyDomain
, sdr
->AppContext
);
1192 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1195 DNSServiceErrorType DNSSD_API DNSServiceBrowse
1197 DNSServiceRef
*sdRef
,
1198 DNSServiceFlags flags
,
1199 uint32_t interfaceIndex
,
1200 const char *regtype
,
1202 DNSServiceBrowseReply callBack
,
1209 DNSServiceErrorType err
= ConnectToServer(sdRef
, flags
, browse_request
, handle_browse_response
, callBack
, context
);
1210 if (err
) return err
; // On error ConnectToServer leaves *sdRef set to NULL
1212 if (!domain
) domain
= "";
1213 len
= sizeof(flags
);
1214 len
+= sizeof(interfaceIndex
);
1215 len
+= strlen(regtype
) + 1;
1216 len
+= strlen(domain
) + 1;
1218 hdr
= create_hdr(browse_request
, &len
, &ptr
, (*sdRef
)->primary
? 1 : 0, *sdRef
);
1219 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
1221 put_flags(flags
, &ptr
);
1222 put_uint32(interfaceIndex
, &ptr
);
1223 put_string(regtype
, &ptr
);
1224 put_string(domain
, &ptr
);
1226 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1227 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
1231 DNSServiceErrorType DNSSD_API
DNSServiceSetDefaultDomainForUser(DNSServiceFlags flags
, const char *domain
)
1235 size_t len
= sizeof(flags
) + strlen(domain
) + 1;
1237 DNSServiceErrorType err
= ConnectToServer(&tmp
, 0, setdomain_request
, NULL
, NULL
, NULL
);
1238 if (err
) return err
;
1240 hdr
= create_hdr(setdomain_request
, &len
, &ptr
, 0, tmp
);
1241 if (!hdr
) { DNSServiceRefDeallocate(tmp
); return kDNSServiceErr_NoMemory
; }
1243 put_flags(flags
, &ptr
);
1244 put_string(domain
, &ptr
);
1245 err
= deliver_request(hdr
, tmp
); // Will free hdr for us
1246 DNSServiceRefDeallocate(tmp
);
1250 static void handle_regservice_response(DNSServiceOp
*sdr
, CallbackHeader
*cbh
, char *data
, char *end
)
1252 char name
[256], regtype
[kDNSServiceMaxDomainName
], domain
[kDNSServiceMaxDomainName
];
1253 get_string(&data
, end
, name
, 256);
1254 get_string(&data
, end
, regtype
, kDNSServiceMaxDomainName
);
1255 get_string(&data
, end
, domain
, kDNSServiceMaxDomainName
);
1256 if (!data
) syslog(LOG_WARNING
, "dnssd_clientstub handle_regservice_response: error reading result from daemon");
1257 else ((DNSServiceRegisterReply
)sdr
->AppCallback
)(sdr
, cbh
->cb_flags
, cbh
->cb_err
, name
, regtype
, domain
, sdr
->AppContext
);
1258 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1261 DNSServiceErrorType DNSSD_API DNSServiceRegister
1263 DNSServiceRef
*sdRef
,
1264 DNSServiceFlags flags
,
1265 uint32_t interfaceIndex
,
1267 const char *regtype
,
1270 uint16_t PortInNetworkByteOrder
,
1272 const void *txtRecord
,
1273 DNSServiceRegisterReply callBack
,
1280 DNSServiceErrorType err
;
1281 union { uint16_t s
; u_char b
[2]; } port
= { PortInNetworkByteOrder
};
1283 if (!name
) name
= "";
1284 if (!regtype
) return kDNSServiceErr_BadParam
;
1285 if (!domain
) domain
= "";
1286 if (!host
) host
= "";
1287 if (!txtRecord
) txtRecord
= (void*)"";
1289 // No callback must have auto-rename
1290 if (!callBack
&& (flags
& kDNSServiceFlagsNoAutoRename
)) return kDNSServiceErr_BadParam
;
1292 err
= ConnectToServer(sdRef
, flags
, reg_service_request
, callBack
? handle_regservice_response
: NULL
, callBack
, context
);
1293 if (err
) return err
; // On error ConnectToServer leaves *sdRef set to NULL
1295 len
= sizeof(DNSServiceFlags
);
1296 len
+= sizeof(uint32_t); // interfaceIndex
1297 len
+= strlen(name
) + strlen(regtype
) + strlen(domain
) + strlen(host
) + 4;
1298 len
+= 2 * sizeof(uint16_t); // port, txtLen
1301 hdr
= create_hdr(reg_service_request
, &len
, &ptr
, (*sdRef
)->primary
? 1 : 0, *sdRef
);
1302 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
1303 if (!callBack
) hdr
->ipc_flags
|= IPC_FLAGS_NOREPLY
;
1305 put_flags(flags
, &ptr
);
1306 put_uint32(interfaceIndex
, &ptr
);
1307 put_string(name
, &ptr
);
1308 put_string(regtype
, &ptr
);
1309 put_string(domain
, &ptr
);
1310 put_string(host
, &ptr
);
1313 put_uint16(txtLen
, &ptr
);
1314 put_rdata(txtLen
, txtRecord
, &ptr
);
1316 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1317 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
1321 static void handle_enumeration_response(DNSServiceOp
*sdr
, CallbackHeader
*cbh
, char *data
, char *end
)
1323 char domain
[kDNSServiceMaxDomainName
];
1324 get_string(&data
, end
, domain
, kDNSServiceMaxDomainName
);
1325 if (!data
) syslog(LOG_WARNING
, "dnssd_clientstub handle_enumeration_response: error reading result from daemon");
1326 else ((DNSServiceDomainEnumReply
)sdr
->AppCallback
)(sdr
, cbh
->cb_flags
, cbh
->cb_interface
, cbh
->cb_err
, domain
, sdr
->AppContext
);
1327 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1330 DNSServiceErrorType DNSSD_API DNSServiceEnumerateDomains
1332 DNSServiceRef
*sdRef
,
1333 DNSServiceFlags flags
,
1334 uint32_t interfaceIndex
,
1335 DNSServiceDomainEnumReply callBack
,
1342 DNSServiceErrorType err
;
1344 int f1
= (flags
& kDNSServiceFlagsBrowseDomains
) != 0;
1345 int f2
= (flags
& kDNSServiceFlagsRegistrationDomains
) != 0;
1346 if (f1
+ f2
!= 1) return kDNSServiceErr_BadParam
;
1348 err
= ConnectToServer(sdRef
, flags
, enumeration_request
, handle_enumeration_response
, callBack
, context
);
1349 if (err
) return err
; // On error ConnectToServer leaves *sdRef set to NULL
1351 len
= sizeof(DNSServiceFlags
);
1352 len
+= sizeof(uint32_t);
1354 hdr
= create_hdr(enumeration_request
, &len
, &ptr
, (*sdRef
)->primary
? 1 : 0, *sdRef
);
1355 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
1357 put_flags(flags
, &ptr
);
1358 put_uint32(interfaceIndex
, &ptr
);
1360 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1361 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
1365 static void ConnectionResponse(DNSServiceOp
*sdr
, CallbackHeader
*cbh
, char *data
, char *end
)
1367 DNSRecordRef rref
= cbh
->ipc_hdr
.client_context
.context
;
1368 (void)data
; // Unused
1370 //printf("ConnectionResponse got %d\n", cbh->ipc_hdr.op);
1371 if (cbh
->ipc_hdr
.op
!= reg_record_reply_op
)
1373 // When using kDNSServiceFlagsShareConnection, need to search the list of associated DNSServiceOps
1374 // to find the one this response is intended for, and then call through to its ProcessReply handler
1375 while (sdr
&& (sdr
->uid
.u32
[0] != cbh
->ipc_hdr
.client_context
.u32
[0] || sdr
->uid
.u32
[1] != cbh
->ipc_hdr
.client_context
.u32
[1]))
1377 // NOTE: We may sometimes not find a matching DNSServiceOp, in the case where the client has
1378 // cancelled the subordinate DNSServiceOp, but there are still messages in the pipeline from the daemon
1379 if (sdr
&& sdr
->ProcessReply
) sdr
->ProcessReply(sdr
, cbh
, data
, end
);
1380 // WARNING: Don't touch sdr after this -- client may have called DNSServiceRefDeallocate
1384 if (sdr
->op
== connection_request
)
1385 rref
->AppCallback(rref
->sdr
, rref
, cbh
->cb_flags
, cbh
->cb_err
, rref
->AppContext
);
1388 syslog(LOG_WARNING
, "dnssd_clientstub handle_regrecord_response: sdr->op != connection_request");
1389 rref
->AppCallback(rref
->sdr
, rref
, 0, kDNSServiceErr_Unknown
, rref
->AppContext
);
1391 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1394 DNSServiceErrorType DNSSD_API
DNSServiceCreateConnection(DNSServiceRef
*sdRef
)
1399 DNSServiceErrorType err
= ConnectToServer(sdRef
, 0, connection_request
, ConnectionResponse
, NULL
, NULL
);
1400 if (err
) return err
; // On error ConnectToServer leaves *sdRef set to NULL
1402 hdr
= create_hdr(connection_request
, &len
, &ptr
, 0, *sdRef
);
1403 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
1405 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1406 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
1410 DNSServiceErrorType DNSSD_API DNSServiceRegisterRecord
1412 DNSServiceRef sdRef
,
1413 DNSRecordRef
*RecordRef
,
1414 DNSServiceFlags flags
,
1415 uint32_t interfaceIndex
,
1416 const char *fullname
,
1422 DNSServiceRegisterRecordReply callBack
,
1428 ipc_msg_hdr
*hdr
= NULL
;
1429 DNSRecordRef rref
= NULL
;
1430 int f1
= (flags
& kDNSServiceFlagsShared
) != 0;
1431 int f2
= (flags
& kDNSServiceFlagsUnique
) != 0;
1432 if (f1
+ f2
!= 1) return kDNSServiceErr_BadParam
;
1434 if (!sdRef
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRegisterRecord called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam
; }
1436 if (!DNSServiceRefValid(sdRef
))
1438 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRegisterRecord called with invalid DNSServiceRef %p %08X %08X", sdRef
, sdRef
->sockfd
, sdRef
->validator
);
1439 return kDNSServiceErr_BadReference
;
1442 if (sdRef
->op
!= connection_request
)
1444 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRegisterRecord called with non-DNSServiceCreateConnection DNSServiceRef %p %d", sdRef
, sdRef
->op
);
1445 return kDNSServiceErr_BadReference
;
1450 len
= sizeof(DNSServiceFlags
);
1451 len
+= 2 * sizeof(uint32_t); // interfaceIndex, ttl
1452 len
+= 3 * sizeof(uint16_t); // rrtype, rrclass, rdlen
1453 len
+= strlen(fullname
) + 1;
1456 hdr
= create_hdr(reg_record_request
, &len
, &ptr
, 1, sdRef
);
1457 if (!hdr
) return kDNSServiceErr_NoMemory
;
1459 put_flags(flags
, &ptr
);
1460 put_uint32(interfaceIndex
, &ptr
);
1461 put_string(fullname
, &ptr
);
1462 put_uint16(rrtype
, &ptr
);
1463 put_uint16(rrclass
, &ptr
);
1464 put_uint16(rdlen
, &ptr
);
1465 put_rdata(rdlen
, rdata
, &ptr
);
1466 put_uint32(ttl
, &ptr
);
1468 rref
= malloc(sizeof(DNSRecord
));
1469 if (!rref
) { free(hdr
); return kDNSServiceErr_NoMemory
; }
1470 rref
->AppContext
= context
;
1471 rref
->AppCallback
= callBack
;
1472 rref
->record_index
= sdRef
->max_index
++;
1475 hdr
->client_context
.context
= rref
;
1476 hdr
->reg_index
= rref
->record_index
;
1478 return deliver_request(hdr
, sdRef
); // Will free hdr for us
1481 // sdRef returned by DNSServiceRegister()
1482 DNSServiceErrorType DNSSD_API DNSServiceAddRecord
1484 DNSServiceRef sdRef
,
1485 DNSRecordRef
*RecordRef
,
1486 DNSServiceFlags flags
,
1498 if (!sdRef
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceAddRecord called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam
; }
1499 if (!RecordRef
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceAddRecord called with NULL DNSRecordRef pointer"); return kDNSServiceErr_BadParam
; }
1500 if (sdRef
->op
!= reg_service_request
)
1502 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceAddRecord called with non-DNSServiceRegister DNSServiceRef %p %d", sdRef
, sdRef
->op
);
1503 return kDNSServiceErr_BadReference
;
1506 if (!DNSServiceRefValid(sdRef
))
1508 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceAddRecord called with invalid DNSServiceRef %p %08X %08X", sdRef
, sdRef
->sockfd
, sdRef
->validator
);
1509 return kDNSServiceErr_BadReference
;
1514 len
+= 2 * sizeof(uint16_t); // rrtype, rdlen
1516 len
+= sizeof(uint32_t);
1517 len
+= sizeof(DNSServiceFlags
);
1519 hdr
= create_hdr(add_record_request
, &len
, &ptr
, 1, sdRef
);
1520 if (!hdr
) return kDNSServiceErr_NoMemory
;
1521 put_flags(flags
, &ptr
);
1522 put_uint16(rrtype
, &ptr
);
1523 put_uint16(rdlen
, &ptr
);
1524 put_rdata(rdlen
, rdata
, &ptr
);
1525 put_uint32(ttl
, &ptr
);
1527 rref
= malloc(sizeof(DNSRecord
));
1528 if (!rref
) { free(hdr
); return kDNSServiceErr_NoMemory
; }
1529 rref
->AppContext
= NULL
;
1530 rref
->AppCallback
= NULL
;
1531 rref
->record_index
= sdRef
->max_index
++;
1534 hdr
->client_context
.context
= rref
;
1535 hdr
->reg_index
= rref
->record_index
;
1537 return deliver_request(hdr
, sdRef
); // Will free hdr for us
1540 // DNSRecordRef returned by DNSServiceRegisterRecord or DNSServiceAddRecord
1541 DNSServiceErrorType DNSSD_API DNSServiceUpdateRecord
1543 DNSServiceRef sdRef
,
1544 DNSRecordRef RecordRef
,
1545 DNSServiceFlags flags
,
1555 if (!sdRef
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceUpdateRecord called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam
; }
1557 if (!DNSServiceRefValid(sdRef
))
1559 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceUpdateRecord called with invalid DNSServiceRef %p %08X %08X", sdRef
, sdRef
->sockfd
, sdRef
->validator
);
1560 return kDNSServiceErr_BadReference
;
1563 // Note: RecordRef is allowed to be NULL
1565 len
+= sizeof(uint16_t);
1567 len
+= sizeof(uint32_t);
1568 len
+= sizeof(DNSServiceFlags
);
1570 hdr
= create_hdr(update_record_request
, &len
, &ptr
, 1, sdRef
);
1571 if (!hdr
) return kDNSServiceErr_NoMemory
;
1572 hdr
->reg_index
= RecordRef
? RecordRef
->record_index
: TXT_RECORD_INDEX
;
1573 put_flags(flags
, &ptr
);
1574 put_uint16(rdlen
, &ptr
);
1575 put_rdata(rdlen
, rdata
, &ptr
);
1576 put_uint32(ttl
, &ptr
);
1577 return deliver_request(hdr
, sdRef
); // Will free hdr for us
1580 DNSServiceErrorType DNSSD_API DNSServiceRemoveRecord
1582 DNSServiceRef sdRef
,
1583 DNSRecordRef RecordRef
,
1584 DNSServiceFlags flags
1590 DNSServiceErrorType err
;
1592 if (!sdRef
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRemoveRecord called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam
; }
1593 if (!RecordRef
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRemoveRecord called with NULL DNSRecordRef"); return kDNSServiceErr_BadParam
; }
1594 if (!sdRef
->max_index
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRemoveRecord called with bad DNSServiceRef"); return kDNSServiceErr_BadReference
; }
1596 if (!DNSServiceRefValid(sdRef
))
1598 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRemoveRecord called with invalid DNSServiceRef %p %08X %08X", sdRef
, sdRef
->sockfd
, sdRef
->validator
);
1599 return kDNSServiceErr_BadReference
;
1602 len
+= sizeof(flags
);
1603 hdr
= create_hdr(remove_record_request
, &len
, &ptr
, 1, sdRef
);
1604 if (!hdr
) return kDNSServiceErr_NoMemory
;
1605 hdr
->reg_index
= RecordRef
->record_index
;
1606 put_flags(flags
, &ptr
);
1607 err
= deliver_request(hdr
, sdRef
); // Will free hdr for us
1608 if (!err
) free(RecordRef
);
1612 DNSServiceErrorType DNSSD_API DNSServiceReconfirmRecord
1614 DNSServiceFlags flags
,
1615 uint32_t interfaceIndex
,
1616 const char *fullname
,
1628 DNSServiceErrorType err
= ConnectToServer(&tmp
, flags
, reconfirm_record_request
, NULL
, NULL
, NULL
);
1629 if (err
) return err
;
1631 len
= sizeof(DNSServiceFlags
);
1632 len
+= sizeof(uint32_t);
1633 len
+= strlen(fullname
) + 1;
1634 len
+= 3 * sizeof(uint16_t);
1636 hdr
= create_hdr(reconfirm_record_request
, &len
, &ptr
, 0, tmp
);
1637 if (!hdr
) { DNSServiceRefDeallocate(tmp
); return kDNSServiceErr_NoMemory
; }
1639 put_flags(flags
, &ptr
);
1640 put_uint32(interfaceIndex
, &ptr
);
1641 put_string(fullname
, &ptr
);
1642 put_uint16(rrtype
, &ptr
);
1643 put_uint16(rrclass
, &ptr
);
1644 put_uint16(rdlen
, &ptr
);
1645 put_rdata(rdlen
, rdata
, &ptr
);
1647 err
= deliver_request(hdr
, tmp
); // Will free hdr for us
1648 DNSServiceRefDeallocate(tmp
);
1652 static void handle_port_mapping_response(DNSServiceOp
*sdr
, CallbackHeader
*cbh
, char *data
, char *end
)
1654 union { uint32_t l
; u_char b
[4]; } addr
;
1655 uint8_t protocol
= 0;
1656 union { uint16_t s
; u_char b
[2]; } privatePort
;
1657 union { uint16_t s
; u_char b
[2]; } publicPort
;
1660 if (data
+ 13 > end
) data
= NULL
;
1663 addr
.b
[0] = *data
++;
1664 addr
.b
[1] = *data
++;
1665 addr
.b
[2] = *data
++;
1666 addr
.b
[3] = *data
++;
1668 privatePort
.b
[0] = *data
++;
1669 privatePort
.b
[1] = *data
++;
1670 publicPort
.b
[0] = *data
++;
1671 publicPort
.b
[1] = *data
++;
1672 ttl
= get_uint32(&data
, end
);
1675 if (!data
) syslog(LOG_WARNING
, "dnssd_clientstub handle_port_mapping_response: error reading result from daemon");
1676 else ((DNSServiceNATPortMappingReply
)sdr
->AppCallback
)(sdr
, cbh
->cb_flags
, cbh
->cb_interface
, cbh
->cb_err
, addr
.l
, protocol
, privatePort
.s
, publicPort
.s
, ttl
, sdr
->AppContext
);
1677 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1680 DNSServiceErrorType DNSSD_API DNSServiceNATPortMappingCreate
1682 DNSServiceRef
*sdRef
,
1683 DNSServiceFlags flags
,
1684 uint32_t interfaceIndex
,
1685 uint32_t protocol
, /* TCP and/or UDP */
1686 uint16_t privatePortInNetworkByteOrder
,
1687 uint16_t publicPortInNetworkByteOrder
,
1688 uint32_t ttl
, /* time to live in seconds */
1689 DNSServiceNATPortMappingReply callBack
,
1690 void *context
/* may be NULL */
1696 union { uint16_t s
; u_char b
[2]; } privatePort
= { privatePortInNetworkByteOrder
};
1697 union { uint16_t s
; u_char b
[2]; } publicPort
= { publicPortInNetworkByteOrder
};
1699 DNSServiceErrorType err
= ConnectToServer(sdRef
, flags
, port_mapping_request
, handle_port_mapping_response
, callBack
, context
);
1700 if (err
) return err
; // On error ConnectToServer leaves *sdRef set to NULL
1702 len
= sizeof(flags
);
1703 len
+= sizeof(interfaceIndex
);
1704 len
+= sizeof(protocol
);
1705 len
+= sizeof(privatePort
);
1706 len
+= sizeof(publicPort
);
1709 hdr
= create_hdr(port_mapping_request
, &len
, &ptr
, (*sdRef
)->primary
? 1 : 0, *sdRef
);
1710 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
1712 put_flags(flags
, &ptr
);
1713 put_uint32(interfaceIndex
, &ptr
);
1714 put_uint32(protocol
, &ptr
);
1715 *ptr
++ = privatePort
.b
[0];
1716 *ptr
++ = privatePort
.b
[1];
1717 *ptr
++ = publicPort
.b
[0];
1718 *ptr
++ = publicPort
.b
[1];
1719 put_uint32(ttl
, &ptr
);
1721 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1722 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }