1 /* -*- Mode: C; tab-width: 4 -*-
3 * Copyright (c) 2003-2004, Apple Computer, Inc. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of its
14 * contributors may be used to endorse or promote products derived from this
15 * software without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
18 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
21 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
24 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
26 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 #include "dnssd_ipc.h"
37 #include <CommonServices.h>
38 #include <DebugServices.h>
44 #define sockaddr_mdns sockaddr_in
45 #define AF_MDNS AF_INET
47 // Disable warning: "'type cast' : from data pointer 'void *' to function pointer"
48 #pragma warning(disable:4055)
50 // Disable warning: "nonstandard extension, function/data pointer conversion in expression"
51 #pragma warning(disable:4152)
53 extern BOOL
IsSystemServiceDisabled();
55 #define sleep(X) Sleep((X) * 1000)
57 static int g_initWinsock
= 0;
58 #define LOG_WARNING kDebugLevelWarning
59 static void syslog( int priority
, const char * message
, ...)
64 DWORD err
= WSAGetLastError();
66 va_start( args
, message
);
67 len
= _vscprintf( message
, args
) + 1;
68 buffer
= malloc( len
* sizeof(char) );
69 if ( buffer
) { vsprintf( buffer
, message
, args
); OutputDebugString( buffer
); free( buffer
); }
70 WSASetLastError( err
);
74 #include <sys/fcntl.h> // For O_RDWR etc.
76 #include <sys/socket.h>
79 #define sockaddr_mdns sockaddr_un
80 #define AF_MDNS AF_LOCAL
84 // <rdar://problem/4096913> Specifies how many times we'll try and connect to the server.
86 #define DNSSD_CLIENT_MAXTRIES 4
88 // Uncomment the line below to use the old error return mechanism of creating a temporary named socket (e.g. in /var/tmp)
89 //#define USE_NAMED_ERROR_RETURN_SOCKET 1
91 #ifndef CTL_PATH_PREFIX
92 #define CTL_PATH_PREFIX "/var/tmp/dnssd_result_socket."
98 DNSServiceFlags cb_flags
;
99 uint32_t cb_interface
;
100 DNSServiceErrorType cb_err
;
103 typedef struct _DNSServiceRef_t DNSServiceOp
;
104 typedef struct _DNSRecordRef_t DNSRecord
;
106 // client stub callback to process message from server and deliver results to client application
107 typedef void (*ProcessReplyFn
)(DNSServiceOp
*const sdr
, const CallbackHeader
*const cbh
, const char *msg
, const char *const end
);
109 #define ValidatorBits 0x12345678
110 #define DNSServiceRefValid(X) (dnssd_SocketValid((X)->sockfd) && (((X)->sockfd ^ (X)->validator) == ValidatorBits))
112 // When using kDNSServiceFlagsShareConnection, there is one primary _DNSServiceOp_t, and zero or more subordinates
113 // For the primary, the 'next' field points to the first subordinate, and its 'next' field points to the next, and so on.
114 // For the primary, the 'primary' field is NULL; for subordinates the 'primary' field points back to the associated primary
116 // _DNS_SD_LIBDISPATCH is defined where libdispatch/GCD is available. This does not mean that the application will use the
117 // DNSServiceSetDispatchQueue API. Hence any new code guarded with _DNS_SD_LIBDISPATCH should still be backwards compatible.
118 struct _DNSServiceRef_t
120 DNSServiceOp
*next
; // For shared connection
121 DNSServiceOp
*primary
; // For shared connection
122 dnssd_sock_t sockfd
; // Connected socket between client and daemon
123 dnssd_sock_t validator
; // Used to detect memory corruption, double disposals, etc.
124 client_context_t uid
; // For shared connection requests, each subordinate DNSServiceRef has its own ID,
125 // unique within the scope of the same shared parent DNSServiceRef
126 uint32_t op
; // request_op_t or reply_op_t
127 uint32_t max_index
; // Largest assigned record index - 0 if no additional records registered
128 uint32_t logcounter
; // Counter used to control number of syslog messages we write
129 int *moreptr
; // Set while DNSServiceProcessResult working on this particular DNSServiceRef
130 ProcessReplyFn ProcessReply
; // Function pointer to the code to handle received messages
131 void *AppCallback
; // Client callback function and context
134 #if _DNS_SD_LIBDISPATCH
135 dispatch_source_t disp_source
;
136 dispatch_queue_t disp_queue
;
140 struct _DNSRecordRef_t
144 DNSServiceRegisterRecordReply AppCallback
;
146 uint32_t record_index
; // index is unique to the ServiceDiscoveryRef
150 // Write len bytes. Return 0 on success, -1 on error
151 static int write_all(dnssd_sock_t sd
, char *buf
, size_t len
)
153 // Don't use "MSG_WAITALL"; it returns "Invalid argument" on some Linux versions; use an explicit while() loop instead.
154 //if (send(sd, buf, len, MSG_WAITALL) != len) return -1;
157 ssize_t num_written
= send(sd
, buf
, (long)len
, 0);
158 if (num_written
< 0 || (size_t)num_written
> len
)
160 // Should never happen. If it does, it indicates some OS bug,
161 // or that the mDNSResponder daemon crashed (which should never happen).
162 #if !defined(__ppc__) && defined(SO_ISDEFUNCT)
164 socklen_t dlen
= sizeof (defunct
);
165 if (getsockopt(sd
, SOL_SOCKET
, SO_ISDEFUNCT
, &defunct
, &dlen
) < 0)
166 syslog(LOG_WARNING
, "dnssd_clientstub write_all: SO_ISDEFUNCT failed %d %s", dnssd_errno
, dnssd_strerror(dnssd_errno
));
168 syslog(LOG_WARNING
, "dnssd_clientstub write_all(%d) failed %ld/%ld %d %s", sd
,
169 (long)num_written
, (long)len
,
170 (num_written
< 0) ? dnssd_errno
: 0,
171 (num_written
< 0) ? dnssd_strerror(dnssd_errno
) : "");
173 syslog(LOG_INFO
, "dnssd_clientstub write_all(%d) DEFUNCT", sd
);
175 syslog(LOG_WARNING
, "dnssd_clientstub write_all(%d) failed %ld/%ld %d %s", sd
,
176 (long)num_written
, (long)len
,
177 (num_written
< 0) ? dnssd_errno
: 0,
178 (num_written
< 0) ? dnssd_strerror(dnssd_errno
) : "");
188 enum { read_all_success
= 0, read_all_fail
= -1, read_all_wouldblock
= -2 };
190 // Read len bytes. Return 0 on success, read_all_fail on error, or read_all_wouldblock for
191 static int read_all(dnssd_sock_t sd
, char *buf
, int len
)
193 // Don't use "MSG_WAITALL"; it returns "Invalid argument" on some Linux versions; use an explicit while() loop instead.
194 //if (recv(sd, buf, len, MSG_WAITALL) != len) return -1;
198 ssize_t num_read
= recv(sd
, buf
, len
, 0);
199 if ((num_read
== 0) || (num_read
< 0) || (num_read
> len
))
203 // Should never happen. If it does, it indicates some OS bug,
204 // or that the mDNSResponder daemon crashed (which should never happen).
206 // <rdar://problem/7481776> Suppress logs for "A non-blocking socket operation
207 // could not be completed immediately"
208 if (WSAGetLastError() != WSAEWOULDBLOCK
)
211 #if !defined(__ppc__) && defined(SO_ISDEFUNCT)
213 socklen_t dlen
= sizeof (defunct
);
214 if (getsockopt(sd
, SOL_SOCKET
, SO_ISDEFUNCT
, &defunct
, &dlen
) < 0)
215 syslog(LOG_WARNING
, "dnssd_clientstub read_all: SO_ISDEFUNCT failed %d %s", dnssd_errno
, dnssd_strerror(dnssd_errno
));
221 syslog(LOG_WARNING
, "dnssd_clientstub read_all(%d) failed %ld/%ld %d %s", sd
,
222 (long)num_read
, (long)len
,
223 (num_read
< 0) ? dnssd_errno
: 0,
224 (num_read
< 0) ? dnssd_strerror(dnssd_errno
) : "");
226 syslog(LOG_INFO
, "dnssd_clientstub read_all(%d) DEFUNCT", sd
);
227 return (num_read
< 0 && dnssd_errno
== dnssd_EWOULDBLOCK
) ? read_all_wouldblock
: read_all_fail
;
232 return read_all_success
;
235 // Returns 1 if more bytes remain to be read on socket descriptor sd, 0 otherwise
236 static int more_bytes(dnssd_sock_t sd
)
238 struct timeval tv
= { 0, 0 };
250 // Compute the number of integers needed for storing "sd". Internally fd_set is stored
251 // as an array of ints with one bit for each fd and hence we need to compute
252 // the number of ints needed rather than the number of bytes. If "sd" is 32, we need
253 // two ints and not just one.
254 int nfdbits
= sizeof (int) * 8;
255 int nints
= (sd
/nfdbits
) + 1;
256 fs
= (fd_set
*)calloc(nints
, sizeof(int));
257 if (fs
== NULL
) { syslog(LOG_WARNING
, "dnssd_clientstub more_bytes: malloc failed"); return 0; }
260 ret
= select((int)sd
+1, fs
, (fd_set
*)NULL
, (fd_set
*)NULL
, &tv
);
261 if (fs
!= &readfds
) free(fs
);
267 * allocate and initialize an ipc message header. Value of len should initially be the
268 * length of the data, and is set to the value of the data plus the header. data_start
269 * is set to point to the beginning of the data section. SeparateReturnSocket should be
270 * non-zero for calls that can't receive an immediate error return value on their primary
271 * socket, and therefore require a separate return path for the error code result.
272 * if zero, the path to a control socket is appended at the beginning of the message buffer.
273 * data_start is set past this string.
275 static ipc_msg_hdr
*create_hdr(uint32_t op
, size_t *len
, char **data_start
, int SeparateReturnSocket
, DNSServiceOp
*ref
)
280 #if !defined(USE_TCP_LOOPBACK)
281 char ctrl_path
[64] = ""; // "/var/tmp/dnssd_result_socket.xxxxxxxxxx-xxx-xxxxxx"
284 if (SeparateReturnSocket
)
286 #if defined(USE_TCP_LOOPBACK)
287 *len
+= 2; // Allocate space for two-byte port number
288 #elif defined(USE_NAMED_ERROR_RETURN_SOCKET)
290 if (gettimeofday(&tv
, NULL
) < 0)
291 { syslog(LOG_WARNING
, "dnssd_clientstub create_hdr: gettimeofday failed %d %s", dnssd_errno
, dnssd_strerror(dnssd_errno
)); return NULL
; }
292 sprintf(ctrl_path
, "%s%d-%.3lx-%.6lu", CTL_PATH_PREFIX
, (int)getpid(),
293 (unsigned long)(tv
.tv_sec
& 0xFFF), (unsigned long)(tv
.tv_usec
));
294 *len
+= strlen(ctrl_path
) + 1;
296 *len
+= 1; // Allocate space for single zero byte (empty C string)
300 datalen
= (int) *len
;
301 *len
+= sizeof(ipc_msg_hdr
);
303 // Write message to buffer
305 if (!msg
) { syslog(LOG_WARNING
, "dnssd_clientstub create_hdr: malloc failed"); return NULL
; }
307 memset(msg
, 0, *len
);
308 hdr
= (ipc_msg_hdr
*)msg
;
309 hdr
->version
= VERSION
;
310 hdr
->datalen
= datalen
;
313 hdr
->client_context
= ref
->uid
;
315 *data_start
= msg
+ sizeof(ipc_msg_hdr
);
316 #if defined(USE_TCP_LOOPBACK)
317 // Put dummy data in for the port, since we don't know what it is yet.
318 // The data will get filled in before we send the message. This happens in deliver_request().
319 if (SeparateReturnSocket
) put_uint16(0, data_start
);
321 if (SeparateReturnSocket
) put_string(ctrl_path
, data_start
);
326 static void FreeDNSRecords(DNSServiceOp
*sdRef
)
328 DNSRecord
*rec
= sdRef
->rec
;
331 DNSRecord
*next
= rec
->recnext
;
337 static void FreeDNSServiceOp(DNSServiceOp
*x
)
339 // We don't use our DNSServiceRefValid macro here because if we're cleaning up after a socket() call failed
340 // then sockfd could legitimately contain a failing value (e.g. dnssd_InvalidSocket)
341 if ((x
->sockfd
^ x
->validator
) != ValidatorBits
)
342 syslog(LOG_WARNING
, "dnssd_clientstub attempt to dispose invalid DNSServiceRef %p %08X %08X", x
, x
->sockfd
, x
->validator
);
347 x
->sockfd
= dnssd_InvalidSocket
;
348 x
->validator
= 0xDDDDDDDD;
349 x
->op
= request_op_none
;
353 x
->ProcessReply
= NULL
;
354 x
->AppCallback
= NULL
;
355 x
->AppContext
= NULL
;
357 #if _DNS_SD_LIBDISPATCH
358 if (x
->disp_source
) dispatch_release(x
->disp_source
);
359 x
->disp_source
= NULL
;
360 x
->disp_queue
= NULL
;
362 // DNSRecords may have been added to subordinate sdRef e.g., DNSServiceRegister/DNSServiceAddRecord
363 // or on the main sdRef e.g., DNSServiceCreateConnection/DNSServiveRegisterRecord. DNSRecords may have
364 // been freed if the application called DNSRemoveRecord
370 // Return a connected service ref (deallocate with DNSServiceRefDeallocate)
371 static DNSServiceErrorType
ConnectToServer(DNSServiceRef
*ref
, DNSServiceFlags flags
, uint32_t op
, ProcessReplyFn ProcessReply
, void *AppCallback
, void *AppContext
)
373 #if APPLE_OSX_mDNSResponder
374 int NumTries
= DNSSD_CLIENT_MAXTRIES
;
379 dnssd_sockaddr_t saddr
;
382 if (!ref
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSService operation with NULL DNSServiceRef"); return kDNSServiceErr_BadParam
; }
384 if (flags
& kDNSServiceFlagsShareConnection
)
388 syslog(LOG_WARNING
, "dnssd_clientstub kDNSServiceFlagsShareConnection used with NULL DNSServiceRef");
389 return kDNSServiceErr_BadParam
;
391 if (!DNSServiceRefValid(*ref
) || (*ref
)->op
!= connection_request
|| (*ref
)->primary
)
393 syslog(LOG_WARNING
, "dnssd_clientstub kDNSServiceFlagsShareConnection used with invalid DNSServiceRef %p %08X %08X",
394 (*ref
), (*ref
)->sockfd
, (*ref
)->validator
);
396 return kDNSServiceErr_BadReference
;
405 if (WSAStartup(MAKEWORD(2,2), &wsaData
) != 0) { *ref
= NULL
; return kDNSServiceErr_ServiceNotRunning
; }
407 // <rdar://problem/4096913> If the system service is disabled, we only want to try to connect once
408 if (IsSystemServiceDisabled()) NumTries
= DNSSD_CLIENT_MAXTRIES
;
411 sdr
= malloc(sizeof(DNSServiceOp
));
412 if (!sdr
) { syslog(LOG_WARNING
, "dnssd_clientstub ConnectToServer: malloc failed"); *ref
= NULL
; return kDNSServiceErr_NoMemory
; }
415 sdr
->sockfd
= dnssd_InvalidSocket
;
416 sdr
->validator
= sdr
->sockfd
^ ValidatorBits
;
423 sdr
->ProcessReply
= ProcessReply
;
424 sdr
->AppCallback
= AppCallback
;
425 sdr
->AppContext
= AppContext
;
427 #if _DNS_SD_LIBDISPATCH
428 sdr
->disp_source
= NULL
;
429 sdr
->disp_queue
= NULL
;
432 if (flags
& kDNSServiceFlagsShareConnection
)
434 DNSServiceOp
**p
= &(*ref
)->next
; // Append ourselves to end of primary's list
435 while (*p
) p
= &(*p
)->next
;
437 // Preincrement counter before we use it -- it helps with debugging if we know the all-zeroes ID should never appear
438 if (++(*ref
)->uid
.u32
[0] == 0) ++(*ref
)->uid
.u32
[1]; // In parent DNSServiceOp increment UID counter
439 sdr
->primary
= *ref
; // Set our primary pointer
440 sdr
->sockfd
= (*ref
)->sockfd
; // Inherit primary's socket
441 sdr
->validator
= (*ref
)->validator
;
442 sdr
->uid
= (*ref
)->uid
;
443 //printf("ConnectToServer sharing socket %d\n", sdr->sockfd);
448 const unsigned long optval
= 1;
451 sdr
->sockfd
= socket(AF_DNSSD
, SOCK_STREAM
, 0);
452 sdr
->validator
= sdr
->sockfd
^ ValidatorBits
;
453 if (!dnssd_SocketValid(sdr
->sockfd
))
455 syslog(LOG_WARNING
, "dnssd_clientstub ConnectToServer: socket failed %d %s", dnssd_errno
, dnssd_strerror(dnssd_errno
));
456 FreeDNSServiceOp(sdr
);
457 return kDNSServiceErr_NoMemory
;
460 // Some environments (e.g. OS X) support turning off SIGPIPE for a socket
461 if (setsockopt(sdr
->sockfd
, SOL_SOCKET
, SO_NOSIGPIPE
, &optval
, sizeof(optval
)) < 0)
462 syslog(LOG_WARNING
, "dnssd_clientstub ConnectToServer: SO_NOSIGPIPE failed %d %s", dnssd_errno
, dnssd_strerror(dnssd_errno
));
464 #if defined(USE_TCP_LOOPBACK)
465 saddr
.sin_family
= AF_INET
;
466 saddr
.sin_addr
.s_addr
= inet_addr(MDNS_TCP_SERVERADDR
);
467 saddr
.sin_port
= htons(MDNS_TCP_SERVERPORT
);
469 saddr
.sun_family
= AF_LOCAL
;
470 strcpy(saddr
.sun_path
, MDNS_UDS_SERVERPATH
);
471 #if !defined(__ppc__) && defined(SO_DEFUNCTOK)
474 if (setsockopt(sdr
->sockfd
, SOL_SOCKET
, SO_DEFUNCTOK
, &defunct
, sizeof(defunct
)) < 0)
475 syslog(LOG_WARNING
, "dnssd_clientstub ConnectToServer: SO_DEFUNCTOK failed %d %s", dnssd_errno
, dnssd_strerror(dnssd_errno
));
482 int err
= connect(sdr
->sockfd
, (struct sockaddr
*) &saddr
, sizeof(saddr
));
483 if (!err
) break; // If we succeeded, return sdr
484 // If we failed, then it may be because the daemon is still launching.
485 // This can happen for processes that launch early in the boot process, while the
486 // daemon is still coming up. Rather than fail here, we'll wait a bit and try again.
487 // If, after four seconds, we still can't connect to the daemon,
488 // then we give up and return a failure code.
489 if (++NumTries
< DNSSD_CLIENT_MAXTRIES
) sleep(1); // Sleep a bit, then try again
490 else { dnssd_close(sdr
->sockfd
); FreeDNSServiceOp(sdr
); return kDNSServiceErr_ServiceNotRunning
; }
492 //printf("ConnectToServer opened socket %d\n", sdr->sockfd);
496 return kDNSServiceErr_NoError
;
499 #define deliver_request_bailout(MSG) \
500 do { syslog(LOG_WARNING, "dnssd_clientstub deliver_request: %s failed %d (%s)", (MSG), dnssd_errno, dnssd_strerror(dnssd_errno)); goto cleanup; } while(0)
502 static DNSServiceErrorType
deliver_request(ipc_msg_hdr
*hdr
, DNSServiceOp
*sdr
)
504 uint32_t datalen
= hdr
->datalen
; // We take a copy here because we're going to convert hdr->datalen to network byte order
505 #if defined(USE_TCP_LOOPBACK) || defined(USE_NAMED_ERROR_RETURN_SOCKET)
506 char *const data
= (char *)hdr
+ sizeof(ipc_msg_hdr
);
508 dnssd_sock_t listenfd
= dnssd_InvalidSocket
, errsd
= dnssd_InvalidSocket
;
509 DNSServiceErrorType err
= kDNSServiceErr_Unknown
; // Default for the "goto cleanup" cases
510 int MakeSeparateReturnSocket
= 0;
512 // Note: need to check hdr->op, not sdr->op.
513 // hdr->op contains the code for the specific operation we're currently doing, whereas sdr->op
514 // contains the original parent DNSServiceOp (e.g. for an add_record_request, hdr->op will be
515 // add_record_request but the parent sdr->op will be connection_request or reg_service_request)
517 hdr
->op
== reg_record_request
|| hdr
->op
== add_record_request
|| hdr
->op
== update_record_request
|| hdr
->op
== remove_record_request
)
518 MakeSeparateReturnSocket
= 1;
520 if (!DNSServiceRefValid(sdr
))
522 syslog(LOG_WARNING
, "dnssd_clientstub deliver_request: invalid DNSServiceRef %p %08X %08X", sdr
, sdr
->sockfd
, sdr
->validator
);
523 return kDNSServiceErr_BadReference
;
526 if (!hdr
) { syslog(LOG_WARNING
, "dnssd_clientstub deliver_request: !hdr"); return kDNSServiceErr_Unknown
; }
528 if (MakeSeparateReturnSocket
)
530 #if defined(USE_TCP_LOOPBACK)
532 union { uint16_t s
; u_char b
[2]; } port
;
533 dnssd_sockaddr_t caddr
;
534 dnssd_socklen_t len
= (dnssd_socklen_t
) sizeof(caddr
);
535 listenfd
= socket(AF_DNSSD
, SOCK_STREAM
, 0);
536 if (!dnssd_SocketValid(listenfd
)) deliver_request_bailout("TCP socket");
538 caddr
.sin_family
= AF_INET
;
540 caddr
.sin_addr
.s_addr
= inet_addr(MDNS_TCP_SERVERADDR
);
541 if (bind(listenfd
, (struct sockaddr
*) &caddr
, sizeof(caddr
)) < 0) deliver_request_bailout("TCP bind");
542 if (getsockname(listenfd
, (struct sockaddr
*) &caddr
, &len
) < 0) deliver_request_bailout("TCP getsockname");
543 if (listen(listenfd
, 1) < 0) deliver_request_bailout("TCP listen");
544 port
.s
= caddr
.sin_port
;
545 data
[0] = port
.b
[0]; // don't switch the byte order, as the
546 data
[1] = port
.b
[1]; // daemon expects it in network byte order
548 #elif defined(USE_NAMED_ERROR_RETURN_SOCKET)
552 dnssd_sockaddr_t caddr
;
553 listenfd
= socket(AF_DNSSD
, SOCK_STREAM
, 0);
554 if (!dnssd_SocketValid(listenfd
)) deliver_request_bailout("USE_NAMED_ERROR_RETURN_SOCKET socket");
556 caddr
.sun_family
= AF_LOCAL
;
557 // According to Stevens (section 3.2), there is no portable way to
558 // determine whether sa_len is defined on a particular platform.
559 #ifndef NOT_HAVE_SA_LEN
560 caddr
.sun_len
= sizeof(struct sockaddr_un
);
562 strcpy(caddr
.sun_path
, data
);
564 bindresult
= bind(listenfd
, (struct sockaddr
*)&caddr
, sizeof(caddr
));
566 if (bindresult
< 0) deliver_request_bailout("USE_NAMED_ERROR_RETURN_SOCKET bind");
567 if (listen(listenfd
, 1) < 0) deliver_request_bailout("USE_NAMED_ERROR_RETURN_SOCKET listen");
572 if (socketpair(AF_DNSSD
, SOCK_STREAM
, 0, sp
) < 0) deliver_request_bailout("socketpair");
575 errsd
= sp
[0]; // We'll read our four-byte error code from sp[0]
576 listenfd
= sp
[1]; // We'll send sp[1] to the daemon
577 #if !defined(__ppc__) && defined(SO_DEFUNCTOK)
580 if (setsockopt(errsd
, SOL_SOCKET
, SO_DEFUNCTOK
, &defunct
, sizeof(defunct
)) < 0)
581 syslog(LOG_WARNING
, "dnssd_clientstub ConnectToServer: SO_DEFUNCTOK failed %d %s", dnssd_errno
, dnssd_strerror(dnssd_errno
));
589 #if !defined(USE_TCP_LOOPBACK) && !defined(USE_NAMED_ERROR_RETURN_SOCKET)
590 // If we're going to make a separate error return socket, and pass it to the daemon
591 // using sendmsg, then we'll hold back one data byte to go with it.
592 // On some versions of Unix (including Leopard) sending a control message without
593 // any associated data does not work reliably -- e.g. one particular issue we ran
594 // into is that if the receiving program is in a kqueue loop waiting to be notified
595 // of the received message, it doesn't get woken up when the control message arrives.
596 if (MakeSeparateReturnSocket
|| sdr
->op
== send_bpf
) datalen
--; // Okay to use sdr->op when checking for op == send_bpf
599 // At this point, our listening socket is set up and waiting, if necessary, for the daemon to connect back to
600 ConvertHeaderBytes(hdr
);
601 //syslog(LOG_WARNING, "dnssd_clientstub deliver_request writing %lu bytes", (unsigned long)(datalen + sizeof(ipc_msg_hdr)));
602 //if (MakeSeparateReturnSocket) syslog(LOG_WARNING, "dnssd_clientstub deliver_request name is %s", data);
603 #if TEST_SENDING_ONE_BYTE_AT_A_TIME
605 for (i
=0; i
<datalen
+ sizeof(ipc_msg_hdr
); i
++)
607 syslog(LOG_WARNING
, "dnssd_clientstub deliver_request writing %d", i
);
608 if (write_all(sdr
->sockfd
, ((char *)hdr
)+i
, 1) < 0)
609 { syslog(LOG_WARNING
, "write_all (byte %u) failed", i
); goto cleanup
; }
613 if (write_all(sdr
->sockfd
, (char *)hdr
, datalen
+ sizeof(ipc_msg_hdr
)) < 0)
615 syslog(LOG_WARNING
, "dnssd_clientstub deliver_request ERROR: write_all(%d, %lu bytes) failed",
616 sdr
->sockfd
, (unsigned long)(datalen
+ sizeof(ipc_msg_hdr
)));
621 if (!MakeSeparateReturnSocket
) errsd
= sdr
->sockfd
;
622 if (MakeSeparateReturnSocket
|| sdr
->op
== send_bpf
) // Okay to use sdr->op when checking for op == send_bpf
624 #if defined(USE_TCP_LOOPBACK) || defined(USE_NAMED_ERROR_RETURN_SOCKET)
625 // At this point we may block in accept for a few milliseconds waiting for the daemon to connect back to us,
626 // but that's okay -- the daemon is a trusted service and we know if won't take more than a few milliseconds to respond.
627 dnssd_sockaddr_t daddr
;
628 dnssd_socklen_t len
= sizeof(daddr
);
629 errsd
= accept(listenfd
, (struct sockaddr
*)&daddr
, &len
);
630 if (!dnssd_SocketValid(errsd
)) deliver_request_bailout("accept");
633 #if APPLE_OSX_mDNSResponder
634 // On Leopard, the stock definitions of the CMSG_* macros in /usr/include/sys/socket.h,
635 // while arguably correct in theory, nonetheless in practice produce code that doesn't work on 64-bit machines
636 // For details see <rdar://problem/5565787> Bonjour API broken for 64-bit apps (SCM_RIGHTS sendmsg fails)
638 #define CMSG_DATA(cmsg) ((unsigned char *)(cmsg) + (sizeof(struct cmsghdr)))
640 #define CMSG_SPACE(l) ((sizeof(struct cmsghdr)) + (l))
642 #define CMSG_LEN(l) ((sizeof(struct cmsghdr)) + (l))
645 struct iovec vec
= { ((char *)hdr
) + sizeof(ipc_msg_hdr
) + datalen
, 1 }; // Send the last byte along with the SCM_RIGHTS
647 struct cmsghdr
*cmsg
;
648 char cbuf
[CMSG_SPACE(sizeof(dnssd_sock_t
))];
650 if (sdr
->op
== send_bpf
) // Okay to use sdr->op when checking for op == send_bpf
653 char p
[12]; // Room for "/dev/bpf999" with terminating null
654 for (i
=0; i
<100; i
++)
656 snprintf(p
, sizeof(p
), "/dev/bpf%d", i
);
657 listenfd
= open(p
, O_RDWR
, 0);
658 //if (dnssd_SocketValid(listenfd)) syslog(LOG_WARNING, "Sending fd %d for %s", listenfd, p);
659 if (!dnssd_SocketValid(listenfd
) && dnssd_errno
!= EBUSY
)
660 syslog(LOG_WARNING
, "Error opening %s %d (%s)", p
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
661 if (dnssd_SocketValid(listenfd
) || dnssd_errno
!= EBUSY
) break;
669 msg
.msg_control
= cbuf
;
670 msg
.msg_controllen
= CMSG_LEN(sizeof(dnssd_sock_t
));
672 cmsg
= CMSG_FIRSTHDR(&msg
);
673 cmsg
->cmsg_len
= CMSG_LEN(sizeof(dnssd_sock_t
));
674 cmsg
->cmsg_level
= SOL_SOCKET
;
675 cmsg
->cmsg_type
= SCM_RIGHTS
;
676 *((dnssd_sock_t
*)CMSG_DATA(cmsg
)) = listenfd
;
678 #if TEST_KQUEUE_CONTROL_MESSAGE_BUG
682 #if DEBUG_64BIT_SCM_RIGHTS
683 syslog(LOG_WARNING
, "dnssd_clientstub sendmsg read sd=%d write sd=%d %ld %ld %ld/%ld/%ld/%ld",
684 errsd
, listenfd
, sizeof(dnssd_sock_t
), sizeof(void*),
685 sizeof(struct cmsghdr
) + sizeof(dnssd_sock_t
),
686 CMSG_LEN(sizeof(dnssd_sock_t
)), (long)CMSG_SPACE(sizeof(dnssd_sock_t
)),
687 (long)((char*)CMSG_DATA(cmsg
) + 4 - cbuf
));
688 #endif // DEBUG_64BIT_SCM_RIGHTS
690 if (sendmsg(sdr
->sockfd
, &msg
, 0) < 0)
692 syslog(LOG_WARNING
, "dnssd_clientstub deliver_request ERROR: sendmsg failed read sd=%d write sd=%d errno %d (%s)",
693 errsd
, listenfd
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
694 err
= kDNSServiceErr_Incompatible
;
698 #if DEBUG_64BIT_SCM_RIGHTS
699 syslog(LOG_WARNING
, "dnssd_clientstub sendmsg read sd=%d write sd=%d okay", errsd
, listenfd
);
700 #endif // DEBUG_64BIT_SCM_RIGHTS
703 // Close our end of the socketpair *before* blocking in read_all to get the four-byte error code.
704 // Otherwise, if the daemon closes our socket (or crashes), we block in read_all() forever
705 // because the socket is not closed (we still have an open reference to it ourselves).
706 dnssd_close(listenfd
);
707 listenfd
= dnssd_InvalidSocket
; // Make sure we don't close it a second time in the cleanup handling below
710 // At this point we may block in read_all for a few milliseconds waiting for the daemon to send us the error code,
711 // but that's okay -- the daemon is a trusted service and we know if won't take more than a few milliseconds to respond.
712 if (sdr
->op
== send_bpf
) // Okay to use sdr->op when checking for op == send_bpf
713 err
= kDNSServiceErr_NoError
;
714 else if (read_all(errsd
, (char*)&err
, (int)sizeof(err
)) < 0)
715 err
= kDNSServiceErr_ServiceNotRunning
; // On failure read_all will have written a message to syslog for us
719 //syslog(LOG_WARNING, "dnssd_clientstub deliver_request: retrieved error code %d", err);
722 if (MakeSeparateReturnSocket
)
724 if (dnssd_SocketValid(listenfd
)) dnssd_close(listenfd
);
725 if (dnssd_SocketValid(errsd
)) dnssd_close(errsd
);
726 #if defined(USE_NAMED_ERROR_RETURN_SOCKET)
727 // syslog(LOG_WARNING, "dnssd_clientstub deliver_request: removing UDS: %s", data);
728 if (unlink(data
) != 0)
729 syslog(LOG_WARNING
, "dnssd_clientstub WARNING: unlink(\"%s\") failed errno %d (%s)", data
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
730 // else syslog(LOG_WARNING, "dnssd_clientstub deliver_request: removed UDS: %s", data);
738 int DNSSD_API
DNSServiceRefSockFD(DNSServiceRef sdRef
)
740 if (!sdRef
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRefSockFD called with NULL DNSServiceRef"); return dnssd_InvalidSocket
; }
742 if (!DNSServiceRefValid(sdRef
))
744 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRefSockFD called with invalid DNSServiceRef %p %08X %08X",
745 sdRef
, sdRef
->sockfd
, sdRef
->validator
);
746 return dnssd_InvalidSocket
;
751 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRefSockFD undefined for kDNSServiceFlagsShareConnection subordinate DNSServiceRef %p", sdRef
);
752 return dnssd_InvalidSocket
;
755 return (int) sdRef
->sockfd
;
758 #if _DNS_SD_LIBDISPATCH
759 static void CallbackWithError(DNSServiceRef sdRef
, DNSServiceErrorType error
)
761 DNSServiceOp
*sdr
= sdRef
;
762 DNSServiceOp
*sdrNext
;
769 // We can't touch the sdr after the callback as it can be deallocated in the callback
772 sdr
->moreptr
= &morebytes
;
775 case resolve_request
:
776 if (sdr
->AppCallback
)((DNSServiceResolveReply
) sdr
->AppCallback
)(sdr
, 0, 0, error
, NULL
, 0, 0, 0, NULL
, sdr
->AppContext
);
779 if (sdr
->AppCallback
)((DNSServiceQueryRecordReply
)sdr
->AppCallback
)(sdr
, 0, 0, error
, NULL
, 0, 0, 0, NULL
, 0, sdr
->AppContext
);
781 case addrinfo_request
:
782 if (sdr
->AppCallback
)((DNSServiceGetAddrInfoReply
)sdr
->AppCallback
)(sdr
, 0, 0, error
, NULL
, NULL
, 0, sdr
->AppContext
);
785 if (sdr
->AppCallback
)((DNSServiceBrowseReply
) sdr
->AppCallback
)(sdr
, 0, 0, error
, NULL
, 0, NULL
, sdr
->AppContext
);
787 case reg_service_request
:
788 if (sdr
->AppCallback
)((DNSServiceRegisterReply
) sdr
->AppCallback
)(sdr
, 0, error
, NULL
, 0, NULL
, sdr
->AppContext
);
790 case enumeration_request
:
791 if (sdr
->AppCallback
)((DNSServiceDomainEnumReply
) sdr
->AppCallback
)(sdr
, 0, 0, error
, NULL
, sdr
->AppContext
);
793 case connection_request
:
794 // This means Register Record, walk the list of DNSRecords to do the callback
798 recnext
= rec
->recnext
;
799 if (rec
->AppCallback
) ((DNSServiceRegisterRecordReply
)rec
->AppCallback
)(sdr
, 0, 0, error
, rec
->AppContext
);
800 // The Callback can call DNSServiceRefDeallocate which in turn frees sdr and all the records.
801 // Detect that and return early
802 if (!morebytes
){syslog(LOG_WARNING
, "dnssdclientstub:Record: CallbackwithError morebytes zero"); return;}
806 case port_mapping_request
:
807 if (sdr
->AppCallback
)((DNSServiceNATPortMappingReply
)sdr
->AppCallback
)(sdr
, 0, 0, error
, 0, 0, 0, 0, 0, sdr
->AppContext
);
810 syslog(LOG_WARNING
, "dnssd_clientstub CallbackWithError called with bad op %d", sdr
->op
);
812 // If DNSServiceRefDeallocate was called in the callback, morebytes will be zero. It means
813 // all other sdrefs have been freed. This happens for shared connections where the
814 // DNSServiceRefDeallocate on the first sdRef frees all other sdrefs.
815 if (!morebytes
){syslog(LOG_WARNING
, "dnssdclientstub:sdRef: CallbackwithError morebytes zero"); return;}
819 #endif // _DNS_SD_LIBDISPATCH
821 // Handle reply from server, calling application client callback. If there is no reply
822 // from the daemon on the socket contained in sdRef, the call will block.
823 DNSServiceErrorType DNSSD_API
DNSServiceProcessResult(DNSServiceRef sdRef
)
827 if (!sdRef
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceProcessResult called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam
; }
829 if (!DNSServiceRefValid(sdRef
))
831 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceProcessResult called with invalid DNSServiceRef %p %08X %08X", sdRef
, sdRef
->sockfd
, sdRef
->validator
);
832 return kDNSServiceErr_BadReference
;
837 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceProcessResult undefined for kDNSServiceFlagsShareConnection subordinate DNSServiceRef %p", sdRef
);
838 return kDNSServiceErr_BadReference
;
841 if (!sdRef
->ProcessReply
)
843 static int num_logs
= 0;
844 if (num_logs
< 10) syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceProcessResult called with DNSServiceRef with no ProcessReply function");
845 if (num_logs
< 1000) num_logs
++; else sleep(1);
846 return kDNSServiceErr_BadReference
;
854 // return NoError on EWOULDBLOCK. This will handle the case
855 // where a non-blocking socket is told there is data, but it was a false positive.
856 // On error, read_all will write a message to syslog for us, so don't need to duplicate that here
857 // Note: If we want to properly support using non-blocking sockets in the future
858 int result
= read_all(sdRef
->sockfd
, (void *)&cbh
.ipc_hdr
, sizeof(cbh
.ipc_hdr
));
859 if (result
== read_all_fail
)
861 // Set the ProcessReply to NULL before callback as the sdRef can get deallocated
863 sdRef
->ProcessReply
= NULL
;
864 #if _DNS_SD_LIBDISPATCH
865 // Call the callbacks with an error if using the dispatch API, as DNSServiceProcessResult
866 // is not called by the application and hence need to communicate the error. Cancel the
867 // source so that we don't get any more events
868 if (sdRef
->disp_source
)
870 dispatch_source_cancel(sdRef
->disp_source
);
871 dispatch_release(sdRef
->disp_source
);
872 sdRef
->disp_source
= NULL
;
873 CallbackWithError(sdRef
, kDNSServiceErr_ServiceNotRunning
);
876 // Don't touch sdRef anymore as it might have been deallocated
877 return kDNSServiceErr_ServiceNotRunning
;
879 else if (result
== read_all_wouldblock
)
881 if (morebytes
&& sdRef
->logcounter
< 100)
884 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceProcessResult error: select indicated data was waiting but read_all returned EWOULDBLOCK");
886 return kDNSServiceErr_NoError
;
889 ConvertHeaderBytes(&cbh
.ipc_hdr
);
890 if (cbh
.ipc_hdr
.version
!= VERSION
)
892 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceProcessResult daemon version %d does not match client version %d", cbh
.ipc_hdr
.version
, VERSION
);
893 sdRef
->ProcessReply
= NULL
;
894 return kDNSServiceErr_Incompatible
;
897 data
= malloc(cbh
.ipc_hdr
.datalen
);
898 if (!data
) return kDNSServiceErr_NoMemory
;
899 if (read_all(sdRef
->sockfd
, data
, cbh
.ipc_hdr
.datalen
) < 0) // On error, read_all will write a message to syslog for us
901 // Set the ProcessReply to NULL before callback as the sdRef can get deallocated
903 sdRef
->ProcessReply
= NULL
;
904 #if _DNS_SD_LIBDISPATCH
905 // Call the callbacks with an error if using the dispatch API, as DNSServiceProcessResult
906 // is not called by the application and hence need to communicate the error. Cancel the
907 // source so that we don't get any more events
908 if (sdRef
->disp_source
)
910 dispatch_source_cancel(sdRef
->disp_source
);
911 dispatch_release(sdRef
->disp_source
);
912 sdRef
->disp_source
= NULL
;
913 CallbackWithError(sdRef
, kDNSServiceErr_ServiceNotRunning
);
916 // Don't touch sdRef anymore as it might have been deallocated
918 return kDNSServiceErr_ServiceNotRunning
;
922 const char *ptr
= data
;
923 cbh
.cb_flags
= get_flags (&ptr
, data
+ cbh
.ipc_hdr
.datalen
);
924 cbh
.cb_interface
= get_uint32 (&ptr
, data
+ cbh
.ipc_hdr
.datalen
);
925 cbh
.cb_err
= get_error_code(&ptr
, data
+ cbh
.ipc_hdr
.datalen
);
927 // CAUTION: We have to handle the case where the client calls DNSServiceRefDeallocate from within the callback function.
928 // To do this we set moreptr to point to morebytes. If the client does call DNSServiceRefDeallocate(),
929 // then that routine will clear morebytes for us, and cause us to exit our loop.
930 morebytes
= more_bytes(sdRef
->sockfd
);
933 cbh
.cb_flags
|= kDNSServiceFlagsMoreComing
;
934 sdRef
->moreptr
= &morebytes
;
936 if (ptr
) sdRef
->ProcessReply(sdRef
, &cbh
, ptr
, data
+ cbh
.ipc_hdr
.datalen
);
937 // Careful code here:
938 // If morebytes is non-zero, that means we set sdRef->moreptr above, and the operation was not
939 // cancelled out from under us, so now we need to clear sdRef->moreptr so we don't leave a stray
940 // dangling pointer pointing to a long-gone stack variable.
941 // If morebytes is zero, then one of two thing happened:
942 // (a) morebytes was 0 above, so we didn't set sdRef->moreptr, so we don't need to clear it
943 // (b) morebytes was 1 above, and we set sdRef->moreptr, but the operation was cancelled (with DNSServiceRefDeallocate()),
944 // so we MUST NOT try to dereference our stale sdRef pointer.
945 if (morebytes
) sdRef
->moreptr
= NULL
;
950 return kDNSServiceErr_NoError
;
953 void DNSSD_API
DNSServiceRefDeallocate(DNSServiceRef sdRef
)
955 if (!sdRef
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRefDeallocate called with NULL DNSServiceRef"); return; }
957 if (!DNSServiceRefValid(sdRef
)) // Also verifies dnssd_SocketValid(sdRef->sockfd) for us too
959 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRefDeallocate called with invalid DNSServiceRef %p %08X %08X", sdRef
, sdRef
->sockfd
, sdRef
->validator
);
963 // 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
964 if (sdRef
->moreptr
) *(sdRef
->moreptr
) = 0;
966 if (sdRef
->primary
) // If this is a subordinate DNSServiceOp, just send a 'stop' command
968 DNSServiceOp
**p
= &sdRef
->primary
->next
;
969 while (*p
&& *p
!= sdRef
) p
= &(*p
)->next
;
974 ipc_msg_hdr
*hdr
= create_hdr(cancel_request
, &len
, &ptr
, 0, sdRef
);
977 ConvertHeaderBytes(hdr
);
978 write_all(sdRef
->sockfd
, (char *)hdr
, len
);
982 FreeDNSServiceOp(sdRef
);
985 else // else, make sure to terminate all subordinates as well
987 #if _DNS_SD_LIBDISPATCH
988 // The cancel handler will close the fd if a dispatch source has been set
989 if (sdRef
->disp_source
)
991 // By setting the ProcessReply to NULL, we make sure that we never call
992 // the application callbacks ever, after returning from this function. We
993 // assume that DNSServiceRefDeallocate is called from the serial queue
994 // that was passed to DNSServiceSetDispatchQueue. Hence, dispatch_source_cancel
995 // should cancel all the blocks on the queue and hence there should be no more
996 // callbacks when we return from this function. Setting ProcessReply to NULL
997 // provides extra protection.
998 sdRef
->ProcessReply
= NULL
;
999 dispatch_source_cancel(sdRef
->disp_source
);
1000 dispatch_release(sdRef
->disp_source
);
1001 sdRef
->disp_source
= NULL
;
1003 // if disp_queue is set, it means it used the DNSServiceSetDispatchQueue API. In that case,
1004 // when the source was cancelled, the fd was closed in the handler. Currently the source
1005 // is cancelled only when the mDNSResponder daemon dies
1006 else if (!sdRef
->disp_queue
) dnssd_close(sdRef
->sockfd
);
1008 dnssd_close(sdRef
->sockfd
);
1010 // Free DNSRecords added in DNSRegisterRecord if they have not
1011 // been freed in DNSRemoveRecord
1014 DNSServiceOp
*p
= sdRef
;
1015 sdRef
= sdRef
->next
;
1016 FreeDNSServiceOp(p
);
1021 DNSServiceErrorType DNSSD_API
DNSServiceGetProperty(const char *property
, void *result
, uint32_t *size
)
1024 size_t len
= strlen(property
) + 1;
1027 uint32_t actualsize
;
1029 DNSServiceErrorType err
= ConnectToServer(&tmp
, 0, getproperty_request
, NULL
, NULL
, NULL
);
1030 if (err
) return err
;
1032 hdr
= create_hdr(getproperty_request
, &len
, &ptr
, 0, tmp
);
1033 if (!hdr
) { DNSServiceRefDeallocate(tmp
); return kDNSServiceErr_NoMemory
; }
1035 put_string(property
, &ptr
);
1036 err
= deliver_request(hdr
, tmp
); // Will free hdr for us
1037 if (read_all(tmp
->sockfd
, (char*)&actualsize
, (int)sizeof(actualsize
)) < 0)
1038 { DNSServiceRefDeallocate(tmp
); return kDNSServiceErr_ServiceNotRunning
; }
1040 actualsize
= ntohl(actualsize
);
1041 if (read_all(tmp
->sockfd
, (char*)result
, actualsize
< *size
? actualsize
: *size
) < 0)
1042 { DNSServiceRefDeallocate(tmp
); return kDNSServiceErr_ServiceNotRunning
; }
1043 DNSServiceRefDeallocate(tmp
);
1045 // Swap version result back to local process byte order
1046 if (!strcmp(property
, kDNSServiceProperty_DaemonVersion
) && *size
>= 4)
1047 *(uint32_t*)result
= ntohl(*(uint32_t*)result
);
1050 return kDNSServiceErr_NoError
;
1053 static void handle_resolve_response(DNSServiceOp
*const sdr
, const CallbackHeader
*const cbh
, const char *data
, const char *end
)
1055 char fullname
[kDNSServiceMaxDomainName
];
1056 char target
[kDNSServiceMaxDomainName
];
1058 union { uint16_t s
; u_char b
[2]; } port
;
1059 unsigned char *txtrecord
;
1061 get_string(&data
, end
, fullname
, kDNSServiceMaxDomainName
);
1062 get_string(&data
, end
, target
, kDNSServiceMaxDomainName
);
1063 if (!data
|| data
+ 2 > end
) goto fail
;
1065 port
.b
[0] = *data
++;
1066 port
.b
[1] = *data
++;
1067 txtlen
= get_uint16(&data
, end
);
1068 txtrecord
= (unsigned char *)get_rdata(&data
, end
, txtlen
);
1070 if (!data
) goto fail
;
1071 ((DNSServiceResolveReply
)sdr
->AppCallback
)(sdr
, cbh
->cb_flags
, cbh
->cb_interface
, cbh
->cb_err
, fullname
, target
, port
.s
, txtlen
, txtrecord
, sdr
->AppContext
);
1073 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1075 syslog(LOG_WARNING
, "dnssd_clientstub handle_resolve_response: error reading result from daemon");
1078 DNSServiceErrorType DNSSD_API DNSServiceResolve
1080 DNSServiceRef
*sdRef
,
1081 DNSServiceFlags flags
,
1082 uint32_t interfaceIndex
,
1084 const char *regtype
,
1086 DNSServiceResolveReply callBack
,
1093 DNSServiceErrorType err
;
1095 if (!name
|| !regtype
|| !domain
|| !callBack
) return kDNSServiceErr_BadParam
;
1097 err
= ConnectToServer(sdRef
, flags
, resolve_request
, handle_resolve_response
, callBack
, context
);
1098 if (err
) return err
; // On error ConnectToServer leaves *sdRef set to NULL
1100 // Calculate total message length
1101 len
= sizeof(flags
);
1102 len
+= sizeof(interfaceIndex
);
1103 len
+= strlen(name
) + 1;
1104 len
+= strlen(regtype
) + 1;
1105 len
+= strlen(domain
) + 1;
1107 hdr
= create_hdr(resolve_request
, &len
, &ptr
, (*sdRef
)->primary
? 1 : 0, *sdRef
);
1108 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
1110 put_flags(flags
, &ptr
);
1111 put_uint32(interfaceIndex
, &ptr
);
1112 put_string(name
, &ptr
);
1113 put_string(regtype
, &ptr
);
1114 put_string(domain
, &ptr
);
1116 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1117 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
1121 static void handle_query_response(DNSServiceOp
*const sdr
, const CallbackHeader
*const cbh
, const char *data
, const char *const end
)
1124 char name
[kDNSServiceMaxDomainName
];
1125 uint16_t rrtype
, rrclass
, rdlen
;
1128 get_string(&data
, end
, name
, kDNSServiceMaxDomainName
);
1129 rrtype
= get_uint16(&data
, end
);
1130 rrclass
= get_uint16(&data
, end
);
1131 rdlen
= get_uint16(&data
, end
);
1132 rdata
= get_rdata(&data
, end
, rdlen
);
1133 ttl
= get_uint32(&data
, end
);
1135 if (!data
) syslog(LOG_WARNING
, "dnssd_clientstub handle_query_response: error reading result from daemon");
1136 else ((DNSServiceQueryRecordReply
)sdr
->AppCallback
)(sdr
, cbh
->cb_flags
, cbh
->cb_interface
, cbh
->cb_err
, name
, rrtype
, rrclass
, rdlen
, rdata
, ttl
, sdr
->AppContext
);
1137 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1140 DNSServiceErrorType DNSSD_API DNSServiceQueryRecord
1142 DNSServiceRef
*sdRef
,
1143 DNSServiceFlags flags
,
1144 uint32_t interfaceIndex
,
1148 DNSServiceQueryRecordReply callBack
,
1155 DNSServiceErrorType err
= ConnectToServer(sdRef
, flags
, query_request
, handle_query_response
, callBack
, context
);
1156 if (err
) return err
; // On error ConnectToServer leaves *sdRef set to NULL
1158 if (!name
) name
= "\0";
1160 // Calculate total message length
1161 len
= sizeof(flags
);
1162 len
+= sizeof(uint32_t); // interfaceIndex
1163 len
+= strlen(name
) + 1;
1164 len
+= 2 * sizeof(uint16_t); // rrtype, rrclass
1166 hdr
= create_hdr(query_request
, &len
, &ptr
, (*sdRef
)->primary
? 1 : 0, *sdRef
);
1167 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
1169 put_flags(flags
, &ptr
);
1170 put_uint32(interfaceIndex
, &ptr
);
1171 put_string(name
, &ptr
);
1172 put_uint16(rrtype
, &ptr
);
1173 put_uint16(rrclass
, &ptr
);
1175 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1176 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
1180 static void handle_addrinfo_response(DNSServiceOp
*const sdr
, const CallbackHeader
*const cbh
, const char *data
, const char *const end
)
1182 char hostname
[kDNSServiceMaxDomainName
];
1183 uint16_t rrtype
, rrclass
, rdlen
;
1187 get_string(&data
, end
, hostname
, kDNSServiceMaxDomainName
);
1188 rrtype
= get_uint16(&data
, end
);
1189 rrclass
= get_uint16(&data
, end
);
1190 rdlen
= get_uint16(&data
, end
);
1191 rdata
= get_rdata (&data
, end
, rdlen
);
1192 ttl
= get_uint32(&data
, end
);
1194 // We only generate client callbacks for A and AAAA results (including NXDOMAIN results for
1195 // those types, if the client has requested those with the kDNSServiceFlagsReturnIntermediates).
1196 // Other result types, specifically CNAME referrals, are not communicated to the client, because
1197 // the DNSServiceGetAddrInfoReply interface doesn't have any meaningful way to communiate CNAME referrals.
1198 if (!data
) syslog(LOG_WARNING
, "dnssd_clientstub handle_addrinfo_response: error reading result from daemon");
1199 else if (rrtype
== kDNSServiceType_A
|| rrtype
== kDNSServiceType_AAAA
)
1201 struct sockaddr_in sa4
;
1202 struct sockaddr_in6 sa6
;
1203 const struct sockaddr
*const sa
= (rrtype
== kDNSServiceType_A
) ? (struct sockaddr
*)&sa4
: (struct sockaddr
*)&sa6
;
1204 if (rrtype
== kDNSServiceType_A
)
1206 memset(&sa4
, 0, sizeof(sa4
));
1207 #ifndef NOT_HAVE_SA_LEN
1208 sa4
.sin_len
= sizeof(struct sockaddr_in
);
1210 sa4
.sin_family
= AF_INET
;
1212 if (!cbh
->cb_err
) memcpy(&sa4
.sin_addr
, rdata
, rdlen
);
1216 memset(&sa6
, 0, sizeof(sa6
));
1217 #ifndef NOT_HAVE_SA_LEN
1218 sa6
.sin6_len
= sizeof(struct sockaddr_in6
);
1220 sa6
.sin6_family
= AF_INET6
;
1222 // sin6_flowinfo = 0;
1223 // sin6_scope_id = 0;
1226 memcpy(&sa6
.sin6_addr
, rdata
, rdlen
);
1227 if (IN6_IS_ADDR_LINKLOCAL(&sa6
.sin6_addr
)) sa6
.sin6_scope_id
= cbh
->cb_interface
;
1230 ((DNSServiceGetAddrInfoReply
)sdr
->AppCallback
)(sdr
, cbh
->cb_flags
, cbh
->cb_interface
, cbh
->cb_err
, hostname
, sa
, ttl
, sdr
->AppContext
);
1231 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1235 DNSServiceErrorType DNSSD_API DNSServiceGetAddrInfo
1237 DNSServiceRef
*sdRef
,
1238 DNSServiceFlags flags
,
1239 uint32_t interfaceIndex
,
1241 const char *hostname
,
1242 DNSServiceGetAddrInfoReply callBack
,
1243 void *context
/* may be NULL */
1249 DNSServiceErrorType err
;
1251 if (!hostname
) return kDNSServiceErr_BadParam
;
1253 err
= ConnectToServer(sdRef
, flags
, addrinfo_request
, handle_addrinfo_response
, callBack
, context
);
1254 if (err
) return err
; // On error ConnectToServer leaves *sdRef set to NULL
1256 // Calculate total message length
1257 len
= sizeof(flags
);
1258 len
+= sizeof(uint32_t); // interfaceIndex
1259 len
+= sizeof(uint32_t); // protocol
1260 len
+= strlen(hostname
) + 1;
1262 hdr
= create_hdr(addrinfo_request
, &len
, &ptr
, (*sdRef
)->primary
? 1 : 0, *sdRef
);
1263 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
1265 put_flags(flags
, &ptr
);
1266 put_uint32(interfaceIndex
, &ptr
);
1267 put_uint32(protocol
, &ptr
);
1268 put_string(hostname
, &ptr
);
1270 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1271 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
1275 static void handle_browse_response(DNSServiceOp
*const sdr
, const CallbackHeader
*const cbh
, const char *data
, const char *const end
)
1277 char replyName
[256], replyType
[kDNSServiceMaxDomainName
], replyDomain
[kDNSServiceMaxDomainName
];
1278 get_string(&data
, end
, replyName
, 256);
1279 get_string(&data
, end
, replyType
, kDNSServiceMaxDomainName
);
1280 get_string(&data
, end
, replyDomain
, kDNSServiceMaxDomainName
);
1281 if (!data
) syslog(LOG_WARNING
, "dnssd_clientstub handle_browse_response: error reading result from daemon");
1282 else ((DNSServiceBrowseReply
)sdr
->AppCallback
)(sdr
, cbh
->cb_flags
, cbh
->cb_interface
, cbh
->cb_err
, replyName
, replyType
, replyDomain
, sdr
->AppContext
);
1283 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1286 DNSServiceErrorType DNSSD_API DNSServiceBrowse
1288 DNSServiceRef
*sdRef
,
1289 DNSServiceFlags flags
,
1290 uint32_t interfaceIndex
,
1291 const char *regtype
,
1293 DNSServiceBrowseReply callBack
,
1300 DNSServiceErrorType err
= ConnectToServer(sdRef
, flags
, browse_request
, handle_browse_response
, callBack
, context
);
1301 if (err
) return err
; // On error ConnectToServer leaves *sdRef set to NULL
1303 if (!domain
) domain
= "";
1304 len
= sizeof(flags
);
1305 len
+= sizeof(interfaceIndex
);
1306 len
+= strlen(regtype
) + 1;
1307 len
+= strlen(domain
) + 1;
1309 hdr
= create_hdr(browse_request
, &len
, &ptr
, (*sdRef
)->primary
? 1 : 0, *sdRef
);
1310 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
1312 put_flags(flags
, &ptr
);
1313 put_uint32(interfaceIndex
, &ptr
);
1314 put_string(regtype
, &ptr
);
1315 put_string(domain
, &ptr
);
1317 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1318 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
1322 DNSServiceErrorType DNSSD_API
DNSServiceSetDefaultDomainForUser(DNSServiceFlags flags
, const char *domain
);
1323 DNSServiceErrorType DNSSD_API
DNSServiceSetDefaultDomainForUser(DNSServiceFlags flags
, const char *domain
)
1327 size_t len
= sizeof(flags
) + strlen(domain
) + 1;
1329 DNSServiceErrorType err
= ConnectToServer(&tmp
, 0, setdomain_request
, NULL
, NULL
, NULL
);
1330 if (err
) return err
;
1332 hdr
= create_hdr(setdomain_request
, &len
, &ptr
, 0, tmp
);
1333 if (!hdr
) { DNSServiceRefDeallocate(tmp
); return kDNSServiceErr_NoMemory
; }
1335 put_flags(flags
, &ptr
);
1336 put_string(domain
, &ptr
);
1337 err
= deliver_request(hdr
, tmp
); // Will free hdr for us
1338 DNSServiceRefDeallocate(tmp
);
1342 static void handle_regservice_response(DNSServiceOp
*const sdr
, const CallbackHeader
*const cbh
, const char *data
, const char *const end
)
1344 char name
[256], regtype
[kDNSServiceMaxDomainName
], domain
[kDNSServiceMaxDomainName
];
1345 get_string(&data
, end
, name
, 256);
1346 get_string(&data
, end
, regtype
, kDNSServiceMaxDomainName
);
1347 get_string(&data
, end
, domain
, kDNSServiceMaxDomainName
);
1348 if (!data
) syslog(LOG_WARNING
, "dnssd_clientstub handle_regservice_response: error reading result from daemon");
1349 else ((DNSServiceRegisterReply
)sdr
->AppCallback
)(sdr
, cbh
->cb_flags
, cbh
->cb_err
, name
, regtype
, domain
, sdr
->AppContext
);
1350 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1353 DNSServiceErrorType DNSSD_API DNSServiceRegister
1355 DNSServiceRef
*sdRef
,
1356 DNSServiceFlags flags
,
1357 uint32_t interfaceIndex
,
1359 const char *regtype
,
1362 uint16_t PortInNetworkByteOrder
,
1364 const void *txtRecord
,
1365 DNSServiceRegisterReply callBack
,
1372 DNSServiceErrorType err
;
1373 union { uint16_t s
; u_char b
[2]; } port
= { PortInNetworkByteOrder
};
1375 if (!name
) name
= "";
1376 if (!regtype
) return kDNSServiceErr_BadParam
;
1377 if (!domain
) domain
= "";
1378 if (!host
) host
= "";
1379 if (!txtRecord
) txtRecord
= (void*)"";
1381 // No callback must have auto-rename
1382 if (!callBack
&& (flags
& kDNSServiceFlagsNoAutoRename
)) return kDNSServiceErr_BadParam
;
1384 err
= ConnectToServer(sdRef
, flags
, reg_service_request
, callBack
? handle_regservice_response
: NULL
, callBack
, context
);
1385 if (err
) return err
; // On error ConnectToServer leaves *sdRef set to NULL
1387 len
= sizeof(DNSServiceFlags
);
1388 len
+= sizeof(uint32_t); // interfaceIndex
1389 len
+= strlen(name
) + strlen(regtype
) + strlen(domain
) + strlen(host
) + 4;
1390 len
+= 2 * sizeof(uint16_t); // port, txtLen
1393 hdr
= create_hdr(reg_service_request
, &len
, &ptr
, (*sdRef
)->primary
? 1 : 0, *sdRef
);
1394 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
1395 if (!callBack
) hdr
->ipc_flags
|= IPC_FLAGS_NOREPLY
;
1397 put_flags(flags
, &ptr
);
1398 put_uint32(interfaceIndex
, &ptr
);
1399 put_string(name
, &ptr
);
1400 put_string(regtype
, &ptr
);
1401 put_string(domain
, &ptr
);
1402 put_string(host
, &ptr
);
1405 put_uint16(txtLen
, &ptr
);
1406 put_rdata(txtLen
, txtRecord
, &ptr
);
1408 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1409 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
1413 static void handle_enumeration_response(DNSServiceOp
*const sdr
, const CallbackHeader
*const cbh
, const char *data
, const char *const end
)
1415 char domain
[kDNSServiceMaxDomainName
];
1416 get_string(&data
, end
, domain
, kDNSServiceMaxDomainName
);
1417 if (!data
) syslog(LOG_WARNING
, "dnssd_clientstub handle_enumeration_response: error reading result from daemon");
1418 else ((DNSServiceDomainEnumReply
)sdr
->AppCallback
)(sdr
, cbh
->cb_flags
, cbh
->cb_interface
, cbh
->cb_err
, domain
, sdr
->AppContext
);
1419 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1422 DNSServiceErrorType DNSSD_API DNSServiceEnumerateDomains
1424 DNSServiceRef
*sdRef
,
1425 DNSServiceFlags flags
,
1426 uint32_t interfaceIndex
,
1427 DNSServiceDomainEnumReply callBack
,
1434 DNSServiceErrorType err
;
1436 int f1
= (flags
& kDNSServiceFlagsBrowseDomains
) != 0;
1437 int f2
= (flags
& kDNSServiceFlagsRegistrationDomains
) != 0;
1438 if (f1
+ f2
!= 1) return kDNSServiceErr_BadParam
;
1440 err
= ConnectToServer(sdRef
, flags
, enumeration_request
, handle_enumeration_response
, callBack
, context
);
1441 if (err
) return err
; // On error ConnectToServer leaves *sdRef set to NULL
1443 len
= sizeof(DNSServiceFlags
);
1444 len
+= sizeof(uint32_t);
1446 hdr
= create_hdr(enumeration_request
, &len
, &ptr
, (*sdRef
)->primary
? 1 : 0, *sdRef
);
1447 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
1449 put_flags(flags
, &ptr
);
1450 put_uint32(interfaceIndex
, &ptr
);
1452 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1453 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
1457 static void ConnectionResponse(DNSServiceOp
*const sdr
, const CallbackHeader
*const cbh
, const char *const data
, const char *const end
)
1459 DNSRecordRef rref
= cbh
->ipc_hdr
.client_context
.context
;
1460 (void)data
; // Unused
1462 //printf("ConnectionResponse got %d\n", cbh->ipc_hdr.op);
1463 if (cbh
->ipc_hdr
.op
!= reg_record_reply_op
)
1465 // When using kDNSServiceFlagsShareConnection, need to search the list of associated DNSServiceOps
1466 // to find the one this response is intended for, and then call through to its ProcessReply handler.
1467 // We start with our first subordinate DNSServiceRef -- don't want to accidentally match the parent DNSServiceRef.
1468 DNSServiceOp
*op
= sdr
->next
;
1469 while (op
&& (op
->uid
.u32
[0] != cbh
->ipc_hdr
.client_context
.u32
[0] || op
->uid
.u32
[1] != cbh
->ipc_hdr
.client_context
.u32
[1]))
1471 // Note: We may sometimes not find a matching DNSServiceOp, in the case where the client has
1472 // cancelled the subordinate DNSServiceOp, but there are still messages in the pipeline from the daemon
1473 if (op
&& op
->ProcessReply
) op
->ProcessReply(op
, cbh
, data
, end
);
1474 // WARNING: Don't touch op or sdr after this -- client may have called DNSServiceRefDeallocate
1478 if (sdr
->op
== connection_request
)
1479 rref
->AppCallback(rref
->sdr
, rref
, cbh
->cb_flags
, cbh
->cb_err
, rref
->AppContext
);
1482 syslog(LOG_WARNING
, "dnssd_clientstub ConnectionResponse: sdr->op != connection_request");
1483 rref
->AppCallback(rref
->sdr
, rref
, 0, kDNSServiceErr_Unknown
, rref
->AppContext
);
1485 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1488 DNSServiceErrorType DNSSD_API
DNSServiceCreateConnection(DNSServiceRef
*sdRef
)
1493 DNSServiceErrorType err
= ConnectToServer(sdRef
, 0, connection_request
, ConnectionResponse
, NULL
, NULL
);
1494 if (err
) return err
; // On error ConnectToServer leaves *sdRef set to NULL
1496 hdr
= create_hdr(connection_request
, &len
, &ptr
, 0, *sdRef
);
1497 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
1499 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1500 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
1504 DNSServiceErrorType DNSSD_API DNSServiceRegisterRecord
1506 DNSServiceRef sdRef
,
1507 DNSRecordRef
*RecordRef
,
1508 DNSServiceFlags flags
,
1509 uint32_t interfaceIndex
,
1510 const char *fullname
,
1516 DNSServiceRegisterRecordReply callBack
,
1522 ipc_msg_hdr
*hdr
= NULL
;
1523 DNSRecordRef rref
= NULL
;
1525 int f1
= (flags
& kDNSServiceFlagsShared
) != 0;
1526 int f2
= (flags
& kDNSServiceFlagsUnique
) != 0;
1527 if (f1
+ f2
!= 1) return kDNSServiceErr_BadParam
;
1529 if (!sdRef
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRegisterRecord called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam
; }
1531 if (!DNSServiceRefValid(sdRef
))
1533 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRegisterRecord called with invalid DNSServiceRef %p %08X %08X", sdRef
, sdRef
->sockfd
, sdRef
->validator
);
1534 return kDNSServiceErr_BadReference
;
1537 if (sdRef
->op
!= connection_request
)
1539 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRegisterRecord called with non-DNSServiceCreateConnection DNSServiceRef %p %d", sdRef
, sdRef
->op
);
1540 return kDNSServiceErr_BadReference
;
1545 len
= sizeof(DNSServiceFlags
);
1546 len
+= 2 * sizeof(uint32_t); // interfaceIndex, ttl
1547 len
+= 3 * sizeof(uint16_t); // rrtype, rrclass, rdlen
1548 len
+= strlen(fullname
) + 1;
1551 hdr
= create_hdr(reg_record_request
, &len
, &ptr
, 1, sdRef
);
1552 if (!hdr
) return kDNSServiceErr_NoMemory
;
1554 put_flags(flags
, &ptr
);
1555 put_uint32(interfaceIndex
, &ptr
);
1556 put_string(fullname
, &ptr
);
1557 put_uint16(rrtype
, &ptr
);
1558 put_uint16(rrclass
, &ptr
);
1559 put_uint16(rdlen
, &ptr
);
1560 put_rdata(rdlen
, rdata
, &ptr
);
1561 put_uint32(ttl
, &ptr
);
1563 rref
= malloc(sizeof(DNSRecord
));
1564 if (!rref
) { free(hdr
); return kDNSServiceErr_NoMemory
; }
1565 rref
->AppContext
= context
;
1566 rref
->AppCallback
= callBack
;
1567 rref
->record_index
= sdRef
->max_index
++;
1569 rref
->recnext
= NULL
;
1571 hdr
->client_context
.context
= rref
;
1572 hdr
->reg_index
= rref
->record_index
;
1575 while (*p
) p
= &(*p
)->recnext
;
1578 return deliver_request(hdr
, sdRef
); // Will free hdr for us
1581 // sdRef returned by DNSServiceRegister()
1582 DNSServiceErrorType DNSSD_API DNSServiceAddRecord
1584 DNSServiceRef sdRef
,
1585 DNSRecordRef
*RecordRef
,
1586 DNSServiceFlags flags
,
1599 if (!sdRef
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceAddRecord called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam
; }
1600 if (!RecordRef
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceAddRecord called with NULL DNSRecordRef pointer"); return kDNSServiceErr_BadParam
; }
1601 if (sdRef
->op
!= reg_service_request
)
1603 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceAddRecord called with non-DNSServiceRegister DNSServiceRef %p %d", sdRef
, sdRef
->op
);
1604 return kDNSServiceErr_BadReference
;
1607 if (!DNSServiceRefValid(sdRef
))
1609 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceAddRecord called with invalid DNSServiceRef %p %08X %08X", sdRef
, sdRef
->sockfd
, sdRef
->validator
);
1610 return kDNSServiceErr_BadReference
;
1615 len
+= 2 * sizeof(uint16_t); // rrtype, rdlen
1617 len
+= sizeof(uint32_t);
1618 len
+= sizeof(DNSServiceFlags
);
1620 hdr
= create_hdr(add_record_request
, &len
, &ptr
, 1, sdRef
);
1621 if (!hdr
) return kDNSServiceErr_NoMemory
;
1622 put_flags(flags
, &ptr
);
1623 put_uint16(rrtype
, &ptr
);
1624 put_uint16(rdlen
, &ptr
);
1625 put_rdata(rdlen
, rdata
, &ptr
);
1626 put_uint32(ttl
, &ptr
);
1628 rref
= malloc(sizeof(DNSRecord
));
1629 if (!rref
) { free(hdr
); return kDNSServiceErr_NoMemory
; }
1630 rref
->AppContext
= NULL
;
1631 rref
->AppCallback
= NULL
;
1632 rref
->record_index
= sdRef
->max_index
++;
1634 rref
->recnext
= NULL
;
1636 hdr
->reg_index
= rref
->record_index
;
1639 while (*p
) p
= &(*p
)->recnext
;
1642 return deliver_request(hdr
, sdRef
); // Will free hdr for us
1645 // DNSRecordRef returned by DNSServiceRegisterRecord or DNSServiceAddRecord
1646 DNSServiceErrorType DNSSD_API DNSServiceUpdateRecord
1648 DNSServiceRef sdRef
,
1649 DNSRecordRef RecordRef
,
1650 DNSServiceFlags flags
,
1660 if (!sdRef
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceUpdateRecord called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam
; }
1662 if (!DNSServiceRefValid(sdRef
))
1664 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceUpdateRecord called with invalid DNSServiceRef %p %08X %08X", sdRef
, sdRef
->sockfd
, sdRef
->validator
);
1665 return kDNSServiceErr_BadReference
;
1668 // Note: RecordRef is allowed to be NULL
1670 len
+= sizeof(uint16_t);
1672 len
+= sizeof(uint32_t);
1673 len
+= sizeof(DNSServiceFlags
);
1675 hdr
= create_hdr(update_record_request
, &len
, &ptr
, 1, sdRef
);
1676 if (!hdr
) return kDNSServiceErr_NoMemory
;
1677 hdr
->reg_index
= RecordRef
? RecordRef
->record_index
: TXT_RECORD_INDEX
;
1678 put_flags(flags
, &ptr
);
1679 put_uint16(rdlen
, &ptr
);
1680 put_rdata(rdlen
, rdata
, &ptr
);
1681 put_uint32(ttl
, &ptr
);
1682 return deliver_request(hdr
, sdRef
); // Will free hdr for us
1685 DNSServiceErrorType DNSSD_API DNSServiceRemoveRecord
1687 DNSServiceRef sdRef
,
1688 DNSRecordRef RecordRef
,
1689 DNSServiceFlags flags
1695 DNSServiceErrorType err
;
1697 if (!sdRef
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRemoveRecord called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam
; }
1698 if (!RecordRef
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRemoveRecord called with NULL DNSRecordRef"); return kDNSServiceErr_BadParam
; }
1699 if (!sdRef
->max_index
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRemoveRecord called with bad DNSServiceRef"); return kDNSServiceErr_BadReference
; }
1701 if (!DNSServiceRefValid(sdRef
))
1703 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRemoveRecord called with invalid DNSServiceRef %p %08X %08X", sdRef
, sdRef
->sockfd
, sdRef
->validator
);
1704 return kDNSServiceErr_BadReference
;
1707 len
+= sizeof(flags
);
1708 hdr
= create_hdr(remove_record_request
, &len
, &ptr
, 1, sdRef
);
1709 if (!hdr
) return kDNSServiceErr_NoMemory
;
1710 hdr
->reg_index
= RecordRef
->record_index
;
1711 put_flags(flags
, &ptr
);
1712 err
= deliver_request(hdr
, sdRef
); // Will free hdr for us
1715 // This RecordRef could have been allocated in DNSServiceRegisterRecord or DNSServiceAddRecord.
1716 // If so, delink from the list before freeing
1717 DNSRecord
**p
= &sdRef
->rec
;
1718 while (*p
&& *p
!= RecordRef
) p
= &(*p
)->recnext
;
1719 if (*p
) *p
= RecordRef
->recnext
;
1725 DNSServiceErrorType DNSSD_API DNSServiceReconfirmRecord
1727 DNSServiceFlags flags
,
1728 uint32_t interfaceIndex
,
1729 const char *fullname
,
1741 DNSServiceErrorType err
= ConnectToServer(&tmp
, flags
, reconfirm_record_request
, NULL
, NULL
, NULL
);
1742 if (err
) return err
;
1744 len
= sizeof(DNSServiceFlags
);
1745 len
+= sizeof(uint32_t);
1746 len
+= strlen(fullname
) + 1;
1747 len
+= 3 * sizeof(uint16_t);
1749 hdr
= create_hdr(reconfirm_record_request
, &len
, &ptr
, 0, tmp
);
1750 if (!hdr
) { DNSServiceRefDeallocate(tmp
); return kDNSServiceErr_NoMemory
; }
1752 put_flags(flags
, &ptr
);
1753 put_uint32(interfaceIndex
, &ptr
);
1754 put_string(fullname
, &ptr
);
1755 put_uint16(rrtype
, &ptr
);
1756 put_uint16(rrclass
, &ptr
);
1757 put_uint16(rdlen
, &ptr
);
1758 put_rdata(rdlen
, rdata
, &ptr
);
1760 err
= deliver_request(hdr
, tmp
); // Will free hdr for us
1761 DNSServiceRefDeallocate(tmp
);
1765 static void handle_port_mapping_response(DNSServiceOp
*const sdr
, const CallbackHeader
*const cbh
, const char *data
, const char *const end
)
1767 union { uint32_t l
; u_char b
[4]; } addr
;
1769 union { uint16_t s
; u_char b
[2]; } internalPort
;
1770 union { uint16_t s
; u_char b
[2]; } externalPort
;
1773 if (!data
|| data
+ 13 > end
) goto fail
;
1775 addr
.b
[0] = *data
++;
1776 addr
.b
[1] = *data
++;
1777 addr
.b
[2] = *data
++;
1778 addr
.b
[3] = *data
++;
1780 internalPort
.b
[0] = *data
++;
1781 internalPort
.b
[1] = *data
++;
1782 externalPort
.b
[0] = *data
++;
1783 externalPort
.b
[1] = *data
++;
1784 ttl
= get_uint32(&data
, end
);
1785 if (!data
) goto fail
;
1787 ((DNSServiceNATPortMappingReply
)sdr
->AppCallback
)(sdr
, cbh
->cb_flags
, cbh
->cb_interface
, cbh
->cb_err
, addr
.l
, protocol
, internalPort
.s
, externalPort
.s
, ttl
, sdr
->AppContext
);
1789 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1792 syslog(LOG_WARNING
, "dnssd_clientstub handle_port_mapping_response: error reading result from daemon");
1795 DNSServiceErrorType DNSSD_API DNSServiceNATPortMappingCreate
1797 DNSServiceRef
*sdRef
,
1798 DNSServiceFlags flags
,
1799 uint32_t interfaceIndex
,
1800 uint32_t protocol
, /* TCP and/or UDP */
1801 uint16_t internalPortInNetworkByteOrder
,
1802 uint16_t externalPortInNetworkByteOrder
,
1803 uint32_t ttl
, /* time to live in seconds */
1804 DNSServiceNATPortMappingReply callBack
,
1805 void *context
/* may be NULL */
1811 union { uint16_t s
; u_char b
[2]; } internalPort
= { internalPortInNetworkByteOrder
};
1812 union { uint16_t s
; u_char b
[2]; } externalPort
= { externalPortInNetworkByteOrder
};
1814 DNSServiceErrorType err
= ConnectToServer(sdRef
, flags
, port_mapping_request
, handle_port_mapping_response
, callBack
, context
);
1815 if (err
) return err
; // On error ConnectToServer leaves *sdRef set to NULL
1817 len
= sizeof(flags
);
1818 len
+= sizeof(interfaceIndex
);
1819 len
+= sizeof(protocol
);
1820 len
+= sizeof(internalPort
);
1821 len
+= sizeof(externalPort
);
1824 hdr
= create_hdr(port_mapping_request
, &len
, &ptr
, (*sdRef
)->primary
? 1 : 0, *sdRef
);
1825 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
1827 put_flags(flags
, &ptr
);
1828 put_uint32(interfaceIndex
, &ptr
);
1829 put_uint32(protocol
, &ptr
);
1830 *ptr
++ = internalPort
.b
[0];
1831 *ptr
++ = internalPort
.b
[1];
1832 *ptr
++ = externalPort
.b
[0];
1833 *ptr
++ = externalPort
.b
[1];
1834 put_uint32(ttl
, &ptr
);
1836 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1837 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
1841 #if _DNS_SD_LIBDISPATCH
1842 DNSServiceErrorType DNSSD_API DNSServiceSetDispatchQueue
1844 DNSServiceRef service
,
1845 dispatch_queue_t queue
1848 int dnssd_fd
= DNSServiceRefSockFD(service
);
1849 if (dnssd_fd
== dnssd_InvalidSocket
) return kDNSServiceErr_BadParam
;
1852 syslog(LOG_WARNING
, "dnssd_clientstub: DNSServiceSetDispatchQueue dispatch queue NULL");
1853 return kDNSServiceErr_BadParam
;
1855 if (service
->disp_queue
)
1857 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceSetDispatchQueue dispatch queue set already");
1858 return kDNSServiceErr_BadParam
;
1860 if (service
->disp_source
)
1862 syslog(LOG_WARNING
, "DNSServiceSetDispatchQueue dispatch source set already");
1863 return kDNSServiceErr_BadParam
;
1865 service
->disp_source
= dispatch_source_create(DISPATCH_SOURCE_TYPE_READ
, dnssd_fd
, 0, queue
);
1866 if (!service
->disp_source
)
1868 syslog(LOG_WARNING
, "DNSServiceSetDispatchQueue dispatch_source_create failed");
1869 return kDNSServiceErr_NoMemory
;
1871 service
->disp_queue
= queue
;
1872 dispatch_source_set_event_handler(service
->disp_source
, ^{DNSServiceProcessResult(service
);});
1873 dispatch_source_set_cancel_handler(service
->disp_source
, ^{dnssd_close(dnssd_fd
);});
1874 dispatch_resume(service
->disp_source
);
1875 return kDNSServiceErr_NoError
;
1877 #endif // _DNS_SD_LIBDISPATCH