1 /* -*- Mode: C; tab-width: 4 -*-
3 * Copyright (c) 2003-2004, Apple Computer, Inc. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of its
14 * contributors may be used to endorse or promote products derived from this
15 * software without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
18 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
21 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
24 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
26 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 #if APPLE_OSX_mDNSResponder
33 #include <mach-o/dyld.h>
36 #include "dnssd_ipc.h"
38 static int gDaemonErr
= kDNSServiceErr_NoError
;
43 #include <CommonServices.h>
44 #include <DebugServices.h>
51 #define sockaddr_mdns sockaddr_in
52 #define AF_MDNS AF_INET
54 // Disable warning: "'type cast' : from data pointer 'void *' to function pointer"
55 #pragma warning(disable:4055)
57 // Disable warning: "nonstandard extension, function/data pointer conversion in expression"
58 #pragma warning(disable:4152)
60 extern BOOL
IsSystemServiceDisabled();
62 #define sleep(X) Sleep((X) * 1000)
64 static int g_initWinsock
= 0;
65 #define LOG_WARNING kDebugLevelWarning
66 #define LOG_INFO kDebugLevelInfo
67 static void syslog( int priority
, const char * message
, ...)
72 DWORD err
= WSAGetLastError();
74 va_start( args
, message
);
75 len
= _vscprintf( message
, args
) + 1;
76 buffer
= malloc( len
* sizeof(char) );
77 if ( buffer
) { vsprintf( buffer
, message
, args
); OutputDebugString( buffer
); free( buffer
); }
78 WSASetLastError( err
);
82 #include <sys/fcntl.h> // For O_RDWR etc.
84 #include <sys/socket.h>
87 #define sockaddr_mdns sockaddr_un
88 #define AF_MDNS AF_LOCAL
92 // <rdar://problem/4096913> Specifies how many times we'll try and connect to the server.
94 #define DNSSD_CLIENT_MAXTRIES 4
96 // Uncomment the line below to use the old error return mechanism of creating a temporary named socket (e.g. in /var/tmp)
97 //#define USE_NAMED_ERROR_RETURN_SOCKET 1
99 #define DNSSD_CLIENT_TIMEOUT 10 // In seconds
101 #ifndef CTL_PATH_PREFIX
102 #define CTL_PATH_PREFIX "/var/tmp/dnssd_result_socket."
108 DNSServiceFlags cb_flags
;
109 uint32_t cb_interface
;
110 DNSServiceErrorType cb_err
;
113 typedef struct _DNSServiceRef_t DNSServiceOp
;
114 typedef struct _DNSRecordRef_t DNSRecord
;
119 void *AppCallback
; // Client callback function and context
124 // client stub callback to process message from server and deliver results to client application
125 typedef void (*ProcessReplyFn
)(DNSServiceOp
*const sdr
, const CallbackHeader
*const cbh
, const char *msg
, const char *const end
);
127 #define ValidatorBits 0x12345678
128 #define DNSServiceRefValid(X) (dnssd_SocketValid((X)->sockfd) && (((X)->sockfd ^ (X)->validator) == ValidatorBits))
130 // When using kDNSServiceFlagsShareConnection, there is one primary _DNSServiceOp_t, and zero or more subordinates
131 // For the primary, the 'next' field points to the first subordinate, and its 'next' field points to the next, and so on.
132 // For the primary, the 'primary' field is NULL; for subordinates the 'primary' field points back to the associated primary
134 // _DNS_SD_LIBDISPATCH is defined where libdispatch/GCD is available. This does not mean that the application will use the
135 // DNSServiceSetDispatchQueue API. Hence any new code guarded with _DNS_SD_LIBDISPATCH should still be backwards compatible.
136 struct _DNSServiceRef_t
138 DNSServiceOp
*next
; // For shared connection
139 DNSServiceOp
*primary
; // For shared connection
140 dnssd_sock_t sockfd
; // Connected socket between client and daemon
141 dnssd_sock_t validator
; // Used to detect memory corruption, double disposals, etc.
142 client_context_t uid
; // For shared connection requests, each subordinate DNSServiceRef has its own ID,
143 // unique within the scope of the same shared parent DNSServiceRef
144 uint32_t op
; // request_op_t or reply_op_t
145 uint32_t max_index
; // Largest assigned record index - 0 if no additional records registered
146 uint32_t logcounter
; // Counter used to control number of syslog messages we write
147 int *moreptr
; // Set while DNSServiceProcessResult working on this particular DNSServiceRef
148 ProcessReplyFn ProcessReply
; // Function pointer to the code to handle received messages
149 void *AppCallback
; // Client callback function and context
152 #if _DNS_SD_LIBDISPATCH
153 dispatch_source_t disp_source
;
154 dispatch_queue_t disp_queue
;
159 struct _DNSRecordRef_t
163 DNSServiceRegisterRecordReply AppCallback
;
165 uint32_t record_index
; // index is unique to the ServiceDiscoveryRef
169 // Write len bytes. Return 0 on success, -1 on error
170 static int write_all(dnssd_sock_t sd
, char *buf
, size_t len
)
172 // Don't use "MSG_WAITALL"; it returns "Invalid argument" on some Linux versions; use an explicit while() loop instead.
173 //if (send(sd, buf, len, MSG_WAITALL) != len) return -1;
176 ssize_t num_written
= send(sd
, buf
, (long)len
, 0);
177 if (num_written
< 0 || (size_t)num_written
> len
)
179 // Should never happen. If it does, it indicates some OS bug,
180 // or that the mDNSResponder daemon crashed (which should never happen).
181 #if !defined(__ppc__) && defined(SO_ISDEFUNCT)
183 socklen_t dlen
= sizeof (defunct
);
184 if (getsockopt(sd
, SOL_SOCKET
, SO_ISDEFUNCT
, &defunct
, &dlen
) < 0)
185 syslog(LOG_WARNING
, "dnssd_clientstub write_all: SO_ISDEFUNCT failed %d %s", dnssd_errno
, dnssd_strerror(dnssd_errno
));
187 syslog(LOG_WARNING
, "dnssd_clientstub write_all(%d) failed %ld/%ld %d %s", sd
,
188 (long)num_written
, (long)len
,
189 (num_written
< 0) ? dnssd_errno
: 0,
190 (num_written
< 0) ? dnssd_strerror(dnssd_errno
) : "");
192 syslog(LOG_INFO
, "dnssd_clientstub write_all(%d) DEFUNCT", sd
);
194 syslog(LOG_WARNING
, "dnssd_clientstub write_all(%d) failed %ld/%ld %d %s", sd
,
195 (long)num_written
, (long)len
,
196 (num_written
< 0) ? dnssd_errno
: 0,
197 (num_written
< 0) ? dnssd_strerror(dnssd_errno
) : "");
207 enum { read_all_success
= 0, read_all_fail
= -1, read_all_wouldblock
= -2 };
209 // Read len bytes. Return 0 on success, read_all_fail on error, or read_all_wouldblock for
210 static int read_all(dnssd_sock_t sd
, char *buf
, int len
)
212 // Don't use "MSG_WAITALL"; it returns "Invalid argument" on some Linux versions; use an explicit while() loop instead.
213 //if (recv(sd, buf, len, MSG_WAITALL) != len) return -1;
217 ssize_t num_read
= recv(sd
, buf
, len
, 0);
218 // It is valid to get an interrupted system call error e.g., somebody attaching
219 // in a debugger, retry without failing
220 if ((num_read
< 0) && (errno
== EINTR
)) { syslog(LOG_INFO
, "dnssd_clientstub read_all: EINTR continue"); continue; }
221 if ((num_read
== 0) || (num_read
< 0) || (num_read
> len
))
225 // Should never happen. If it does, it indicates some OS bug,
226 // or that the mDNSResponder daemon crashed (which should never happen).
228 // <rdar://problem/7481776> Suppress logs for "A non-blocking socket operation
229 // could not be completed immediately"
230 if (WSAGetLastError() != WSAEWOULDBLOCK
)
233 #if !defined(__ppc__) && defined(SO_ISDEFUNCT)
235 socklen_t dlen
= sizeof (defunct
);
236 if (getsockopt(sd
, SOL_SOCKET
, SO_ISDEFUNCT
, &defunct
, &dlen
) < 0)
237 syslog(LOG_WARNING
, "dnssd_clientstub read_all: SO_ISDEFUNCT failed %d %s", dnssd_errno
, dnssd_strerror(dnssd_errno
));
243 syslog(LOG_WARNING
, "dnssd_clientstub read_all(%d) failed %ld/%ld %d %s", sd
,
244 (long)num_read
, (long)len
,
245 (num_read
< 0) ? dnssd_errno
: 0,
246 (num_read
< 0) ? dnssd_strerror(dnssd_errno
) : "");
248 syslog(LOG_INFO
, "dnssd_clientstub read_all(%d) DEFUNCT", sd
);
249 return (num_read
< 0 && dnssd_errno
== dnssd_EWOULDBLOCK
) ? read_all_wouldblock
: read_all_fail
;
254 return read_all_success
;
257 // Returns 1 if more bytes remain to be read on socket descriptor sd, 0 otherwise
258 static int more_bytes(dnssd_sock_t sd
)
260 struct timeval tv
= { 0, 0 };
272 // Compute the number of integers needed for storing "sd". Internally fd_set is stored
273 // as an array of ints with one bit for each fd and hence we need to compute
274 // the number of ints needed rather than the number of bytes. If "sd" is 32, we need
275 // two ints and not just one.
276 int nfdbits
= sizeof (int) * 8;
277 int nints
= (sd
/nfdbits
) + 1;
278 fs
= (fd_set
*)calloc(nints
, sizeof(int));
279 if (fs
== NULL
) { syslog(LOG_WARNING
, "dnssd_clientstub more_bytes: malloc failed"); return 0; }
282 ret
= select((int)sd
+1, fs
, (fd_set
*)NULL
, (fd_set
*)NULL
, &tv
);
283 if (fs
!= &readfds
) free(fs
);
287 // Wait for daemon to write to socket
288 static int wait_for_daemon(dnssd_sock_t sock
, int timeout
)
291 // At this point the next operation (accept() or read()) on this socket may block for a few milliseconds waiting
292 // for the daemon to respond, but that's okay -- the daemon is a trusted service and we know if won't take more
293 // than a few milliseconds to respond. So we'll forego checking for readability of the socket.
297 // Windows on the other hand suffers from 3rd party software (primarily 3rd party firewall software) that
298 // interferes with proper functioning of the TCP protocol stack. Because of this and because we depend on TCP
299 // to communicate with the system service, we want to make sure that the next operation on this socket (accept() or
300 // read()) doesn't block indefinitely.
310 if (!select((int)(sock
+ 1), &set
, NULL
, NULL
, &tv
))
312 syslog(LOG_WARNING
, "dnssd_clientstub wait_for_daemon timed out");
313 gDaemonErr
= kDNSServiceErr_Timeout
;
322 * allocate and initialize an ipc message header. Value of len should initially be the
323 * length of the data, and is set to the value of the data plus the header. data_start
324 * is set to point to the beginning of the data section. SeparateReturnSocket should be
325 * non-zero for calls that can't receive an immediate error return value on their primary
326 * socket, and therefore require a separate return path for the error code result.
327 * if zero, the path to a control socket is appended at the beginning of the message buffer.
328 * data_start is set past this string.
330 static ipc_msg_hdr
*create_hdr(uint32_t op
, size_t *len
, char **data_start
, int SeparateReturnSocket
, DNSServiceOp
*ref
)
335 #if !defined(USE_TCP_LOOPBACK)
336 char ctrl_path
[64] = ""; // "/var/tmp/dnssd_result_socket.xxxxxxxxxx-xxx-xxxxxx"
339 if (SeparateReturnSocket
)
341 #if defined(USE_TCP_LOOPBACK)
342 *len
+= 2; // Allocate space for two-byte port number
343 #elif defined(USE_NAMED_ERROR_RETURN_SOCKET)
345 if (gettimeofday(&tv
, NULL
) < 0)
346 { syslog(LOG_WARNING
, "dnssd_clientstub create_hdr: gettimeofday failed %d %s", dnssd_errno
, dnssd_strerror(dnssd_errno
)); return NULL
; }
347 sprintf(ctrl_path
, "%s%d-%.3lx-%.6lu", CTL_PATH_PREFIX
, (int)getpid(),
348 (unsigned long)(tv
.tv_sec
& 0xFFF), (unsigned long)(tv
.tv_usec
));
349 *len
+= strlen(ctrl_path
) + 1;
351 *len
+= 1; // Allocate space for single zero byte (empty C string)
355 datalen
= (int) *len
;
356 *len
+= sizeof(ipc_msg_hdr
);
358 // Write message to buffer
360 if (!msg
) { syslog(LOG_WARNING
, "dnssd_clientstub create_hdr: malloc failed"); return NULL
; }
362 memset(msg
, 0, *len
);
363 hdr
= (ipc_msg_hdr
*)msg
;
364 hdr
->version
= VERSION
;
365 hdr
->datalen
= datalen
;
368 hdr
->client_context
= ref
->uid
;
370 *data_start
= msg
+ sizeof(ipc_msg_hdr
);
371 #if defined(USE_TCP_LOOPBACK)
372 // Put dummy data in for the port, since we don't know what it is yet.
373 // The data will get filled in before we send the message. This happens in deliver_request().
374 if (SeparateReturnSocket
) put_uint16(0, data_start
);
376 if (SeparateReturnSocket
) put_string(ctrl_path
, data_start
);
381 static void FreeDNSRecords(DNSServiceOp
*sdRef
)
383 DNSRecord
*rec
= sdRef
->rec
;
386 DNSRecord
*next
= rec
->recnext
;
392 static void FreeDNSServiceOp(DNSServiceOp
*x
)
394 // We don't use our DNSServiceRefValid macro here because if we're cleaning up after a socket() call failed
395 // then sockfd could legitimately contain a failing value (e.g. dnssd_InvalidSocket)
396 if ((x
->sockfd
^ x
->validator
) != ValidatorBits
)
397 syslog(LOG_WARNING
, "dnssd_clientstub attempt to dispose invalid DNSServiceRef %p %08X %08X", x
, x
->sockfd
, x
->validator
);
402 x
->sockfd
= dnssd_InvalidSocket
;
403 x
->validator
= 0xDDDDDDDD;
404 x
->op
= request_op_none
;
408 x
->ProcessReply
= NULL
;
409 x
->AppCallback
= NULL
;
410 x
->AppContext
= NULL
;
411 #if _DNS_SD_LIBDISPATCH
412 if (x
->disp_source
) dispatch_release(x
->disp_source
);
413 x
->disp_source
= NULL
;
414 x
->disp_queue
= NULL
;
416 // DNSRecords may have been added to subordinate sdRef e.g., DNSServiceRegister/DNSServiceAddRecord
417 // or on the main sdRef e.g., DNSServiceCreateConnection/DNSServiveRegisterRecord. DNSRecords may have
418 // been freed if the application called DNSRemoveRecord
429 // Return a connected service ref (deallocate with DNSServiceRefDeallocate)
430 static DNSServiceErrorType
ConnectToServer(DNSServiceRef
*ref
, DNSServiceFlags flags
, uint32_t op
, ProcessReplyFn ProcessReply
, void *AppCallback
, void *AppContext
)
432 #if APPLE_OSX_mDNSResponder
433 int NumTries
= DNSSD_CLIENT_MAXTRIES
;
438 dnssd_sockaddr_t saddr
;
441 if (!ref
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSService operation with NULL DNSServiceRef"); return kDNSServiceErr_BadParam
; }
443 if (flags
& kDNSServiceFlagsShareConnection
)
447 syslog(LOG_WARNING
, "dnssd_clientstub kDNSServiceFlagsShareConnection used with NULL DNSServiceRef");
448 return kDNSServiceErr_BadParam
;
450 if (!DNSServiceRefValid(*ref
) || (*ref
)->op
!= connection_request
|| (*ref
)->primary
)
452 syslog(LOG_WARNING
, "dnssd_clientstub kDNSServiceFlagsShareConnection used with invalid DNSServiceRef %p %08X %08X",
453 (*ref
), (*ref
)->sockfd
, (*ref
)->validator
);
455 return kDNSServiceErr_BadReference
;
464 if (WSAStartup(MAKEWORD(2,2), &wsaData
) != 0) { *ref
= NULL
; return kDNSServiceErr_ServiceNotRunning
; }
466 // <rdar://problem/4096913> If the system service is disabled, we only want to try to connect once
467 if (IsSystemServiceDisabled()) NumTries
= DNSSD_CLIENT_MAXTRIES
;
470 sdr
= malloc(sizeof(DNSServiceOp
));
471 if (!sdr
) { syslog(LOG_WARNING
, "dnssd_clientstub ConnectToServer: malloc failed"); *ref
= NULL
; return kDNSServiceErr_NoMemory
; }
474 sdr
->sockfd
= dnssd_InvalidSocket
;
475 sdr
->validator
= sdr
->sockfd
^ ValidatorBits
;
482 sdr
->ProcessReply
= ProcessReply
;
483 sdr
->AppCallback
= AppCallback
;
484 sdr
->AppContext
= AppContext
;
486 #if _DNS_SD_LIBDISPATCH
487 sdr
->disp_source
= NULL
;
488 sdr
->disp_queue
= NULL
;
490 sdr
->kacontext
= NULL
;
492 if (flags
& kDNSServiceFlagsShareConnection
)
494 DNSServiceOp
**p
= &(*ref
)->next
; // Append ourselves to end of primary's list
495 while (*p
) p
= &(*p
)->next
;
497 // Preincrement counter before we use it -- it helps with debugging if we know the all-zeroes ID should never appear
498 if (++(*ref
)->uid
.u32
[0] == 0) ++(*ref
)->uid
.u32
[1]; // In parent DNSServiceOp increment UID counter
499 sdr
->primary
= *ref
; // Set our primary pointer
500 sdr
->sockfd
= (*ref
)->sockfd
; // Inherit primary's socket
501 sdr
->validator
= (*ref
)->validator
;
502 sdr
->uid
= (*ref
)->uid
;
503 //printf("ConnectToServer sharing socket %d\n", sdr->sockfd);
508 const unsigned long optval
= 1;
511 sdr
->sockfd
= socket(AF_DNSSD
, SOCK_STREAM
, 0);
512 sdr
->validator
= sdr
->sockfd
^ ValidatorBits
;
513 if (!dnssd_SocketValid(sdr
->sockfd
))
515 syslog(LOG_WARNING
, "dnssd_clientstub ConnectToServer: socket failed %d %s", dnssd_errno
, dnssd_strerror(dnssd_errno
));
516 FreeDNSServiceOp(sdr
);
517 return kDNSServiceErr_NoMemory
;
520 // Some environments (e.g. OS X) support turning off SIGPIPE for a socket
521 if (setsockopt(sdr
->sockfd
, SOL_SOCKET
, SO_NOSIGPIPE
, &optval
, sizeof(optval
)) < 0)
522 syslog(LOG_WARNING
, "dnssd_clientstub ConnectToServer: SO_NOSIGPIPE failed %d %s", dnssd_errno
, dnssd_strerror(dnssd_errno
));
524 #if defined(USE_TCP_LOOPBACK)
525 saddr
.sin_family
= AF_INET
;
526 saddr
.sin_addr
.s_addr
= inet_addr(MDNS_TCP_SERVERADDR
);
527 saddr
.sin_port
= htons(MDNS_TCP_SERVERPORT
);
529 saddr
.sun_family
= AF_LOCAL
;
530 strcpy(saddr
.sun_path
, MDNS_UDS_SERVERPATH
);
531 #if !defined(__ppc__) && defined(SO_DEFUNCTOK)
534 if (setsockopt(sdr
->sockfd
, SOL_SOCKET
, SO_DEFUNCTOK
, &defunct
, sizeof(defunct
)) < 0)
535 syslog(LOG_WARNING
, "dnssd_clientstub ConnectToServer: SO_DEFUNCTOK failed %d %s", dnssd_errno
, dnssd_strerror(dnssd_errno
));
542 int err
= connect(sdr
->sockfd
, (struct sockaddr
*) &saddr
, sizeof(saddr
));
543 if (!err
) break; // If we succeeded, return sdr
544 // If we failed, then it may be because the daemon is still launching.
545 // This can happen for processes that launch early in the boot process, while the
546 // daemon is still coming up. Rather than fail here, we'll wait a bit and try again.
547 // If, after four seconds, we still can't connect to the daemon,
548 // then we give up and return a failure code.
549 if (++NumTries
< DNSSD_CLIENT_MAXTRIES
) sleep(1); // Sleep a bit, then try again
550 else { dnssd_close(sdr
->sockfd
); FreeDNSServiceOp(sdr
); return kDNSServiceErr_ServiceNotRunning
; }
552 //printf("ConnectToServer opened socket %d\n", sdr->sockfd);
556 return kDNSServiceErr_NoError
;
559 #define deliver_request_bailout(MSG) \
560 do { syslog(LOG_WARNING, "dnssd_clientstub deliver_request: %s failed %d (%s)", (MSG), dnssd_errno, dnssd_strerror(dnssd_errno)); goto cleanup; } while(0)
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
= kDNSServiceErr_Unknown
; // Default for the "goto cleanup" cases
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
)) deliver_request_bailout("TCP socket");
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) deliver_request_bailout("TCP bind");
602 if (getsockname(listenfd
, (struct sockaddr
*) &caddr
, &len
) < 0) deliver_request_bailout("TCP getsockname");
603 if (listen(listenfd
, 1) < 0) deliver_request_bailout("TCP listen");
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
)) deliver_request_bailout("USE_NAMED_ERROR_RETURN_SOCKET socket");
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) deliver_request_bailout("USE_NAMED_ERROR_RETURN_SOCKET bind");
627 if (listen(listenfd
, 1) < 0) deliver_request_bailout("USE_NAMED_ERROR_RETURN_SOCKET listen");
632 if (socketpair(AF_DNSSD
, SOCK_STREAM
, 0, sp
) < 0) deliver_request_bailout("socketpair");
635 errsd
= sp
[0]; // We'll read our four-byte error code from sp[0]
636 listenfd
= sp
[1]; // We'll send sp[1] to the daemon
637 #if !defined(__ppc__) && defined(SO_DEFUNCTOK)
640 if (setsockopt(errsd
, SOL_SOCKET
, SO_DEFUNCTOK
, &defunct
, sizeof(defunct
)) < 0)
641 syslog(LOG_WARNING
, "dnssd_clientstub ConnectToServer: SO_DEFUNCTOK failed %d %s", dnssd_errno
, dnssd_strerror(dnssd_errno
));
649 #if !defined(USE_TCP_LOOPBACK) && !defined(USE_NAMED_ERROR_RETURN_SOCKET)
650 // If we're going to make a separate error return socket, and pass it to the daemon
651 // using sendmsg, then we'll hold back one data byte to go with it.
652 // On some versions of Unix (including Leopard) sending a control message without
653 // any associated data does not work reliably -- e.g. one particular issue we ran
654 // into is that if the receiving program is in a kqueue loop waiting to be notified
655 // of the received message, it doesn't get woken up when the control message arrives.
656 if (MakeSeparateReturnSocket
|| sdr
->op
== send_bpf
) datalen
--; // Okay to use sdr->op when checking for op == send_bpf
659 // At this point, our listening socket is set up and waiting, if necessary, for the daemon to connect back to
660 ConvertHeaderBytes(hdr
);
661 //syslog(LOG_WARNING, "dnssd_clientstub deliver_request writing %lu bytes", (unsigned long)(datalen + sizeof(ipc_msg_hdr)));
662 //if (MakeSeparateReturnSocket) syslog(LOG_WARNING, "dnssd_clientstub deliver_request name is %s", data);
663 #if TEST_SENDING_ONE_BYTE_AT_A_TIME
665 for (i
=0; i
<datalen
+ sizeof(ipc_msg_hdr
); i
++)
667 syslog(LOG_WARNING
, "dnssd_clientstub deliver_request writing %d", i
);
668 if (write_all(sdr
->sockfd
, ((char *)hdr
)+i
, 1) < 0)
669 { syslog(LOG_WARNING
, "write_all (byte %u) failed", i
); goto cleanup
; }
673 if (write_all(sdr
->sockfd
, (char *)hdr
, datalen
+ sizeof(ipc_msg_hdr
)) < 0)
675 // write_all already prints an error message if there is an error writing to
676 // the socket except for DEFUNCT. Logging here is unnecessary and also wrong
677 // in the case of DEFUNCT sockets
678 syslog(LOG_INFO
, "dnssd_clientstub deliver_request ERROR: write_all(%d, %lu bytes) failed",
679 sdr
->sockfd
, (unsigned long)(datalen
+ sizeof(ipc_msg_hdr
)));
684 if (!MakeSeparateReturnSocket
) errsd
= sdr
->sockfd
;
685 if (MakeSeparateReturnSocket
|| sdr
->op
== send_bpf
) // Okay to use sdr->op when checking for op == send_bpf
687 #if defined(USE_TCP_LOOPBACK) || defined(USE_NAMED_ERROR_RETURN_SOCKET)
688 // At this point we may block in accept for a few milliseconds waiting for the daemon to connect back to us,
689 // but that's okay -- the daemon is a trusted service and we know if won't take more than a few milliseconds to respond.
690 dnssd_sockaddr_t daddr
;
691 dnssd_socklen_t len
= sizeof(daddr
);
692 if ((err
= wait_for_daemon(listenfd
, DNSSD_CLIENT_TIMEOUT
)) != kDNSServiceErr_NoError
) goto cleanup
;
693 errsd
= accept(listenfd
, (struct sockaddr
*)&daddr
, &len
);
694 if (!dnssd_SocketValid(errsd
)) deliver_request_bailout("accept");
697 struct iovec vec
= { ((char *)hdr
) + sizeof(ipc_msg_hdr
) + datalen
, 1 }; // Send the last byte along with the SCM_RIGHTS
699 struct cmsghdr
*cmsg
;
700 char cbuf
[CMSG_SPACE(sizeof(dnssd_sock_t
))];
702 if (sdr
->op
== send_bpf
) // Okay to use sdr->op when checking for op == send_bpf
705 char p
[12]; // Room for "/dev/bpf999" with terminating null
706 for (i
=0; i
<100; i
++)
708 snprintf(p
, sizeof(p
), "/dev/bpf%d", i
);
709 listenfd
= open(p
, O_RDWR
, 0);
710 //if (dnssd_SocketValid(listenfd)) syslog(LOG_WARNING, "Sending fd %d for %s", listenfd, p);
711 if (!dnssd_SocketValid(listenfd
) && dnssd_errno
!= EBUSY
)
712 syslog(LOG_WARNING
, "Error opening %s %d (%s)", p
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
713 if (dnssd_SocketValid(listenfd
) || dnssd_errno
!= EBUSY
) break;
721 msg
.msg_control
= cbuf
;
722 msg
.msg_controllen
= CMSG_LEN(sizeof(dnssd_sock_t
));
724 cmsg
= CMSG_FIRSTHDR(&msg
);
725 cmsg
->cmsg_len
= CMSG_LEN(sizeof(dnssd_sock_t
));
726 cmsg
->cmsg_level
= SOL_SOCKET
;
727 cmsg
->cmsg_type
= SCM_RIGHTS
;
728 *((dnssd_sock_t
*)CMSG_DATA(cmsg
)) = listenfd
;
730 #if TEST_KQUEUE_CONTROL_MESSAGE_BUG
734 #if DEBUG_64BIT_SCM_RIGHTS
735 syslog(LOG_WARNING
, "dnssd_clientstub sendmsg read sd=%d write sd=%d %ld %ld %ld/%ld/%ld/%ld",
736 errsd
, listenfd
, sizeof(dnssd_sock_t
), sizeof(void*),
737 sizeof(struct cmsghdr
) + sizeof(dnssd_sock_t
),
738 CMSG_LEN(sizeof(dnssd_sock_t
)), (long)CMSG_SPACE(sizeof(dnssd_sock_t
)),
739 (long)((char*)CMSG_DATA(cmsg
) + 4 - cbuf
));
740 #endif // DEBUG_64BIT_SCM_RIGHTS
742 if (sendmsg(sdr
->sockfd
, &msg
, 0) < 0)
744 syslog(LOG_WARNING
, "dnssd_clientstub deliver_request ERROR: sendmsg failed read sd=%d write sd=%d errno %d (%s)",
745 errsd
, listenfd
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
746 err
= kDNSServiceErr_Incompatible
;
750 #if DEBUG_64BIT_SCM_RIGHTS
751 syslog(LOG_WARNING
, "dnssd_clientstub sendmsg read sd=%d write sd=%d okay", errsd
, listenfd
);
752 #endif // DEBUG_64BIT_SCM_RIGHTS
755 // Close our end of the socketpair *before* blocking in read_all to get the four-byte error code.
756 // Otherwise, if the daemon closes our socket (or crashes), we block in read_all() forever
757 // because the socket is not closed (we still have an open reference to it ourselves).
758 dnssd_close(listenfd
);
759 listenfd
= dnssd_InvalidSocket
; // Make sure we don't close it a second time in the cleanup handling below
762 // At this point we may block in read_all for a few milliseconds waiting for the daemon to send us the error code,
763 // but that's okay -- the daemon is a trusted service and we know if won't take more than a few milliseconds to respond.
764 if (sdr
->op
== send_bpf
) // Okay to use sdr->op when checking for op == send_bpf
765 err
= kDNSServiceErr_NoError
;
766 else if ((err
= wait_for_daemon(errsd
, DNSSD_CLIENT_TIMEOUT
)) == kDNSServiceErr_NoError
)
768 if (read_all(errsd
, (char*)&err
, (int)sizeof(err
)) < 0)
769 err
= kDNSServiceErr_ServiceNotRunning
; // On failure read_all will have written a message to syslog for us
774 //syslog(LOG_WARNING, "dnssd_clientstub deliver_request: retrieved error code %d", err);
777 if (MakeSeparateReturnSocket
)
779 if (dnssd_SocketValid(listenfd
)) dnssd_close(listenfd
);
780 if (dnssd_SocketValid(errsd
)) dnssd_close(errsd
);
781 #if defined(USE_NAMED_ERROR_RETURN_SOCKET)
782 // syslog(LOG_WARNING, "dnssd_clientstub deliver_request: removing UDS: %s", data);
783 if (unlink(data
) != 0)
784 syslog(LOG_WARNING
, "dnssd_clientstub WARNING: unlink(\"%s\") failed errno %d (%s)", data
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
785 // else syslog(LOG_WARNING, "dnssd_clientstub deliver_request: removed UDS: %s", data);
793 int DNSSD_API
DNSServiceRefSockFD(DNSServiceRef sdRef
)
795 if (!sdRef
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRefSockFD called with NULL DNSServiceRef"); return dnssd_InvalidSocket
; }
797 if (!DNSServiceRefValid(sdRef
))
799 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRefSockFD called with invalid DNSServiceRef %p %08X %08X",
800 sdRef
, sdRef
->sockfd
, sdRef
->validator
);
801 return dnssd_InvalidSocket
;
806 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRefSockFD undefined for kDNSServiceFlagsShareConnection subordinate DNSServiceRef %p", sdRef
);
807 return dnssd_InvalidSocket
;
810 return (int) sdRef
->sockfd
;
813 #if _DNS_SD_LIBDISPATCH
814 static void CallbackWithError(DNSServiceRef sdRef
, DNSServiceErrorType error
)
816 DNSServiceOp
*sdr
= sdRef
;
817 DNSServiceOp
*sdrNext
;
824 // We can't touch the sdr after the callback as it can be deallocated in the callback
827 sdr
->moreptr
= &morebytes
;
830 case resolve_request
:
831 if (sdr
->AppCallback
) ((DNSServiceResolveReply
) sdr
->AppCallback
)(sdr
, 0, 0, error
, NULL
, 0, 0, 0, NULL
, sdr
->AppContext
);
834 if (sdr
->AppCallback
) ((DNSServiceQueryRecordReply
)sdr
->AppCallback
)(sdr
, 0, 0, error
, NULL
, 0, 0, 0, NULL
, 0, sdr
->AppContext
);
836 case addrinfo_request
:
837 if (sdr
->AppCallback
) ((DNSServiceGetAddrInfoReply
)sdr
->AppCallback
)(sdr
, 0, 0, error
, NULL
, NULL
, 0, sdr
->AppContext
);
840 if (sdr
->AppCallback
) ((DNSServiceBrowseReply
) sdr
->AppCallback
)(sdr
, 0, 0, error
, NULL
, 0, NULL
, sdr
->AppContext
);
842 case reg_service_request
:
843 if (sdr
->AppCallback
) ((DNSServiceRegisterReply
) sdr
->AppCallback
)(sdr
, 0, error
, NULL
, 0, NULL
, sdr
->AppContext
);
845 case enumeration_request
:
846 if (sdr
->AppCallback
) ((DNSServiceDomainEnumReply
) sdr
->AppCallback
)(sdr
, 0, 0, error
, NULL
, sdr
->AppContext
);
848 case connection_request
:
849 // This means Register Record, walk the list of DNSRecords to do the callback
853 recnext
= rec
->recnext
;
854 if (rec
->AppCallback
) ((DNSServiceRegisterRecordReply
)rec
->AppCallback
)(sdr
, 0, 0, error
, rec
->AppContext
);
855 // The Callback can call DNSServiceRefDeallocate which in turn frees sdr and all the records.
856 // Detect that and return early
857 if (!morebytes
) {syslog(LOG_WARNING
, "dnssdclientstub:Record: CallbackwithError morebytes zero"); return;}
861 case port_mapping_request
:
862 if (sdr
->AppCallback
) ((DNSServiceNATPortMappingReply
)sdr
->AppCallback
)(sdr
, 0, 0, error
, 0, 0, 0, 0, 0, sdr
->AppContext
);
865 syslog(LOG_WARNING
, "dnssd_clientstub CallbackWithError called with bad op %d", sdr
->op
);
867 // If DNSServiceRefDeallocate was called in the callback, morebytes will be zero. As the sdRef
868 // (and its subordinates) have been freed, we should not proceed further. Note that when we
869 // call the callback with a subordinate sdRef the application can call DNSServiceRefDeallocate
870 // on the main sdRef and DNSServiceRefDeallocate handles this case by walking all the sdRefs and
871 // clears the moreptr so that we can terminate here.
873 // If DNSServiceRefDeallocate was not called in the callback, then set moreptr to NULL so that
874 // we don't access the stack variable after we return from this function.
875 if (!morebytes
) {syslog(LOG_WARNING
, "dnssdclientstub:sdRef: CallbackwithError morebytes zero sdr %p", sdr
); return;}
876 else {sdr
->moreptr
= NULL
;}
880 #endif // _DNS_SD_LIBDISPATCH
882 // Handle reply from server, calling application client callback. If there is no reply
883 // from the daemon on the socket contained in sdRef, the call will block.
884 DNSServiceErrorType DNSSD_API
DNSServiceProcessResult(DNSServiceRef sdRef
)
888 if (!sdRef
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceProcessResult called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam
; }
890 if (!DNSServiceRefValid(sdRef
))
892 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceProcessResult called with invalid DNSServiceRef %p %08X %08X", sdRef
, sdRef
->sockfd
, sdRef
->validator
);
893 return kDNSServiceErr_BadReference
;
898 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceProcessResult undefined for kDNSServiceFlagsShareConnection subordinate DNSServiceRef %p", sdRef
);
899 return kDNSServiceErr_BadReference
;
902 if (!sdRef
->ProcessReply
)
904 static int num_logs
= 0;
905 if (num_logs
< 10) syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceProcessResult called with DNSServiceRef with no ProcessReply function");
906 if (num_logs
< 1000) num_logs
++;else sleep(1);
907 return kDNSServiceErr_BadReference
;
915 // return NoError on EWOULDBLOCK. This will handle the case
916 // where a non-blocking socket is told there is data, but it was a false positive.
917 // On error, read_all will write a message to syslog for us, so don't need to duplicate that here
918 // Note: If we want to properly support using non-blocking sockets in the future
919 int result
= read_all(sdRef
->sockfd
, (void *)&cbh
.ipc_hdr
, sizeof(cbh
.ipc_hdr
));
920 if (result
== read_all_fail
)
922 // Set the ProcessReply to NULL before callback as the sdRef can get deallocated
924 sdRef
->ProcessReply
= NULL
;
925 #if _DNS_SD_LIBDISPATCH
926 // Call the callbacks with an error if using the dispatch API, as DNSServiceProcessResult
927 // is not called by the application and hence need to communicate the error. Cancel the
928 // source so that we don't get any more events
929 // Note: read_all fails if we could not read from the daemon which can happen if the
930 // daemon dies or the file descriptor is disconnected (defunct).
931 if (sdRef
->disp_source
)
933 dispatch_source_cancel(sdRef
->disp_source
);
934 dispatch_release(sdRef
->disp_source
);
935 sdRef
->disp_source
= NULL
;
936 CallbackWithError(sdRef
, kDNSServiceErr_ServiceNotRunning
);
939 // Don't touch sdRef anymore as it might have been deallocated
940 return kDNSServiceErr_ServiceNotRunning
;
942 else if (result
== read_all_wouldblock
)
944 if (morebytes
&& sdRef
->logcounter
< 100)
947 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceProcessResult error: select indicated data was waiting but read_all returned EWOULDBLOCK");
949 return kDNSServiceErr_NoError
;
952 ConvertHeaderBytes(&cbh
.ipc_hdr
);
953 if (cbh
.ipc_hdr
.version
!= VERSION
)
955 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceProcessResult daemon version %d does not match client version %d", cbh
.ipc_hdr
.version
, VERSION
);
956 sdRef
->ProcessReply
= NULL
;
957 return kDNSServiceErr_Incompatible
;
960 data
= malloc(cbh
.ipc_hdr
.datalen
);
961 if (!data
) return kDNSServiceErr_NoMemory
;
962 if (read_all(sdRef
->sockfd
, data
, cbh
.ipc_hdr
.datalen
) < 0) // On error, read_all will write a message to syslog for us
964 // Set the ProcessReply to NULL before callback as the sdRef can get deallocated
966 sdRef
->ProcessReply
= NULL
;
967 #if _DNS_SD_LIBDISPATCH
968 // Call the callbacks with an error if using the dispatch API, as DNSServiceProcessResult
969 // is not called by the application and hence need to communicate the error. Cancel the
970 // source so that we don't get any more events
971 if (sdRef
->disp_source
)
973 dispatch_source_cancel(sdRef
->disp_source
);
974 dispatch_release(sdRef
->disp_source
);
975 sdRef
->disp_source
= NULL
;
976 CallbackWithError(sdRef
, kDNSServiceErr_ServiceNotRunning
);
979 // Don't touch sdRef anymore as it might have been deallocated
981 return kDNSServiceErr_ServiceNotRunning
;
985 const char *ptr
= data
;
986 cbh
.cb_flags
= get_flags (&ptr
, data
+ cbh
.ipc_hdr
.datalen
);
987 cbh
.cb_interface
= get_uint32 (&ptr
, data
+ cbh
.ipc_hdr
.datalen
);
988 cbh
.cb_err
= get_error_code(&ptr
, data
+ cbh
.ipc_hdr
.datalen
);
990 // CAUTION: We have to handle the case where the client calls DNSServiceRefDeallocate from within the callback function.
991 // To do this we set moreptr to point to morebytes. If the client does call DNSServiceRefDeallocate(),
992 // then that routine will clear morebytes for us, and cause us to exit our loop.
993 morebytes
= more_bytes(sdRef
->sockfd
);
996 cbh
.cb_flags
|= kDNSServiceFlagsMoreComing
;
997 sdRef
->moreptr
= &morebytes
;
999 if (ptr
) sdRef
->ProcessReply(sdRef
, &cbh
, ptr
, data
+ cbh
.ipc_hdr
.datalen
);
1000 // Careful code here:
1001 // If morebytes is non-zero, that means we set sdRef->moreptr above, and the operation was not
1002 // cancelled out from under us, so now we need to clear sdRef->moreptr so we don't leave a stray
1003 // dangling pointer pointing to a long-gone stack variable.
1004 // If morebytes is zero, then one of two thing happened:
1005 // (a) morebytes was 0 above, so we didn't set sdRef->moreptr, so we don't need to clear it
1006 // (b) morebytes was 1 above, and we set sdRef->moreptr, but the operation was cancelled (with DNSServiceRefDeallocate()),
1007 // so we MUST NOT try to dereference our stale sdRef pointer.
1008 if (morebytes
) sdRef
->moreptr
= NULL
;
1011 } while (morebytes
);
1013 return kDNSServiceErr_NoError
;
1016 void DNSSD_API
DNSServiceRefDeallocate(DNSServiceRef sdRef
)
1018 if (!sdRef
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRefDeallocate called with NULL DNSServiceRef"); return; }
1020 if (!DNSServiceRefValid(sdRef
)) // Also verifies dnssd_SocketValid(sdRef->sockfd) for us too
1022 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRefDeallocate called with invalid DNSServiceRef %p %08X %08X", sdRef
, sdRef
->sockfd
, sdRef
->validator
);
1026 // 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
1027 if (sdRef
->moreptr
) *(sdRef
->moreptr
) = 0;
1029 if (sdRef
->primary
) // If this is a subordinate DNSServiceOp, just send a 'stop' command
1031 DNSServiceOp
**p
= &sdRef
->primary
->next
;
1032 while (*p
&& *p
!= sdRef
) p
= &(*p
)->next
;
1037 ipc_msg_hdr
*hdr
= create_hdr(cancel_request
, &len
, &ptr
, 0, sdRef
);
1040 ConvertHeaderBytes(hdr
);
1041 write_all(sdRef
->sockfd
, (char *)hdr
, len
);
1045 FreeDNSServiceOp(sdRef
);
1048 else // else, make sure to terminate all subordinates as well
1050 #if _DNS_SD_LIBDISPATCH
1051 // The cancel handler will close the fd if a dispatch source has been set
1052 if (sdRef
->disp_source
)
1054 // By setting the ProcessReply to NULL, we make sure that we never call
1055 // the application callbacks ever, after returning from this function. We
1056 // assume that DNSServiceRefDeallocate is called from the serial queue
1057 // that was passed to DNSServiceSetDispatchQueue. Hence, dispatch_source_cancel
1058 // should cancel all the blocks on the queue and hence there should be no more
1059 // callbacks when we return from this function. Setting ProcessReply to NULL
1060 // provides extra protection.
1061 sdRef
->ProcessReply
= NULL
;
1062 dispatch_source_cancel(sdRef
->disp_source
);
1063 dispatch_release(sdRef
->disp_source
);
1064 sdRef
->disp_source
= NULL
;
1066 // if disp_queue is set, it means it used the DNSServiceSetDispatchQueue API. In that case,
1067 // when the source was cancelled, the fd was closed in the handler. Currently the source
1068 // is cancelled only when the mDNSResponder daemon dies
1069 else if (!sdRef
->disp_queue
) dnssd_close(sdRef
->sockfd
);
1071 dnssd_close(sdRef
->sockfd
);
1073 // Free DNSRecords added in DNSRegisterRecord if they have not
1074 // been freed in DNSRemoveRecord
1077 DNSServiceOp
*p
= sdRef
;
1078 sdRef
= sdRef
->next
;
1079 // When there is an error reading from the daemon e.g., bad fd, CallbackWithError
1080 // is called which sets moreptr. It might set the moreptr on a subordinate sdRef
1081 // but the application might call DNSServiceRefDeallocate with the main sdRef from
1082 // the callback. Hence, when we loop through the subordinate sdRefs, we need
1083 // to clear the moreptr so that CallbackWithError can terminate itself instead of
1084 // walking through the freed sdRefs.
1085 if (p
->moreptr
) *(p
->moreptr
) = 0;
1086 FreeDNSServiceOp(p
);
1091 DNSServiceErrorType DNSSD_API
DNSServiceGetProperty(const char *property
, void *result
, uint32_t *size
)
1094 size_t len
= strlen(property
) + 1;
1097 uint32_t actualsize
;
1099 DNSServiceErrorType err
= ConnectToServer(&tmp
, 0, getproperty_request
, NULL
, NULL
, NULL
);
1100 if (err
) return err
;
1102 hdr
= create_hdr(getproperty_request
, &len
, &ptr
, 0, tmp
);
1103 if (!hdr
) { DNSServiceRefDeallocate(tmp
); return kDNSServiceErr_NoMemory
; }
1105 put_string(property
, &ptr
);
1106 err
= deliver_request(hdr
, tmp
); // Will free hdr for us
1107 if (read_all(tmp
->sockfd
, (char*)&actualsize
, (int)sizeof(actualsize
)) < 0)
1108 { DNSServiceRefDeallocate(tmp
); return kDNSServiceErr_ServiceNotRunning
; }
1110 actualsize
= ntohl(actualsize
);
1111 if (read_all(tmp
->sockfd
, (char*)result
, actualsize
< *size
? actualsize
: *size
) < 0)
1112 { DNSServiceRefDeallocate(tmp
); return kDNSServiceErr_ServiceNotRunning
; }
1113 DNSServiceRefDeallocate(tmp
);
1115 // Swap version result back to local process byte order
1116 if (!strcmp(property
, kDNSServiceProperty_DaemonVersion
) && *size
>= 4)
1117 *(uint32_t*)result
= ntohl(*(uint32_t*)result
);
1120 return kDNSServiceErr_NoError
;
1123 static void handle_resolve_response(DNSServiceOp
*const sdr
, const CallbackHeader
*const cbh
, const char *data
, const char *end
)
1125 char fullname
[kDNSServiceMaxDomainName
];
1126 char target
[kDNSServiceMaxDomainName
];
1128 union { uint16_t s
; u_char b
[2]; } port
;
1129 unsigned char *txtrecord
;
1131 get_string(&data
, end
, fullname
, kDNSServiceMaxDomainName
);
1132 get_string(&data
, end
, target
, kDNSServiceMaxDomainName
);
1133 if (!data
|| data
+ 2 > end
) goto fail
;
1135 port
.b
[0] = *data
++;
1136 port
.b
[1] = *data
++;
1137 txtlen
= get_uint16(&data
, end
);
1138 txtrecord
= (unsigned char *)get_rdata(&data
, end
, txtlen
);
1140 if (!data
) goto fail
;
1141 ((DNSServiceResolveReply
)sdr
->AppCallback
)(sdr
, cbh
->cb_flags
, cbh
->cb_interface
, cbh
->cb_err
, fullname
, target
, port
.s
, txtlen
, txtrecord
, sdr
->AppContext
);
1143 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1145 syslog(LOG_WARNING
, "dnssd_clientstub handle_resolve_response: error reading result from daemon");
1148 #if APPLE_OSX_mDNSResponder
1150 static int32_t libSystemVersion
= 0;
1152 // Return true if the application linked against a version of libsystem where P2P
1153 // interfaces were included by default when using kDNSServiceInterfaceIndexAny.
1154 // Using 160.0.0 == 0xa00000 as the version threshold.
1155 static int includeP2PWithIndexAny()
1157 if (libSystemVersion
== 0)
1158 libSystemVersion
= NSVersionOfLinkTimeLibrary("System");
1160 if (libSystemVersion
< 0xa00000)
1166 #else // APPLE_OSX_mDNSResponder
1168 // always return false for non Apple platforms
1169 static int includeP2PWithIndexAny()
1174 #endif // APPLE_OSX_mDNSResponder
1176 DNSServiceErrorType DNSSD_API DNSServiceResolve
1178 DNSServiceRef
*sdRef
,
1179 DNSServiceFlags flags
,
1180 uint32_t interfaceIndex
,
1182 const char *regtype
,
1184 DNSServiceResolveReply callBack
,
1191 DNSServiceErrorType err
;
1193 if (!name
|| !regtype
|| !domain
|| !callBack
) return kDNSServiceErr_BadParam
;
1195 // Need a real InterfaceID for WakeOnResolve
1196 if ((flags
& kDNSServiceFlagsWakeOnResolve
) != 0 &&
1197 ((interfaceIndex
== kDNSServiceInterfaceIndexAny
) ||
1198 (interfaceIndex
== kDNSServiceInterfaceIndexLocalOnly
) ||
1199 (interfaceIndex
== kDNSServiceInterfaceIndexUnicast
) ||
1200 (interfaceIndex
== kDNSServiceInterfaceIndexP2P
)))
1202 return kDNSServiceErr_BadParam
;
1205 if ((interfaceIndex
== kDNSServiceInterfaceIndexAny
) && includeP2PWithIndexAny())
1206 flags
|= kDNSServiceFlagsIncludeP2P
;
1208 err
= ConnectToServer(sdRef
, flags
, resolve_request
, handle_resolve_response
, callBack
, context
);
1209 if (err
) return err
; // On error ConnectToServer leaves *sdRef set to NULL
1211 // Calculate total message length
1212 len
= sizeof(flags
);
1213 len
+= sizeof(interfaceIndex
);
1214 len
+= strlen(name
) + 1;
1215 len
+= strlen(regtype
) + 1;
1216 len
+= strlen(domain
) + 1;
1218 hdr
= create_hdr(resolve_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(name
, &ptr
);
1224 put_string(regtype
, &ptr
);
1225 put_string(domain
, &ptr
);
1227 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1228 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
1232 static void handle_query_response(DNSServiceOp
*const sdr
, const CallbackHeader
*const cbh
, const char *data
, const char *const end
)
1235 char name
[kDNSServiceMaxDomainName
];
1236 uint16_t rrtype
, rrclass
, rdlen
;
1239 get_string(&data
, end
, name
, kDNSServiceMaxDomainName
);
1240 rrtype
= get_uint16(&data
, end
);
1241 rrclass
= get_uint16(&data
, end
);
1242 rdlen
= get_uint16(&data
, end
);
1243 rdata
= get_rdata(&data
, end
, rdlen
);
1244 ttl
= get_uint32(&data
, end
);
1246 if (!data
) syslog(LOG_WARNING
, "dnssd_clientstub handle_query_response: error reading result from daemon");
1247 else ((DNSServiceQueryRecordReply
)sdr
->AppCallback
)(sdr
, cbh
->cb_flags
, cbh
->cb_interface
, cbh
->cb_err
, name
, rrtype
, rrclass
, rdlen
, rdata
, ttl
, sdr
->AppContext
);
1248 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1251 DNSServiceErrorType DNSSD_API DNSServiceQueryRecord
1253 DNSServiceRef
*sdRef
,
1254 DNSServiceFlags flags
,
1255 uint32_t interfaceIndex
,
1259 DNSServiceQueryRecordReply callBack
,
1266 DNSServiceErrorType err
;
1268 if ((interfaceIndex
== kDNSServiceInterfaceIndexAny
) && includeP2PWithIndexAny())
1269 flags
|= kDNSServiceFlagsIncludeP2P
;
1271 err
= ConnectToServer(sdRef
, flags
, query_request
, handle_query_response
, callBack
, context
);
1272 if (err
) return err
; // On error ConnectToServer leaves *sdRef set to NULL
1274 if (!name
) name
= "\0";
1276 // Calculate total message length
1277 len
= sizeof(flags
);
1278 len
+= sizeof(uint32_t); // interfaceIndex
1279 len
+= strlen(name
) + 1;
1280 len
+= 2 * sizeof(uint16_t); // rrtype, rrclass
1282 hdr
= create_hdr(query_request
, &len
, &ptr
, (*sdRef
)->primary
? 1 : 0, *sdRef
);
1283 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
1285 put_flags(flags
, &ptr
);
1286 put_uint32(interfaceIndex
, &ptr
);
1287 put_string(name
, &ptr
);
1288 put_uint16(rrtype
, &ptr
);
1289 put_uint16(rrclass
, &ptr
);
1291 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1292 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
1296 static void handle_addrinfo_response(DNSServiceOp
*const sdr
, const CallbackHeader
*const cbh
, const char *data
, const char *const end
)
1298 char hostname
[kDNSServiceMaxDomainName
];
1299 uint16_t rrtype
, rrclass
, rdlen
;
1303 get_string(&data
, end
, hostname
, kDNSServiceMaxDomainName
);
1304 rrtype
= get_uint16(&data
, end
);
1305 rrclass
= get_uint16(&data
, end
);
1306 rdlen
= get_uint16(&data
, end
);
1307 rdata
= get_rdata (&data
, end
, rdlen
);
1308 ttl
= get_uint32(&data
, end
);
1310 // We only generate client callbacks for A and AAAA results (including NXDOMAIN results for
1311 // those types, if the client has requested those with the kDNSServiceFlagsReturnIntermediates).
1312 // Other result types, specifically CNAME referrals, are not communicated to the client, because
1313 // the DNSServiceGetAddrInfoReply interface doesn't have any meaningful way to communiate CNAME referrals.
1314 if (!data
) syslog(LOG_WARNING
, "dnssd_clientstub handle_addrinfo_response: error reading result from daemon");
1315 else if (rrtype
== kDNSServiceType_A
|| rrtype
== kDNSServiceType_AAAA
)
1317 struct sockaddr_in sa4
;
1318 struct sockaddr_in6 sa6
;
1319 const struct sockaddr
*const sa
= (rrtype
== kDNSServiceType_A
) ? (struct sockaddr
*)&sa4
: (struct sockaddr
*)&sa6
;
1320 if (rrtype
== kDNSServiceType_A
)
1322 memset(&sa4
, 0, sizeof(sa4
));
1323 #ifndef NOT_HAVE_SA_LEN
1324 sa4
.sin_len
= sizeof(struct sockaddr_in
);
1326 sa4
.sin_family
= AF_INET
;
1328 if (!cbh
->cb_err
) memcpy(&sa4
.sin_addr
, rdata
, rdlen
);
1332 memset(&sa6
, 0, sizeof(sa6
));
1333 #ifndef NOT_HAVE_SA_LEN
1334 sa6
.sin6_len
= sizeof(struct sockaddr_in6
);
1336 sa6
.sin6_family
= AF_INET6
;
1338 // sin6_flowinfo = 0;
1339 // sin6_scope_id = 0;
1342 memcpy(&sa6
.sin6_addr
, rdata
, rdlen
);
1343 if (IN6_IS_ADDR_LINKLOCAL(&sa6
.sin6_addr
)) sa6
.sin6_scope_id
= cbh
->cb_interface
;
1346 ((DNSServiceGetAddrInfoReply
)sdr
->AppCallback
)(sdr
, cbh
->cb_flags
, cbh
->cb_interface
, cbh
->cb_err
, hostname
, sa
, ttl
, sdr
->AppContext
);
1347 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1351 DNSServiceErrorType DNSSD_API DNSServiceGetAddrInfo
1353 DNSServiceRef
*sdRef
,
1354 DNSServiceFlags flags
,
1355 uint32_t interfaceIndex
,
1357 const char *hostname
,
1358 DNSServiceGetAddrInfoReply callBack
,
1359 void *context
/* may be NULL */
1365 DNSServiceErrorType err
;
1367 if (!hostname
) return kDNSServiceErr_BadParam
;
1369 err
= ConnectToServer(sdRef
, flags
, addrinfo_request
, handle_addrinfo_response
, callBack
, context
);
1370 if (err
) return err
; // On error ConnectToServer leaves *sdRef set to NULL
1372 // Calculate total message length
1373 len
= sizeof(flags
);
1374 len
+= sizeof(uint32_t); // interfaceIndex
1375 len
+= sizeof(uint32_t); // protocol
1376 len
+= strlen(hostname
) + 1;
1378 hdr
= create_hdr(addrinfo_request
, &len
, &ptr
, (*sdRef
)->primary
? 1 : 0, *sdRef
);
1379 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
1381 put_flags(flags
, &ptr
);
1382 put_uint32(interfaceIndex
, &ptr
);
1383 put_uint32(protocol
, &ptr
);
1384 put_string(hostname
, &ptr
);
1386 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1387 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
1391 static void handle_browse_response(DNSServiceOp
*const sdr
, const CallbackHeader
*const cbh
, const char *data
, const char *const end
)
1393 char replyName
[256], replyType
[kDNSServiceMaxDomainName
], replyDomain
[kDNSServiceMaxDomainName
];
1394 get_string(&data
, end
, replyName
, 256);
1395 get_string(&data
, end
, replyType
, kDNSServiceMaxDomainName
);
1396 get_string(&data
, end
, replyDomain
, kDNSServiceMaxDomainName
);
1397 if (!data
) syslog(LOG_WARNING
, "dnssd_clientstub handle_browse_response: error reading result from daemon");
1398 else ((DNSServiceBrowseReply
)sdr
->AppCallback
)(sdr
, cbh
->cb_flags
, cbh
->cb_interface
, cbh
->cb_err
, replyName
, replyType
, replyDomain
, sdr
->AppContext
);
1399 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1402 DNSServiceErrorType DNSSD_API DNSServiceBrowse
1404 DNSServiceRef
*sdRef
,
1405 DNSServiceFlags flags
,
1406 uint32_t interfaceIndex
,
1407 const char *regtype
,
1409 DNSServiceBrowseReply callBack
,
1416 DNSServiceErrorType err
;
1418 if ((interfaceIndex
== kDNSServiceInterfaceIndexAny
) && includeP2PWithIndexAny())
1419 flags
|= kDNSServiceFlagsIncludeP2P
;
1421 err
= ConnectToServer(sdRef
, flags
, browse_request
, handle_browse_response
, callBack
, context
);
1422 if (err
) return err
; // On error ConnectToServer leaves *sdRef set to NULL
1424 if (!domain
) domain
= "";
1425 len
= sizeof(flags
);
1426 len
+= sizeof(interfaceIndex
);
1427 len
+= strlen(regtype
) + 1;
1428 len
+= strlen(domain
) + 1;
1430 hdr
= create_hdr(browse_request
, &len
, &ptr
, (*sdRef
)->primary
? 1 : 0, *sdRef
);
1431 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
1433 put_flags(flags
, &ptr
);
1434 put_uint32(interfaceIndex
, &ptr
);
1435 put_string(regtype
, &ptr
);
1436 put_string(domain
, &ptr
);
1438 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1439 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
1443 DNSServiceErrorType DNSSD_API
DNSServiceSetDefaultDomainForUser(DNSServiceFlags flags
, const char *domain
);
1444 DNSServiceErrorType DNSSD_API
DNSServiceSetDefaultDomainForUser(DNSServiceFlags flags
, const char *domain
)
1448 size_t len
= sizeof(flags
) + strlen(domain
) + 1;
1450 DNSServiceErrorType err
= ConnectToServer(&tmp
, 0, setdomain_request
, NULL
, NULL
, NULL
);
1451 if (err
) return err
;
1453 hdr
= create_hdr(setdomain_request
, &len
, &ptr
, 0, tmp
);
1454 if (!hdr
) { DNSServiceRefDeallocate(tmp
); return kDNSServiceErr_NoMemory
; }
1456 put_flags(flags
, &ptr
);
1457 put_string(domain
, &ptr
);
1458 err
= deliver_request(hdr
, tmp
); // Will free hdr for us
1459 DNSServiceRefDeallocate(tmp
);
1463 static void handle_regservice_response(DNSServiceOp
*const sdr
, const CallbackHeader
*const cbh
, const char *data
, const char *const end
)
1465 char name
[256], regtype
[kDNSServiceMaxDomainName
], domain
[kDNSServiceMaxDomainName
];
1466 get_string(&data
, end
, name
, 256);
1467 get_string(&data
, end
, regtype
, kDNSServiceMaxDomainName
);
1468 get_string(&data
, end
, domain
, kDNSServiceMaxDomainName
);
1469 if (!data
) syslog(LOG_WARNING
, "dnssd_clientstub handle_regservice_response: error reading result from daemon");
1470 else ((DNSServiceRegisterReply
)sdr
->AppCallback
)(sdr
, cbh
->cb_flags
, cbh
->cb_err
, name
, regtype
, domain
, sdr
->AppContext
);
1471 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1474 DNSServiceErrorType DNSSD_API DNSServiceRegister
1476 DNSServiceRef
*sdRef
,
1477 DNSServiceFlags flags
,
1478 uint32_t interfaceIndex
,
1480 const char *regtype
,
1483 uint16_t PortInNetworkByteOrder
,
1485 const void *txtRecord
,
1486 DNSServiceRegisterReply callBack
,
1493 DNSServiceErrorType err
;
1494 union { uint16_t s
; u_char b
[2]; } port
= { PortInNetworkByteOrder
};
1496 if (!name
) name
= "";
1497 if (!regtype
) return kDNSServiceErr_BadParam
;
1498 if (!domain
) domain
= "";
1499 if (!host
) host
= "";
1500 if (!txtRecord
) txtRecord
= (void*)"";
1502 // No callback must have auto-rename
1503 if (!callBack
&& (flags
& kDNSServiceFlagsNoAutoRename
)) return kDNSServiceErr_BadParam
;
1505 if ((interfaceIndex
== kDNSServiceInterfaceIndexAny
) && includeP2PWithIndexAny())
1506 flags
|= kDNSServiceFlagsIncludeP2P
;
1508 err
= ConnectToServer(sdRef
, flags
, reg_service_request
, callBack
? handle_regservice_response
: NULL
, callBack
, context
);
1509 if (err
) return err
; // On error ConnectToServer leaves *sdRef set to NULL
1511 len
= sizeof(DNSServiceFlags
);
1512 len
+= sizeof(uint32_t); // interfaceIndex
1513 len
+= strlen(name
) + strlen(regtype
) + strlen(domain
) + strlen(host
) + 4;
1514 len
+= 2 * sizeof(uint16_t); // port, txtLen
1517 hdr
= create_hdr(reg_service_request
, &len
, &ptr
, (*sdRef
)->primary
? 1 : 0, *sdRef
);
1518 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
1520 // If it is going over a shared connection, then don't set the IPC_FLAGS_NOREPLY
1521 // as it affects all the operations over the shared connection. This is not
1522 // a normal case and hence receiving the response back from the daemon and
1523 // discarding it in ConnectionResponse is okay.
1525 if (!(flags
& kDNSServiceFlagsShareConnection
) && !callBack
) hdr
->ipc_flags
|= IPC_FLAGS_NOREPLY
;
1527 put_flags(flags
, &ptr
);
1528 put_uint32(interfaceIndex
, &ptr
);
1529 put_string(name
, &ptr
);
1530 put_string(regtype
, &ptr
);
1531 put_string(domain
, &ptr
);
1532 put_string(host
, &ptr
);
1535 put_uint16(txtLen
, &ptr
);
1536 put_rdata(txtLen
, txtRecord
, &ptr
);
1538 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1539 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
1543 static void handle_enumeration_response(DNSServiceOp
*const sdr
, const CallbackHeader
*const cbh
, const char *data
, const char *const end
)
1545 char domain
[kDNSServiceMaxDomainName
];
1546 get_string(&data
, end
, domain
, kDNSServiceMaxDomainName
);
1547 if (!data
) syslog(LOG_WARNING
, "dnssd_clientstub handle_enumeration_response: error reading result from daemon");
1548 else ((DNSServiceDomainEnumReply
)sdr
->AppCallback
)(sdr
, cbh
->cb_flags
, cbh
->cb_interface
, cbh
->cb_err
, domain
, sdr
->AppContext
);
1549 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1552 DNSServiceErrorType DNSSD_API DNSServiceEnumerateDomains
1554 DNSServiceRef
*sdRef
,
1555 DNSServiceFlags flags
,
1556 uint32_t interfaceIndex
,
1557 DNSServiceDomainEnumReply callBack
,
1564 DNSServiceErrorType err
;
1566 int f1
= (flags
& kDNSServiceFlagsBrowseDomains
) != 0;
1567 int f2
= (flags
& kDNSServiceFlagsRegistrationDomains
) != 0;
1568 if (f1
+ f2
!= 1) return kDNSServiceErr_BadParam
;
1570 err
= ConnectToServer(sdRef
, flags
, enumeration_request
, handle_enumeration_response
, callBack
, context
);
1571 if (err
) return err
; // On error ConnectToServer leaves *sdRef set to NULL
1573 len
= sizeof(DNSServiceFlags
);
1574 len
+= sizeof(uint32_t);
1576 hdr
= create_hdr(enumeration_request
, &len
, &ptr
, (*sdRef
)->primary
? 1 : 0, *sdRef
);
1577 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
1579 put_flags(flags
, &ptr
);
1580 put_uint32(interfaceIndex
, &ptr
);
1582 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1583 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
1587 static void ConnectionResponse(DNSServiceOp
*const sdr
, const CallbackHeader
*const cbh
, const char *const data
, const char *const end
)
1589 DNSRecordRef rref
= cbh
->ipc_hdr
.client_context
.context
;
1590 (void)data
; // Unused
1592 //printf("ConnectionResponse got %d\n", cbh->ipc_hdr.op);
1593 if (cbh
->ipc_hdr
.op
!= reg_record_reply_op
)
1595 // When using kDNSServiceFlagsShareConnection, need to search the list of associated DNSServiceOps
1596 // to find the one this response is intended for, and then call through to its ProcessReply handler.
1597 // We start with our first subordinate DNSServiceRef -- don't want to accidentally match the parent DNSServiceRef.
1598 DNSServiceOp
*op
= sdr
->next
;
1599 while (op
&& (op
->uid
.u32
[0] != cbh
->ipc_hdr
.client_context
.u32
[0] || op
->uid
.u32
[1] != cbh
->ipc_hdr
.client_context
.u32
[1]))
1601 // Note: We may sometimes not find a matching DNSServiceOp, in the case where the client has
1602 // cancelled the subordinate DNSServiceOp, but there are still messages in the pipeline from the daemon
1603 if (op
&& op
->ProcessReply
) op
->ProcessReply(op
, cbh
, data
, end
);
1604 // WARNING: Don't touch op or sdr after this -- client may have called DNSServiceRefDeallocate
1608 if (sdr
->op
== connection_request
)
1609 rref
->AppCallback(rref
->sdr
, rref
, cbh
->cb_flags
, cbh
->cb_err
, rref
->AppContext
);
1612 syslog(LOG_WARNING
, "dnssd_clientstub ConnectionResponse: sdr->op != connection_request");
1613 rref
->AppCallback(rref
->sdr
, rref
, 0, kDNSServiceErr_Unknown
, rref
->AppContext
);
1615 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1618 DNSServiceErrorType DNSSD_API
DNSServiceCreateConnection(DNSServiceRef
*sdRef
)
1623 DNSServiceErrorType err
= ConnectToServer(sdRef
, 0, connection_request
, ConnectionResponse
, NULL
, NULL
);
1624 if (err
) return err
; // On error ConnectToServer leaves *sdRef set to NULL
1626 hdr
= create_hdr(connection_request
, &len
, &ptr
, 0, *sdRef
);
1627 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
1629 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1630 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
1634 DNSServiceErrorType DNSSD_API DNSServiceRegisterRecord
1636 DNSServiceRef sdRef
,
1637 DNSRecordRef
*RecordRef
,
1638 DNSServiceFlags flags
,
1639 uint32_t interfaceIndex
,
1640 const char *fullname
,
1646 DNSServiceRegisterRecordReply callBack
,
1652 ipc_msg_hdr
*hdr
= NULL
;
1653 DNSRecordRef rref
= NULL
;
1655 int f1
= (flags
& kDNSServiceFlagsShared
) != 0;
1656 int f2
= (flags
& kDNSServiceFlagsUnique
) != 0;
1657 if (f1
+ f2
!= 1) return kDNSServiceErr_BadParam
;
1659 if ((interfaceIndex
== kDNSServiceInterfaceIndexAny
) && includeP2PWithIndexAny())
1660 flags
|= kDNSServiceFlagsIncludeP2P
;
1662 if (!sdRef
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRegisterRecord called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam
; }
1664 if (!DNSServiceRefValid(sdRef
))
1666 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRegisterRecord called with invalid DNSServiceRef %p %08X %08X", sdRef
, sdRef
->sockfd
, sdRef
->validator
);
1667 return kDNSServiceErr_BadReference
;
1670 if (sdRef
->op
!= connection_request
)
1672 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRegisterRecord called with non-DNSServiceCreateConnection DNSServiceRef %p %d", sdRef
, sdRef
->op
);
1673 return kDNSServiceErr_BadReference
;
1678 len
= sizeof(DNSServiceFlags
);
1679 len
+= 2 * sizeof(uint32_t); // interfaceIndex, ttl
1680 len
+= 3 * sizeof(uint16_t); // rrtype, rrclass, rdlen
1681 len
+= strlen(fullname
) + 1;
1684 hdr
= create_hdr(reg_record_request
, &len
, &ptr
, 1, sdRef
);
1685 if (!hdr
) return kDNSServiceErr_NoMemory
;
1687 put_flags(flags
, &ptr
);
1688 put_uint32(interfaceIndex
, &ptr
);
1689 put_string(fullname
, &ptr
);
1690 put_uint16(rrtype
, &ptr
);
1691 put_uint16(rrclass
, &ptr
);
1692 put_uint16(rdlen
, &ptr
);
1693 put_rdata(rdlen
, rdata
, &ptr
);
1694 put_uint32(ttl
, &ptr
);
1696 rref
= malloc(sizeof(DNSRecord
));
1697 if (!rref
) { free(hdr
); return kDNSServiceErr_NoMemory
; }
1698 rref
->AppContext
= context
;
1699 rref
->AppCallback
= callBack
;
1700 rref
->record_index
= sdRef
->max_index
++;
1702 rref
->recnext
= NULL
;
1704 hdr
->client_context
.context
= rref
;
1705 hdr
->reg_index
= rref
->record_index
;
1708 while (*p
) p
= &(*p
)->recnext
;
1711 return deliver_request(hdr
, sdRef
); // Will free hdr for us
1714 // sdRef returned by DNSServiceRegister()
1715 DNSServiceErrorType DNSSD_API DNSServiceAddRecord
1717 DNSServiceRef sdRef
,
1718 DNSRecordRef
*RecordRef
,
1719 DNSServiceFlags flags
,
1732 if (!sdRef
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceAddRecord called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam
; }
1733 if (!RecordRef
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceAddRecord called with NULL DNSRecordRef pointer"); return kDNSServiceErr_BadParam
; }
1734 if (sdRef
->op
!= reg_service_request
)
1736 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceAddRecord called with non-DNSServiceRegister DNSServiceRef %p %d", sdRef
, sdRef
->op
);
1737 return kDNSServiceErr_BadReference
;
1740 if (!DNSServiceRefValid(sdRef
))
1742 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceAddRecord called with invalid DNSServiceRef %p %08X %08X", sdRef
, sdRef
->sockfd
, sdRef
->validator
);
1743 return kDNSServiceErr_BadReference
;
1748 len
+= 2 * sizeof(uint16_t); // rrtype, rdlen
1750 len
+= sizeof(uint32_t);
1751 len
+= sizeof(DNSServiceFlags
);
1753 hdr
= create_hdr(add_record_request
, &len
, &ptr
, 1, sdRef
);
1754 if (!hdr
) return kDNSServiceErr_NoMemory
;
1755 put_flags(flags
, &ptr
);
1756 put_uint16(rrtype
, &ptr
);
1757 put_uint16(rdlen
, &ptr
);
1758 put_rdata(rdlen
, rdata
, &ptr
);
1759 put_uint32(ttl
, &ptr
);
1761 rref
= malloc(sizeof(DNSRecord
));
1762 if (!rref
) { free(hdr
); return kDNSServiceErr_NoMemory
; }
1763 rref
->AppContext
= NULL
;
1764 rref
->AppCallback
= NULL
;
1765 rref
->record_index
= sdRef
->max_index
++;
1767 rref
->recnext
= NULL
;
1769 hdr
->reg_index
= rref
->record_index
;
1772 while (*p
) p
= &(*p
)->recnext
;
1775 return deliver_request(hdr
, sdRef
); // Will free hdr for us
1778 // DNSRecordRef returned by DNSServiceRegisterRecord or DNSServiceAddRecord
1779 DNSServiceErrorType DNSSD_API DNSServiceUpdateRecord
1781 DNSServiceRef sdRef
,
1782 DNSRecordRef RecordRef
,
1783 DNSServiceFlags flags
,
1793 if (!sdRef
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceUpdateRecord called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam
; }
1795 if (!DNSServiceRefValid(sdRef
))
1797 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceUpdateRecord called with invalid DNSServiceRef %p %08X %08X", sdRef
, sdRef
->sockfd
, sdRef
->validator
);
1798 return kDNSServiceErr_BadReference
;
1801 // Note: RecordRef is allowed to be NULL
1803 len
+= sizeof(uint16_t);
1805 len
+= sizeof(uint32_t);
1806 len
+= sizeof(DNSServiceFlags
);
1808 hdr
= create_hdr(update_record_request
, &len
, &ptr
, 1, sdRef
);
1809 if (!hdr
) return kDNSServiceErr_NoMemory
;
1810 hdr
->reg_index
= RecordRef
? RecordRef
->record_index
: TXT_RECORD_INDEX
;
1811 put_flags(flags
, &ptr
);
1812 put_uint16(rdlen
, &ptr
);
1813 put_rdata(rdlen
, rdata
, &ptr
);
1814 put_uint32(ttl
, &ptr
);
1815 return deliver_request(hdr
, sdRef
); // Will free hdr for us
1818 DNSServiceErrorType DNSSD_API DNSServiceRemoveRecord
1820 DNSServiceRef sdRef
,
1821 DNSRecordRef RecordRef
,
1822 DNSServiceFlags flags
1828 DNSServiceErrorType err
;
1830 if (!sdRef
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRemoveRecord called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam
; }
1831 if (!RecordRef
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRemoveRecord called with NULL DNSRecordRef"); return kDNSServiceErr_BadParam
; }
1832 if (!sdRef
->max_index
) { syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRemoveRecord called with bad DNSServiceRef"); return kDNSServiceErr_BadReference
; }
1834 if (!DNSServiceRefValid(sdRef
))
1836 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceRemoveRecord called with invalid DNSServiceRef %p %08X %08X", sdRef
, sdRef
->sockfd
, sdRef
->validator
);
1837 return kDNSServiceErr_BadReference
;
1840 len
+= sizeof(flags
);
1841 hdr
= create_hdr(remove_record_request
, &len
, &ptr
, 1, sdRef
);
1842 if (!hdr
) return kDNSServiceErr_NoMemory
;
1843 hdr
->reg_index
= RecordRef
->record_index
;
1844 put_flags(flags
, &ptr
);
1845 err
= deliver_request(hdr
, sdRef
); // Will free hdr for us
1848 // This RecordRef could have been allocated in DNSServiceRegisterRecord or DNSServiceAddRecord.
1849 // If so, delink from the list before freeing
1850 DNSRecord
**p
= &sdRef
->rec
;
1851 while (*p
&& *p
!= RecordRef
) p
= &(*p
)->recnext
;
1852 if (*p
) *p
= RecordRef
->recnext
;
1858 DNSServiceErrorType DNSSD_API DNSServiceReconfirmRecord
1860 DNSServiceFlags flags
,
1861 uint32_t interfaceIndex
,
1862 const char *fullname
,
1874 DNSServiceErrorType err
= ConnectToServer(&tmp
, flags
, reconfirm_record_request
, NULL
, NULL
, NULL
);
1875 if (err
) return err
;
1877 len
= sizeof(DNSServiceFlags
);
1878 len
+= sizeof(uint32_t);
1879 len
+= strlen(fullname
) + 1;
1880 len
+= 3 * sizeof(uint16_t);
1882 hdr
= create_hdr(reconfirm_record_request
, &len
, &ptr
, 0, tmp
);
1883 if (!hdr
) { DNSServiceRefDeallocate(tmp
); return kDNSServiceErr_NoMemory
; }
1885 put_flags(flags
, &ptr
);
1886 put_uint32(interfaceIndex
, &ptr
);
1887 put_string(fullname
, &ptr
);
1888 put_uint16(rrtype
, &ptr
);
1889 put_uint16(rrclass
, &ptr
);
1890 put_uint16(rdlen
, &ptr
);
1891 put_rdata(rdlen
, rdata
, &ptr
);
1893 err
= deliver_request(hdr
, tmp
); // Will free hdr for us
1894 DNSServiceRefDeallocate(tmp
);
1898 static void handle_port_mapping_response(DNSServiceOp
*const sdr
, const CallbackHeader
*const cbh
, const char *data
, const char *const end
)
1900 union { uint32_t l
; u_char b
[4]; } addr
;
1902 union { uint16_t s
; u_char b
[2]; } internalPort
;
1903 union { uint16_t s
; u_char b
[2]; } externalPort
;
1906 if (!data
|| data
+ 13 > end
) goto fail
;
1908 addr
.b
[0] = *data
++;
1909 addr
.b
[1] = *data
++;
1910 addr
.b
[2] = *data
++;
1911 addr
.b
[3] = *data
++;
1913 internalPort
.b
[0] = *data
++;
1914 internalPort
.b
[1] = *data
++;
1915 externalPort
.b
[0] = *data
++;
1916 externalPort
.b
[1] = *data
++;
1917 ttl
= get_uint32(&data
, end
);
1918 if (!data
) goto fail
;
1920 ((DNSServiceNATPortMappingReply
)sdr
->AppCallback
)(sdr
, cbh
->cb_flags
, cbh
->cb_interface
, cbh
->cb_err
, addr
.l
, protocol
, internalPort
.s
, externalPort
.s
, ttl
, sdr
->AppContext
);
1922 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1925 syslog(LOG_WARNING
, "dnssd_clientstub handle_port_mapping_response: error reading result from daemon");
1928 DNSServiceErrorType DNSSD_API DNSServiceNATPortMappingCreate
1930 DNSServiceRef
*sdRef
,
1931 DNSServiceFlags flags
,
1932 uint32_t interfaceIndex
,
1933 uint32_t protocol
, /* TCP and/or UDP */
1934 uint16_t internalPortInNetworkByteOrder
,
1935 uint16_t externalPortInNetworkByteOrder
,
1936 uint32_t ttl
, /* time to live in seconds */
1937 DNSServiceNATPortMappingReply callBack
,
1938 void *context
/* may be NULL */
1944 union { uint16_t s
; u_char b
[2]; } internalPort
= { internalPortInNetworkByteOrder
};
1945 union { uint16_t s
; u_char b
[2]; } externalPort
= { externalPortInNetworkByteOrder
};
1947 DNSServiceErrorType err
= ConnectToServer(sdRef
, flags
, port_mapping_request
, handle_port_mapping_response
, callBack
, context
);
1948 if (err
) return err
; // On error ConnectToServer leaves *sdRef set to NULL
1950 len
= sizeof(flags
);
1951 len
+= sizeof(interfaceIndex
);
1952 len
+= sizeof(protocol
);
1953 len
+= sizeof(internalPort
);
1954 len
+= sizeof(externalPort
);
1957 hdr
= create_hdr(port_mapping_request
, &len
, &ptr
, (*sdRef
)->primary
? 1 : 0, *sdRef
);
1958 if (!hdr
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; return kDNSServiceErr_NoMemory
; }
1960 put_flags(flags
, &ptr
);
1961 put_uint32(interfaceIndex
, &ptr
);
1962 put_uint32(protocol
, &ptr
);
1963 *ptr
++ = internalPort
.b
[0];
1964 *ptr
++ = internalPort
.b
[1];
1965 *ptr
++ = externalPort
.b
[0];
1966 *ptr
++ = externalPort
.b
[1];
1967 put_uint32(ttl
, &ptr
);
1969 err
= deliver_request(hdr
, *sdRef
); // Will free hdr for us
1970 if (err
) { DNSServiceRefDeallocate(*sdRef
); *sdRef
= NULL
; }
1974 #if _DNS_SD_LIBDISPATCH
1975 DNSServiceErrorType DNSSD_API DNSServiceSetDispatchQueue
1977 DNSServiceRef service
,
1978 dispatch_queue_t queue
1981 int dnssd_fd
= DNSServiceRefSockFD(service
);
1982 if (dnssd_fd
== dnssd_InvalidSocket
) return kDNSServiceErr_BadParam
;
1985 syslog(LOG_WARNING
, "dnssd_clientstub: DNSServiceSetDispatchQueue dispatch queue NULL");
1986 return kDNSServiceErr_BadParam
;
1988 if (service
->disp_queue
)
1990 syslog(LOG_WARNING
, "dnssd_clientstub DNSServiceSetDispatchQueue dispatch queue set already");
1991 return kDNSServiceErr_BadParam
;
1993 if (service
->disp_source
)
1995 syslog(LOG_WARNING
, "DNSServiceSetDispatchQueue dispatch source set already");
1996 return kDNSServiceErr_BadParam
;
1998 service
->disp_source
= dispatch_source_create(DISPATCH_SOURCE_TYPE_READ
, dnssd_fd
, 0, queue
);
1999 if (!service
->disp_source
)
2001 syslog(LOG_WARNING
, "DNSServiceSetDispatchQueue dispatch_source_create failed");
2002 return kDNSServiceErr_NoMemory
;
2004 service
->disp_queue
= queue
;
2005 dispatch_source_set_event_handler(service
->disp_source
, ^{DNSServiceProcessResult(service
);});
2006 dispatch_source_set_cancel_handler(service
->disp_source
, ^{dnssd_close(dnssd_fd
);});
2007 dispatch_resume(service
->disp_source
);
2008 return kDNSServiceErr_NoError
;
2010 #endif // _DNS_SD_LIBDISPATCH
2012 #if !defined(_WIN32)
2014 static void DNSSD_API
SleepKeepaliveCallback(DNSServiceRef sdRef
, DNSRecordRef rec
, const DNSServiceFlags flags
,
2015 DNSServiceErrorType errorCode
, void *context
)
2017 SleepKAContext
*ka
= (SleepKAContext
*)context
;
2018 (void)rec
; // Unused
2019 (void)flags
; // Unused
2021 if (sdRef
->kacontext
!= context
)
2022 syslog(LOG_WARNING
, "SleepKeepaliveCallback context mismatch");
2024 if (ka
->AppCallback
)
2025 ((DNSServiceSleepKeepaliveReply
)ka
->AppCallback
)(sdRef
, errorCode
, ka
->AppContext
);
2028 DNSServiceErrorType DNSSD_API DNSServiceSleepKeepalive
2030 DNSServiceRef
*sdRef
,
2031 DNSServiceFlags flags
,
2033 unsigned int timeout
,
2034 DNSServiceSleepKeepaliveReply callBack
,
2038 char source_str
[INET6_ADDRSTRLEN
];
2039 char target_str
[INET6_ADDRSTRLEN
];
2040 struct sockaddr_storage lss
;
2041 struct sockaddr_storage rss
;
2042 socklen_t len1
, len2
;
2043 unsigned int len
, proxyreclen
;
2045 DNSServiceErrorType err
;
2046 DNSRecordRef record
= NULL
;
2050 unsigned int i
, unique
;
2053 (void) flags
; //unused
2054 if (!timeout
) return kDNSServiceErr_BadParam
;
2058 if (getsockname(fd
, (struct sockaddr
*)&lss
, &len1
) < 0)
2060 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive: getsockname %d\n", errno
);
2061 return kDNSServiceErr_BadParam
;
2065 if (getpeername(fd
, (struct sockaddr
*)&rss
, &len2
) < 0)
2067 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive: getpeername %d\n", errno
);
2068 return kDNSServiceErr_BadParam
;
2073 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive local/remote info not same");
2074 return kDNSServiceErr_Unknown
;
2078 if (lss
.ss_family
== AF_INET
)
2080 struct sockaddr_in
*sl
= (struct sockaddr_in
*)&lss
;
2081 struct sockaddr_in
*sr
= (struct sockaddr_in
*)&rss
;
2082 unsigned char *ptr
= (unsigned char *)&sl
->sin_addr
;
2084 if (!inet_ntop(AF_INET
, (const void *)&sr
->sin_addr
, target_str
, sizeof (target_str
)))
2086 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive remote info failed %d", errno
);
2087 return kDNSServiceErr_Unknown
;
2089 if (!inet_ntop(AF_INET
, (const void *)&sl
->sin_addr
, source_str
, sizeof (source_str
)))
2091 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive local info failed %d", errno
);
2092 return kDNSServiceErr_Unknown
;
2094 // Sum of all bytes in the local address and port should result in a unique
2095 // number in the local network
2096 for (i
= 0; i
< sizeof(struct in_addr
); i
++)
2098 unique
+= sl
->sin_port
;
2099 len
= snprintf(buf
+1, sizeof(buf
) - 1, "t=%u h=%s d=%s l=%u r=%u", timeout
, source_str
, target_str
, ntohs(sl
->sin_port
), ntohs(sr
->sin_port
));
2103 struct sockaddr_in6
*sl6
= (struct sockaddr_in6
*)&lss
;
2104 struct sockaddr_in6
*sr6
= (struct sockaddr_in6
*)&rss
;
2105 unsigned char *ptr
= (unsigned char *)&sl6
->sin6_addr
;
2107 if (!inet_ntop(AF_INET6
, (const void *)&sr6
->sin6_addr
, target_str
, sizeof (target_str
)))
2109 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive remote6 info failed %d", errno
);
2110 return kDNSServiceErr_Unknown
;
2112 if (!inet_ntop(AF_INET6
, (const void *)&sl6
->sin6_addr
, source_str
, sizeof (source_str
)))
2114 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive local6 info failed %d", errno
);
2115 return kDNSServiceErr_Unknown
;
2117 for (i
= 0; i
< sizeof(struct in6_addr
); i
++)
2119 unique
+= sl6
->sin6_port
;
2120 len
= snprintf(buf
+1, sizeof(buf
) - 1, "t=%u H=%s D=%s l=%u r=%u", timeout
, source_str
, target_str
, ntohs(sl6
->sin6_port
), ntohs(sr6
->sin6_port
));
2123 if (len
>= (sizeof(buf
) - 1))
2125 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive could not fit local/remote info");
2126 return kDNSServiceErr_Unknown
;
2128 // Include the NULL byte also in the first byte. The total length of the record includes the
2131 proxyreclen
= len
+ 2;
2133 len
= snprintf(name
, sizeof(name
), "%u", unique
);
2134 if (len
>= sizeof(name
))
2136 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive could not fit unique");
2137 return kDNSServiceErr_Unknown
;
2140 len
= snprintf(recname
, sizeof(recname
), "%s.%s", name
, "_keepalive._dns-sd._udp.local");
2141 if (len
>= sizeof(recname
))
2143 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive could not fit name");
2144 return kDNSServiceErr_Unknown
;
2147 ka
= malloc(sizeof(SleepKAContext
));
2148 if (!ka
) return kDNSServiceErr_NoMemory
;
2149 ka
->AppCallback
= callBack
;
2150 ka
->AppContext
= context
;
2152 err
= DNSServiceCreateConnection(sdRef
);
2155 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive cannot create connection");
2160 // we don't care about the "record". When sdRef gets deallocated later, it will be freed too
2161 err
= DNSServiceRegisterRecord(*sdRef
, &record
, kDNSServiceFlagsUnique
, 0, recname
,
2162 kDNSServiceType_NULL
, kDNSServiceClass_IN
, proxyreclen
, buf
, kDNSServiceInterfaceIndexAny
, SleepKeepaliveCallback
, ka
);
2165 syslog(LOG_WARNING
, "DNSServiceSleepKeepalive cannot create connection");
2169 (*sdRef
)->kacontext
= ka
;
2170 return kDNSServiceErr_NoError
;