• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* -*- Mode: C; tab-width: 4 -*-
2  *
3  * Copyright (c) 2003-2004, Apple Computer, Inc. All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are met:
7  *
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.
16  *
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.
27  */
28 
29 #include <errno.h>
30 #include <stdlib.h>
31 
32 #include "dnssd_ipc.h"
33 
34 static int gDaemonErr = kDNSServiceErr_NoError;
35 
36 #if defined(_WIN32)
37 
38 	#define _SSIZE_T
39 	#include <CommonServices.h>
40 	#include <DebugServices.h>
41 	#include <winsock2.h>
42 	#include <ws2tcpip.h>
43 	#include <windows.h>
44 	#include <stdarg.h>
45 
46 	#define sockaddr_mdns sockaddr_in
47 	#define AF_MDNS AF_INET
48 
49 	// Disable warning: "'type cast' : from data pointer 'void *' to function pointer"
50 	#pragma warning(disable:4055)
51 
52 	// Disable warning: "nonstandard extension, function/data pointer conversion in expression"
53 	#pragma warning(disable:4152)
54 
55 	extern BOOL IsSystemServiceDisabled();
56 
57 	#define sleep(X) Sleep((X) * 1000)
58 
59 	static int g_initWinsock = 0;
60 	#define LOG_WARNING kDebugLevelWarning
61 	#define LOG_INFO kDebugLevelInfo
syslog(int priority,const char * message,...)62 	static void syslog( int priority, const char * message, ...)
63 		{
64 		va_list args;
65 		int len;
66 		char * buffer;
67 		DWORD err = WSAGetLastError();
68 		(void) priority;
69 		va_start( args, message );
70 		len = _vscprintf( message, args ) + 1;
71 		buffer = malloc( len * sizeof(char) );
72 		if ( buffer ) { vsprintf( buffer, message, args ); OutputDebugString( buffer ); free( buffer ); }
73 		WSASetLastError( err );
74 		}
75 #else
76 
77 #ifndef __ANDROID__
78 	#include <sys/fcntl.h>		// For O_RDWR etc.
79 #else
80 	#include <fcntl.h>
81 	#define LOG_TAG "libmdns"
82 #endif  // !__ANDROID__
83 	#include <sys/time.h>
84 	#include <sys/socket.h>
85 	#include <syslog.h>
86 
87 	#define sockaddr_mdns sockaddr_un
88 	#define AF_MDNS AF_LOCAL
89 
90 #endif
91 
92 // <rdar://problem/4096913> Specifies how many times we'll try and connect to the server.
93 
94 #define DNSSD_CLIENT_MAXTRIES 4
95 
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
98 
99 #define DNSSD_CLIENT_TIMEOUT 10  // In seconds
100 
101 #ifndef CTL_PATH_PREFIX
102 #define CTL_PATH_PREFIX "/var/tmp/dnssd_result_socket."
103 #endif
104 
105 typedef struct
106 	{
107 	ipc_msg_hdr         ipc_hdr;
108 	DNSServiceFlags     cb_flags;
109 	uint32_t            cb_interface;
110 	DNSServiceErrorType cb_err;
111 	} CallbackHeader;
112 
113 typedef struct _DNSServiceRef_t DNSServiceOp;
114 typedef struct _DNSRecordRef_t DNSRecord;
115 
116 // client stub callback to process message from server and deliver results to client application
117 typedef void (*ProcessReplyFn)(DNSServiceOp *const sdr, const CallbackHeader *const cbh, const char *msg, const char *const end);
118 
119 #define ValidatorBits 0x12345678
120 #define DNSServiceRefValid(X) (dnssd_SocketValid((X)->sockfd) && (((X)->sockfd ^ (X)->validator) == ValidatorBits))
121 
122 // When using kDNSServiceFlagsShareConnection, there is one primary _DNSServiceOp_t, and zero or more subordinates
123 // For the primary, the 'next' field points to the first subordinate, and its 'next' field points to the next, and so on.
124 // For the primary, the 'primary' field is NULL; for subordinates the 'primary' field points back to the associated primary
125 //
126 // _DNS_SD_LIBDISPATCH is defined where libdispatch/GCD is available. This does not mean that the application will use the
127 // DNSServiceSetDispatchQueue API. Hence any new code guarded with _DNS_SD_LIBDISPATCH should still be backwards compatible.
128 struct _DNSServiceRef_t
129 	{
130 	DNSServiceOp     *next;				// For shared connection
131 	DNSServiceOp     *primary;			// For shared connection
132 	dnssd_sock_t      sockfd;			// Connected socket between client and daemon
133 	dnssd_sock_t      validator;		// Used to detect memory corruption, double disposals, etc.
134 	client_context_t  uid;				// For shared connection requests, each subordinate DNSServiceRef has its own ID,
135 										// unique within the scope of the same shared parent DNSServiceRef
136 	uint32_t          op;				// request_op_t or reply_op_t
137 	uint32_t          max_index;		// Largest assigned record index - 0 if no additional records registered
138 	uint32_t          logcounter;		// Counter used to control number of syslog messages we write
139 	int              *moreptr;			// Set while DNSServiceProcessResult working on this particular DNSServiceRef
140 	ProcessReplyFn    ProcessReply;		// Function pointer to the code to handle received messages
141 	void             *AppCallback;		// Client callback function and context
142 	void             *AppContext;
143 	DNSRecord        *rec;
144 #if _DNS_SD_LIBDISPATCH
145 	dispatch_source_t disp_source;
146 	dispatch_queue_t  disp_queue;
147 #endif
148 	};
149 
150 struct _DNSRecordRef_t
151 	{
152 	DNSRecord		*recnext;
153 	void *AppContext;
154 	DNSServiceRegisterRecordReply AppCallback;
155 	DNSRecordRef recref;
156 	uint32_t record_index;  // index is unique to the ServiceDiscoveryRef
157 	DNSServiceOp *sdr;
158 	};
159 
160 // Write len bytes. Return 0 on success, -1 on error
write_all(dnssd_sock_t sd,char * buf,size_t len)161 static int write_all(dnssd_sock_t sd, char *buf, size_t len)
162 	{
163 	// Don't use "MSG_WAITALL"; it returns "Invalid argument" on some Linux versions; use an explicit while() loop instead.
164 	//if (send(sd, buf, len, MSG_WAITALL) != len) return -1;
165 	while (len)
166 		{
167 		ssize_t num_written = send(sd, buf, (long)len, 0);
168 		if (num_written < 0 || (size_t)num_written > len)
169 			{
170 			// Should never happen. If it does, it indicates some OS bug,
171 			// or that the mDNSResponder daemon crashed (which should never happen).
172 			#if !defined(__ppc__) && defined(SO_ISDEFUNCT)
173 			int defunct;
174 			socklen_t dlen = sizeof (defunct);
175 			if (getsockopt(sd, SOL_SOCKET, SO_ISDEFUNCT, &defunct, &dlen) < 0)
176 				syslog(LOG_WARNING, "dnssd_clientstub write_all: SO_ISDEFUNCT failed %d %s", dnssd_errno, dnssd_strerror(dnssd_errno));
177 			if (!defunct)
178 				syslog(LOG_WARNING, "dnssd_clientstub write_all(%d) failed %ld/%ld %d %s", sd,
179 					(long)num_written, (long)len,
180 					(num_written < 0) ? dnssd_errno                 : 0,
181 					(num_written < 0) ? dnssd_strerror(dnssd_errno) : "");
182 			else
183 				syslog(LOG_INFO, "dnssd_clientstub write_all(%d) DEFUNCT", sd);
184 			#else
185 			syslog(LOG_WARNING, "dnssd_clientstub write_all(%d) failed %ld/%ld %d %s", sd,
186 				(long)num_written, (long)len,
187 				(num_written < 0) ? dnssd_errno                 : 0,
188 				(num_written < 0) ? dnssd_strerror(dnssd_errno) : "");
189 			#endif
190 			return -1;
191 			}
192 		buf += num_written;
193 		len -= num_written;
194 		}
195 	return 0;
196 	}
197 
198 enum { read_all_success = 0, read_all_fail = -1, read_all_wouldblock = -2 };
199 
200 // Read len bytes. Return 0 on success, read_all_fail on error, or read_all_wouldblock for
read_all(dnssd_sock_t sd,char * buf,int len)201 static int read_all(dnssd_sock_t sd, char *buf, int len)
202 	{
203 	// Don't use "MSG_WAITALL"; it returns "Invalid argument" on some Linux versions; use an explicit while() loop instead.
204 	//if (recv(sd, buf, len, MSG_WAITALL) != len) return -1;
205 
206 	while (len)
207 		{
208 		ssize_t num_read = recv(sd, buf, len, 0);
209 		// It is valid to get an interrupted system call error e.g., somebody attaching
210 		// in a debugger, retry without failing
211 		if ((num_read < 0) && (errno == EINTR)) { syslog(LOG_INFO, "dnssd_clientstub read_all: EINTR continue"); continue; }
212 		if ((num_read == 0) || (num_read < 0) || (num_read > len))
213 			{
214 			int printWarn = 0;
215 			int defunct = 0;
216 			// Should never happen. If it does, it indicates some OS bug,
217 			// or that the mDNSResponder daemon crashed (which should never happen).
218 #if defined(WIN32)
219 			// <rdar://problem/7481776> Suppress logs for "A non-blocking socket operation
220 			//                          could not be completed immediately"
221 			if (WSAGetLastError() != WSAEWOULDBLOCK)
222 				printWarn = 1;
223 #endif
224 #if !defined(__ppc__) && defined(SO_ISDEFUNCT)
225 			{
226 			socklen_t dlen = sizeof (defunct);
227 			if (getsockopt(sd, SOL_SOCKET, SO_ISDEFUNCT, &defunct, &dlen) < 0)
228 				syslog(LOG_WARNING, "dnssd_clientstub read_all: SO_ISDEFUNCT failed %d %s", dnssd_errno, dnssd_strerror(dnssd_errno));
229 			}
230 			if (!defunct)
231 				printWarn = 1;
232 #endif
233 			if (printWarn)
234 				syslog(LOG_WARNING, "dnssd_clientstub read_all(%d) failed %ld/%ld %d %s", sd,
235 					(long)num_read, (long)len,
236 					(num_read < 0) ? dnssd_errno                 : 0,
237 					(num_read < 0) ? dnssd_strerror(dnssd_errno) : "");
238 			else if (defunct)
239 				syslog(LOG_INFO, "dnssd_clientstub read_all(%d) DEFUNCT", sd);
240 			return (num_read < 0 && dnssd_errno == dnssd_EWOULDBLOCK) ? read_all_wouldblock : read_all_fail;
241 			}
242 		buf += num_read;
243 		len -= num_read;
244 		}
245 	return read_all_success;
246 	}
247 
248 // Returns 1 if more bytes remain to be read on socket descriptor sd, 0 otherwise
more_bytes(dnssd_sock_t sd)249 static int more_bytes(dnssd_sock_t sd)
250 	{
251 	struct timeval tv = { 0, 0 };
252 	fd_set readfds;
253 	fd_set *fs;
254 	int ret;
255 
256 	if (sd < FD_SETSIZE)
257 		{
258 		fs = &readfds;
259 		FD_ZERO(fs);
260 		}
261 	else
262 		{
263 		// Compute the number of longs needed for storing "sd". Internally fd_set is stored
264 		// as an array of longs with one bit for each fd and hence we need to compute
265 		// the number of longs needed rather than the number of bytes. If "sd" is 64, we need
266 		// two longs and not just one.
267 		int nfdbits = sizeof (unsigned long) * 8;
268 		int nlongs = (sd/nfdbits) + 1;
269 		fs = (fd_set *)calloc(nlongs, sizeof(unsigned long));
270 		if (fs == NULL) { syslog(LOG_WARNING, "dnssd_clientstub more_bytes: malloc failed"); return 0; }
271 		}
272 
273 	#ifdef __BIONIC__
274 		// The regular FD_SET() macro in Bionic is unaware of the above workaround,
275 		// and would abort on sd >= 1024. Use the unchecked __FD_SET() instead.
276 		__FD_SET(sd, fs);
277 	#else
278 		FD_SET(sd, fs);
279 	#endif
280 	ret = select((int)sd+1, fs, (fd_set*)NULL, (fd_set*)NULL, &tv);
281 	if (fs != &readfds) free(fs);
282 	return (ret > 0);
283 	}
284 
285 // Wait for daemon to write to socket
wait_for_daemon(dnssd_sock_t sock,int timeout)286 static int wait_for_daemon(dnssd_sock_t sock, int timeout)
287 	{
288 #ifndef WIN32
289 	// At this point the next operation (accept() or read()) on this socket may block for a few milliseconds waiting
290 	// for the daemon to respond, but that's okay -- the daemon is a trusted service and we know if won't take more
291 	// than a few milliseconds to respond.  So we'll forego checking for readability of the socket.
292 	(void) sock;
293 	(void) timeout;
294 #else
295 	// Windows on the other hand suffers from 3rd party software (primarily 3rd party firewall software) that
296 	// interferes with proper functioning of the TCP protocol stack. Because of this and because we depend on TCP
297 	// to communicate with the system service, we want to make sure that the next operation on this socket (accept() or
298 	// read()) doesn't block indefinitely.
299 	if (!gDaemonErr)
300 		{
301 		struct timeval tv;
302 		fd_set set;
303 
304 		FD_ZERO(&set);
305 		FD_SET(sock, &set);
306 		tv.tv_sec = timeout;
307 		tv.tv_usec = 0;
308 		if (!select((int)(sock + 1), &set, NULL, NULL, &tv))
309 			{
310 				syslog(LOG_WARNING, "dnssd_clientstub wait_for_daemon timed out");
311 				gDaemonErr = kDNSServiceErr_Timeout;
312 			}
313 		}
314 #endif
315 	return gDaemonErr;
316 	}
317 
318 /* create_hdr
319  *
320  * allocate and initialize an ipc message header. Value of len should initially be the
321  * length of the data, and is set to the value of the data plus the header. data_start
322  * is set to point to the beginning of the data section. SeparateReturnSocket should be
323  * non-zero for calls that can't receive an immediate error return value on their primary
324  * socket, and therefore require a separate return path for the error code result.
325  * if zero, the path to a control socket is appended at the beginning of the message buffer.
326  * data_start is set past this string.
327  */
create_hdr(uint32_t op,size_t * len,char ** data_start,int SeparateReturnSocket,DNSServiceOp * ref)328 static ipc_msg_hdr *create_hdr(uint32_t op, size_t *len, char **data_start, int SeparateReturnSocket, DNSServiceOp *ref)
329 	{
330 	char *msg = NULL;
331 	ipc_msg_hdr *hdr;
332 	int datalen;
333 #if !defined(USE_TCP_LOOPBACK)
334 	char ctrl_path[64] = "";	// "/var/tmp/dnssd_result_socket.xxxxxxxxxx-xxx-xxxxxx"
335 #endif
336 
337 	if (SeparateReturnSocket)
338 		{
339 #if defined(USE_TCP_LOOPBACK)
340 		*len += 2;  // Allocate space for two-byte port number
341 #elif defined(USE_NAMED_ERROR_RETURN_SOCKET)
342 		struct timeval tv;
343 		if (gettimeofday(&tv, NULL) < 0)
344 			{ syslog(LOG_WARNING, "dnssd_clientstub create_hdr: gettimeofday failed %d %s", dnssd_errno, dnssd_strerror(dnssd_errno)); return NULL; }
345 		sprintf(ctrl_path, "%s%d-%.3lx-%.6lu", CTL_PATH_PREFIX, (int)getpid(),
346 			(unsigned long)(tv.tv_sec & 0xFFF), (unsigned long)(tv.tv_usec));
347 		*len += strlen(ctrl_path) + 1;
348 #else
349 		*len += 1;		// Allocate space for single zero byte (empty C string)
350 #endif
351 		}
352 
353 	datalen = (int) *len;
354 	*len += sizeof(ipc_msg_hdr);
355 
356 	// Write message to buffer
357 	msg = malloc(*len);
358 	if (!msg) { syslog(LOG_WARNING, "dnssd_clientstub create_hdr: malloc failed"); return NULL; }
359 
360 	memset(msg, 0, *len);
361 	hdr = (ipc_msg_hdr *)msg;
362 	hdr->version                = VERSION;
363 	hdr->datalen                = datalen;
364 	hdr->ipc_flags              = 0;
365 	hdr->op                     = op;
366 	hdr->client_context         = ref->uid;
367 	hdr->reg_index              = 0;
368 	*data_start = msg + sizeof(ipc_msg_hdr);
369 #if defined(USE_TCP_LOOPBACK)
370 	// Put dummy data in for the port, since we don't know what it is yet.
371 	// The data will get filled in before we send the message. This happens in deliver_request().
372 	if (SeparateReturnSocket) put_uint16(0, data_start);
373 #else
374 	if (SeparateReturnSocket) put_string(ctrl_path, data_start);
375 #endif
376 	return hdr;
377 	}
378 
FreeDNSRecords(DNSServiceOp * sdRef)379 static void FreeDNSRecords(DNSServiceOp *sdRef)
380 	{
381 	DNSRecord *rec = sdRef->rec;
382 	while (rec)
383 		{
384 		DNSRecord *next = rec->recnext;
385 		free(rec);
386 		rec = next;
387 		}
388 	}
389 
FreeDNSServiceOp(DNSServiceOp * x)390 static void FreeDNSServiceOp(DNSServiceOp *x)
391 	{
392 	// We don't use our DNSServiceRefValid macro here because if we're cleaning up after a socket() call failed
393 	// then sockfd could legitimately contain a failing value (e.g. dnssd_InvalidSocket)
394 	if ((x->sockfd ^ x->validator) != ValidatorBits)
395 		syslog(LOG_WARNING, "dnssd_clientstub attempt to dispose invalid DNSServiceRef %p %08X %08X", x, x->sockfd, x->validator);
396 	else
397 		{
398 		x->next         = NULL;
399 		x->primary      = NULL;
400 		x->sockfd       = dnssd_InvalidSocket;
401 		x->validator    = 0xDDDDDDDD;
402 		x->op           = request_op_none;
403 		x->max_index    = 0;
404 		x->logcounter   = 0;
405 		x->moreptr      = NULL;
406 		x->ProcessReply = NULL;
407 		x->AppCallback  = NULL;
408 		x->AppContext   = NULL;
409 #if _DNS_SD_LIBDISPATCH
410 		if (x->disp_source)	dispatch_release(x->disp_source);
411 		x->disp_source  = NULL;
412 		x->disp_queue   = NULL;
413 #endif
414 		// DNSRecords may have been added to subordinate sdRef e.g., DNSServiceRegister/DNSServiceAddRecord
415 		// or on the main sdRef e.g., DNSServiceCreateConnection/DNSServiveRegisterRecord. DNSRecords may have
416 		// been freed if the application called DNSRemoveRecord
417 		FreeDNSRecords(x);
418 		free(x);
419 		}
420 	}
421 
422 // Return a connected service ref (deallocate with DNSServiceRefDeallocate)
ConnectToServer(DNSServiceRef * ref,DNSServiceFlags flags,uint32_t op,ProcessReplyFn ProcessReply,void * AppCallback,void * AppContext)423 static DNSServiceErrorType ConnectToServer(DNSServiceRef *ref, DNSServiceFlags flags, uint32_t op, ProcessReplyFn ProcessReply, void *AppCallback, void *AppContext)
424 	{
425 	#if APPLE_OSX_mDNSResponder
426 	int NumTries = DNSSD_CLIENT_MAXTRIES;
427 	#else
428 	int NumTries = 0;
429 	#endif
430 
431 	dnssd_sockaddr_t saddr;
432 	DNSServiceOp *sdr;
433 
434 	if (!ref) { syslog(LOG_WARNING, "dnssd_clientstub DNSService operation with NULL DNSServiceRef"); return kDNSServiceErr_BadParam; }
435 
436 	if (flags & kDNSServiceFlagsShareConnection)
437 		{
438 		if (!*ref)
439 			{
440 			syslog(LOG_WARNING, "dnssd_clientstub kDNSServiceFlagsShareConnection used with NULL DNSServiceRef");
441 			return kDNSServiceErr_BadParam;
442 			}
443 		if (!DNSServiceRefValid(*ref) || (*ref)->op != connection_request || (*ref)->primary)
444 			{
445 			syslog(LOG_WARNING, "dnssd_clientstub kDNSServiceFlagsShareConnection used with invalid DNSServiceRef %p %08X %08X",
446 				(*ref), (*ref)->sockfd, (*ref)->validator);
447 			*ref = NULL;
448 			return kDNSServiceErr_BadReference;
449 			}
450 		}
451 
452 	#if defined(_WIN32)
453 	if (!g_initWinsock)
454 		{
455 		WSADATA wsaData;
456 		g_initWinsock = 1;
457 		if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) { *ref = NULL; return kDNSServiceErr_ServiceNotRunning; }
458 		}
459 	// <rdar://problem/4096913> If the system service is disabled, we only want to try to connect once
460 	if (IsSystemServiceDisabled()) NumTries = DNSSD_CLIENT_MAXTRIES;
461 	#endif
462 
463 	sdr = malloc(sizeof(DNSServiceOp));
464 	if (!sdr) { syslog(LOG_WARNING, "dnssd_clientstub ConnectToServer: malloc failed"); *ref = NULL; return kDNSServiceErr_NoMemory; }
465 	sdr->next          = NULL;
466 	sdr->primary       = NULL;
467 	sdr->sockfd        = dnssd_InvalidSocket;
468 	sdr->validator     = sdr->sockfd ^ ValidatorBits;
469 	sdr->op            = op;
470 	sdr->max_index     = 0;
471 	sdr->logcounter    = 0;
472 	sdr->moreptr       = NULL;
473 	sdr->uid.u32[0]    = 0;
474 	sdr->uid.u32[1]    = 0;
475 	sdr->ProcessReply  = ProcessReply;
476 	sdr->AppCallback   = AppCallback;
477 	sdr->AppContext    = AppContext;
478 	sdr->rec           = NULL;
479 #if _DNS_SD_LIBDISPATCH
480 	sdr->disp_source   = NULL;
481 	sdr->disp_queue    = NULL;
482 #endif
483 
484 	if (flags & kDNSServiceFlagsShareConnection)
485 		{
486 		DNSServiceOp **p = &(*ref)->next;		// Append ourselves to end of primary's list
487 		while (*p) p = &(*p)->next;
488 		*p = sdr;
489 		// Preincrement counter before we use it -- it helps with debugging if we know the all-zeroes ID should never appear
490 		if (++(*ref)->uid.u32[0] == 0) ++(*ref)->uid.u32[1];	// In parent DNSServiceOp increment UID counter
491 		sdr->primary    = *ref;					// Set our primary pointer
492 		sdr->sockfd     = (*ref)->sockfd;		// Inherit primary's socket
493 		sdr->validator  = (*ref)->validator;
494 		sdr->uid        = (*ref)->uid;
495 		//printf("ConnectToServer sharing socket %d\n", sdr->sockfd);
496 		}
497 	else
498 		{
499 		#ifdef SO_NOSIGPIPE
500 		const unsigned long optval = 1;
501 		#endif
502 		*ref = NULL;
503 		sdr->sockfd    = socket(AF_DNSSD, SOCK_STREAM, 0);
504 		sdr->validator = sdr->sockfd ^ ValidatorBits;
505 		if (!dnssd_SocketValid(sdr->sockfd))
506 			{
507 			syslog(LOG_WARNING, "dnssd_clientstub ConnectToServer: socket failed %d %s", dnssd_errno, dnssd_strerror(dnssd_errno));
508 			FreeDNSServiceOp(sdr);
509 			return kDNSServiceErr_NoMemory;
510 			}
511 		#ifdef SO_NOSIGPIPE
512 		// Some environments (e.g. OS X) support turning off SIGPIPE for a socket
513 		if (setsockopt(sdr->sockfd, SOL_SOCKET, SO_NOSIGPIPE, &optval, sizeof(optval)) < 0)
514 			syslog(LOG_WARNING, "dnssd_clientstub ConnectToServer: SO_NOSIGPIPE failed %d %s", dnssd_errno, dnssd_strerror(dnssd_errno));
515 		#endif
516 		#if defined(USE_TCP_LOOPBACK)
517 		saddr.sin_family      = AF_INET;
518 		saddr.sin_addr.s_addr = inet_addr(MDNS_TCP_SERVERADDR);
519 		saddr.sin_port        = htons(MDNS_TCP_SERVERPORT);
520 		#else
521 		saddr.sun_family      = AF_LOCAL;
522 		strcpy(saddr.sun_path, MDNS_UDS_SERVERPATH);
523 		#if !defined(__ppc__) && defined(SO_DEFUNCTOK)
524 		{
525 		int defunct = 1;
526 		if (setsockopt(sdr->sockfd, SOL_SOCKET, SO_DEFUNCTOK, &defunct, sizeof(defunct)) < 0)
527 			syslog(LOG_WARNING, "dnssd_clientstub ConnectToServer: SO_DEFUNCTOK failed %d %s", dnssd_errno, dnssd_strerror(dnssd_errno));
528 		}
529 		#endif
530 		#endif
531 
532 		while (1)
533 			{
534 			int err = connect(sdr->sockfd, (struct sockaddr *) &saddr, sizeof(saddr));
535 			if (!err) break; // If we succeeded, return sdr
536 			// If we failed, then it may be because the daemon is still launching.
537 			// This can happen for processes that launch early in the boot process, while the
538 			// daemon is still coming up. Rather than fail here, we'll wait a bit and try again.
539 			// If, after four seconds, we still can't connect to the daemon,
540 			// then we give up and return a failure code.
541 			if (++NumTries < DNSSD_CLIENT_MAXTRIES) sleep(1); // Sleep a bit, then try again
542 			else { dnssd_close(sdr->sockfd); FreeDNSServiceOp(sdr); return kDNSServiceErr_ServiceNotRunning; }
543 			}
544 		//printf("ConnectToServer opened socket %d\n", sdr->sockfd);
545 		}
546 
547 	*ref = sdr;
548 	return kDNSServiceErr_NoError;
549 	}
550 
551 #define deliver_request_bailout(MSG) \
552 	do { syslog(LOG_WARNING, "dnssd_clientstub deliver_request: %s failed %d (%s)", (MSG), dnssd_errno, dnssd_strerror(dnssd_errno)); goto cleanup; } while(0)
553 
deliver_request(ipc_msg_hdr * hdr,DNSServiceOp * sdr)554 static DNSServiceErrorType deliver_request(ipc_msg_hdr *hdr, DNSServiceOp *sdr)
555 	{
556 	uint32_t datalen = hdr->datalen;	// We take a copy here because we're going to convert hdr->datalen to network byte order
557 	#if defined(USE_TCP_LOOPBACK) || defined(USE_NAMED_ERROR_RETURN_SOCKET)
558 	char *const data = (char *)hdr + sizeof(ipc_msg_hdr);
559 	#endif
560 	dnssd_sock_t listenfd = dnssd_InvalidSocket, errsd = dnssd_InvalidSocket;
561 	DNSServiceErrorType err = kDNSServiceErr_Unknown;	// Default for the "goto cleanup" cases
562 	int MakeSeparateReturnSocket = 0;
563 
564 	// Note: need to check hdr->op, not sdr->op.
565 	// hdr->op contains the code for the specific operation we're currently doing, whereas sdr->op
566 	// contains the original parent DNSServiceOp (e.g. for an add_record_request, hdr->op will be
567 	// add_record_request but the parent sdr->op will be connection_request or reg_service_request)
568 	if (sdr->primary ||
569 		hdr->op == reg_record_request || hdr->op == add_record_request || hdr->op == update_record_request || hdr->op == remove_record_request)
570 		MakeSeparateReturnSocket = 1;
571 
572 	if (!DNSServiceRefValid(sdr))
573 		{
574 		syslog(LOG_WARNING, "dnssd_clientstub deliver_request: invalid DNSServiceRef %p %08X %08X", sdr, sdr->sockfd, sdr->validator);
575 		return kDNSServiceErr_BadReference;
576 		}
577 
578 	if (!hdr) { syslog(LOG_WARNING, "dnssd_clientstub deliver_request: !hdr"); return kDNSServiceErr_Unknown; }
579 
580 	if (MakeSeparateReturnSocket)
581 		{
582 		#if defined(USE_TCP_LOOPBACK)
583 			{
584 			union { uint16_t s; u_char b[2]; } port;
585 			dnssd_sockaddr_t caddr;
586 			dnssd_socklen_t len = (dnssd_socklen_t) sizeof(caddr);
587 			listenfd = socket(AF_DNSSD, SOCK_STREAM, 0);
588 			if (!dnssd_SocketValid(listenfd)) deliver_request_bailout("TCP socket");
589 
590 			caddr.sin_family      = AF_INET;
591 			caddr.sin_port        = 0;
592 			caddr.sin_addr.s_addr = inet_addr(MDNS_TCP_SERVERADDR);
593 			if (bind(listenfd, (struct sockaddr*) &caddr, sizeof(caddr)) < 0) deliver_request_bailout("TCP bind");
594 			if (getsockname(listenfd, (struct sockaddr*) &caddr, &len)   < 0) deliver_request_bailout("TCP getsockname");
595 			if (listen(listenfd, 1)                                      < 0) deliver_request_bailout("TCP listen");
596 			port.s = caddr.sin_port;
597 			data[0] = port.b[0];  // don't switch the byte order, as the
598 			data[1] = port.b[1];  // daemon expects it in network byte order
599 			}
600 		#elif defined(USE_NAMED_ERROR_RETURN_SOCKET)
601 			{
602 			mode_t mask;
603 			int bindresult;
604 			dnssd_sockaddr_t caddr;
605 			listenfd = socket(AF_DNSSD, SOCK_STREAM, 0);
606 			if (!dnssd_SocketValid(listenfd)) deliver_request_bailout("USE_NAMED_ERROR_RETURN_SOCKET socket");
607 
608 			caddr.sun_family = AF_LOCAL;
609 			// According to Stevens (section 3.2), there is no portable way to
610 			// determine whether sa_len is defined on a particular platform.
611 			#ifndef NOT_HAVE_SA_LEN
612 			caddr.sun_len = sizeof(struct sockaddr_un);
613 			#endif
614 			strcpy(caddr.sun_path, data);
615 			mask = umask(0);
616 			bindresult = bind(listenfd, (struct sockaddr *)&caddr, sizeof(caddr));
617 			umask(mask);
618 			if (bindresult          < 0) deliver_request_bailout("USE_NAMED_ERROR_RETURN_SOCKET bind");
619 			if (listen(listenfd, 1) < 0) deliver_request_bailout("USE_NAMED_ERROR_RETURN_SOCKET listen");
620 			}
621 		#else
622 			{
623 			dnssd_sock_t sp[2];
624 			if (socketpair(AF_DNSSD, SOCK_STREAM, 0, sp) < 0) deliver_request_bailout("socketpair");
625 			else
626 				{
627 				errsd    = sp[0];	// We'll read our four-byte error code from sp[0]
628 				listenfd = sp[1];	// We'll send sp[1] to the daemon
629 				#if !defined(__ppc__) && defined(SO_DEFUNCTOK)
630 				{
631 				int defunct = 1;
632 				if (setsockopt(errsd, SOL_SOCKET, SO_DEFUNCTOK, &defunct, sizeof(defunct)) < 0)
633 					syslog(LOG_WARNING, "dnssd_clientstub ConnectToServer: SO_DEFUNCTOK failed %d %s", dnssd_errno, dnssd_strerror(dnssd_errno));
634 				}
635 				#endif
636 				}
637 			}
638 		#endif
639 		}
640 
641 #if !defined(USE_TCP_LOOPBACK) && !defined(USE_NAMED_ERROR_RETURN_SOCKET)
642 	// If we're going to make a separate error return socket, and pass it to the daemon
643 	// using sendmsg, then we'll hold back one data byte to go with it.
644 	// On some versions of Unix (including Leopard) sending a control message without
645 	// any associated data does not work reliably -- e.g. one particular issue we ran
646 	// into is that if the receiving program is in a kqueue loop waiting to be notified
647 	// of the received message, it doesn't get woken up when the control message arrives.
648 	if (MakeSeparateReturnSocket || sdr->op == send_bpf) datalen--;		// Okay to use sdr->op when checking for op == send_bpf
649 #endif
650 
651 	// At this point, our listening socket is set up and waiting, if necessary, for the daemon to connect back to
652 	ConvertHeaderBytes(hdr);
653 	//syslog(LOG_WARNING, "dnssd_clientstub deliver_request writing %lu bytes", (unsigned long)(datalen + sizeof(ipc_msg_hdr)));
654 	//if (MakeSeparateReturnSocket) syslog(LOG_WARNING, "dnssd_clientstub deliver_request name is %s", data);
655 #if TEST_SENDING_ONE_BYTE_AT_A_TIME
656 	unsigned int i;
657 	for (i=0; i<datalen + sizeof(ipc_msg_hdr); i++)
658 		{
659 		syslog(LOG_WARNING, "dnssd_clientstub deliver_request writing %d", i);
660 		if (write_all(sdr->sockfd, ((char *)hdr)+i, 1) < 0)
661 			{ syslog(LOG_WARNING, "write_all (byte %u) failed", i); goto cleanup; }
662 		usleep(10000);
663 		}
664 #else
665 	if (write_all(sdr->sockfd, (char *)hdr, datalen + sizeof(ipc_msg_hdr)) < 0)
666 		{
667 		// write_all already prints an error message if there is an error writing to
668 		// the socket except for DEFUNCT. Logging here is unnecessary and also wrong
669 		// in the case of DEFUNCT sockets
670 		syslog(LOG_INFO, "dnssd_clientstub deliver_request ERROR: write_all(%d, %lu bytes) failed",
671 			sdr->sockfd, (unsigned long)(datalen + sizeof(ipc_msg_hdr)));
672 		goto cleanup;
673 		}
674 #endif
675 
676 	if (!MakeSeparateReturnSocket) errsd = sdr->sockfd;
677 	if (MakeSeparateReturnSocket || sdr->op == send_bpf)	// Okay to use sdr->op when checking for op == send_bpf
678 		{
679 #if defined(USE_TCP_LOOPBACK) || defined(USE_NAMED_ERROR_RETURN_SOCKET)
680 		// At this point we may block in accept for a few milliseconds waiting for the daemon to connect back to us,
681 		// but that's okay -- the daemon is a trusted service and we know if won't take more than a few milliseconds to respond.
682 		dnssd_sockaddr_t daddr;
683 		dnssd_socklen_t len = sizeof(daddr);
684 		if ((err = wait_for_daemon(listenfd, DNSSD_CLIENT_TIMEOUT)) != kDNSServiceErr_NoError) goto cleanup;
685 		errsd = accept(listenfd, (struct sockaddr *)&daddr, &len);
686 		if (!dnssd_SocketValid(errsd)) deliver_request_bailout("accept");
687 #else
688 
689 #if APPLE_OSX_mDNSResponder
690 // On Leopard, the stock definitions of the CMSG_* macros in /usr/include/sys/socket.h,
691 // while arguably correct in theory, nonetheless in practice produce code that doesn't work on 64-bit machines
692 // For details see <rdar://problem/5565787> Bonjour API broken for 64-bit apps (SCM_RIGHTS sendmsg fails)
693 #undef  CMSG_DATA
694 #define CMSG_DATA(cmsg) ((unsigned char *)(cmsg) + (sizeof(struct cmsghdr)))
695 #undef  CMSG_SPACE
696 #define CMSG_SPACE(l)   ((sizeof(struct cmsghdr)) + (l))
697 #undef  CMSG_LEN
698 #define CMSG_LEN(l)     ((sizeof(struct cmsghdr)) + (l))
699 #endif
700 
701 		struct iovec vec = { ((char *)hdr) + sizeof(ipc_msg_hdr) + datalen, 1 }; // Send the last byte along with the SCM_RIGHTS
702 		struct msghdr msg;
703 		struct cmsghdr *cmsg;
704 		char cbuf[CMSG_SPACE(sizeof(dnssd_sock_t))];
705 
706 		if (sdr->op == send_bpf)	// Okay to use sdr->op when checking for op == send_bpf
707 			{
708 			int i;
709 			char p[12];		// Room for "/dev/bpf999" with terminating null
710 			for (i=0; i<100; i++)
711 				{
712 				snprintf(p, sizeof(p), "/dev/bpf%d", i);
713 				listenfd = open(p, O_RDWR, 0);
714 				//if (dnssd_SocketValid(listenfd)) syslog(LOG_WARNING, "Sending fd %d for %s", listenfd, p);
715 				if (!dnssd_SocketValid(listenfd) && dnssd_errno != EBUSY)
716 					syslog(LOG_WARNING, "Error opening %s %d (%s)", p, dnssd_errno, dnssd_strerror(dnssd_errno));
717 				if (dnssd_SocketValid(listenfd) || dnssd_errno != EBUSY) break;
718 				}
719 			}
720 
721 		msg.msg_name       = 0;
722 		msg.msg_namelen    = 0;
723 		msg.msg_iov        = &vec;
724 		msg.msg_iovlen     = 1;
725 		msg.msg_control    = cbuf;
726 		msg.msg_controllen = CMSG_LEN(sizeof(dnssd_sock_t));
727 		msg.msg_flags      = 0;
728 		cmsg = CMSG_FIRSTHDR(&msg);
729 		cmsg->cmsg_len     = CMSG_LEN(sizeof(dnssd_sock_t));
730 		cmsg->cmsg_level   = SOL_SOCKET;
731 		cmsg->cmsg_type    = SCM_RIGHTS;
732 		*((dnssd_sock_t *)CMSG_DATA(cmsg)) = listenfd;
733 
734 #if TEST_KQUEUE_CONTROL_MESSAGE_BUG
735 		sleep(1);
736 #endif
737 
738 #if DEBUG_64BIT_SCM_RIGHTS
739 		syslog(LOG_WARNING, "dnssd_clientstub sendmsg read sd=%d write sd=%d %ld %ld %ld/%ld/%ld/%ld",
740 			errsd, listenfd, sizeof(dnssd_sock_t), sizeof(void*),
741 			sizeof(struct cmsghdr) + sizeof(dnssd_sock_t),
742 			CMSG_LEN(sizeof(dnssd_sock_t)), (long)CMSG_SPACE(sizeof(dnssd_sock_t)),
743 			(long)((char*)CMSG_DATA(cmsg) + 4 - cbuf));
744 #endif // DEBUG_64BIT_SCM_RIGHTS
745 
746 		if (sendmsg(sdr->sockfd, &msg, 0) < 0)
747 			{
748 			syslog(LOG_WARNING, "dnssd_clientstub deliver_request ERROR: sendmsg failed read sd=%d write sd=%d errno %d (%s)",
749 				errsd, listenfd, dnssd_errno, dnssd_strerror(dnssd_errno));
750 			err = kDNSServiceErr_Incompatible;
751 			goto cleanup;
752 			}
753 
754 #if DEBUG_64BIT_SCM_RIGHTS
755 		syslog(LOG_WARNING, "dnssd_clientstub sendmsg read sd=%d write sd=%d okay", errsd, listenfd);
756 #endif // DEBUG_64BIT_SCM_RIGHTS
757 
758 #endif
759 		// Close our end of the socketpair *before* blocking in read_all to get the four-byte error code.
760 		// Otherwise, if the daemon closes our socket (or crashes), we block in read_all() forever
761 		// because the socket is not closed (we still have an open reference to it ourselves).
762 		dnssd_close(listenfd);
763 		listenfd = dnssd_InvalidSocket;		// Make sure we don't close it a second time in the cleanup handling below
764 		}
765 
766 	// At this point we may block in read_all for a few milliseconds waiting for the daemon to send us the error code,
767 	// but that's okay -- the daemon is a trusted service and we know if won't take more than a few milliseconds to respond.
768 	if (sdr->op == send_bpf)	// Okay to use sdr->op when checking for op == send_bpf
769 		err = kDNSServiceErr_NoError;
770 	else if ((err = wait_for_daemon(errsd, DNSSD_CLIENT_TIMEOUT)) == kDNSServiceErr_NoError)
771 		{
772 		if (read_all(errsd, (char*)&err, (int)sizeof(err)) < 0)
773 			err = kDNSServiceErr_ServiceNotRunning; // On failure read_all will have written a message to syslog for us
774 		else
775 			err = ntohl(err);
776 		}
777 
778 	//syslog(LOG_WARNING, "dnssd_clientstub deliver_request: retrieved error code %d", err);
779 
780 cleanup:
781 	if (MakeSeparateReturnSocket)
782 		{
783 		if (dnssd_SocketValid(listenfd)) dnssd_close(listenfd);
784 		if (dnssd_SocketValid(errsd))    dnssd_close(errsd);
785 #if defined(USE_NAMED_ERROR_RETURN_SOCKET)
786 		// syslog(LOG_WARNING, "dnssd_clientstub deliver_request: removing UDS: %s", data);
787 		if (unlink(data) != 0)
788 			syslog(LOG_WARNING, "dnssd_clientstub WARNING: unlink(\"%s\") failed errno %d (%s)", data, dnssd_errno, dnssd_strerror(dnssd_errno));
789 		// else syslog(LOG_WARNING, "dnssd_clientstub deliver_request: removed UDS: %s", data);
790 #endif
791 		}
792 
793 	free(hdr);
794 	return err;
795 	}
796 
DNSServiceRefSockFD(DNSServiceRef sdRef)797 int DNSSD_API DNSServiceRefSockFD(DNSServiceRef sdRef)
798 	{
799 	if (!sdRef) { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRefSockFD called with NULL DNSServiceRef"); return dnssd_InvalidSocket; }
800 
801 	if (!DNSServiceRefValid(sdRef))
802 		{
803 		syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRefSockFD called with invalid DNSServiceRef %p %08X %08X",
804 			sdRef, sdRef->sockfd, sdRef->validator);
805 		return dnssd_InvalidSocket;
806 		}
807 
808 	if (sdRef->primary)
809 		{
810 		syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRefSockFD undefined for kDNSServiceFlagsShareConnection subordinate DNSServiceRef %p", sdRef);
811 		return dnssd_InvalidSocket;
812 		}
813 
814 	return (int) sdRef->sockfd;
815 	}
816 
817 #if _DNS_SD_LIBDISPATCH
CallbackWithError(DNSServiceRef sdRef,DNSServiceErrorType error)818 static void CallbackWithError(DNSServiceRef sdRef, DNSServiceErrorType error)
819 	{
820 	DNSServiceOp *sdr = sdRef;
821 	DNSServiceOp *sdrNext;
822 	DNSRecord *rec;
823 	DNSRecord *recnext;
824 	int morebytes;
825 
826 	while (sdr)
827 		{
828 		// We can't touch the sdr after the callback as it can be deallocated in the callback
829 		sdrNext = sdr->next;
830 		morebytes = 1;
831 		sdr->moreptr = &morebytes;
832 		switch (sdr->op)
833 			{
834 			case resolve_request:
835 				if (sdr->AppCallback)((DNSServiceResolveReply)    sdr->AppCallback)(sdr, 0, 0, error, NULL, 0, 0, 0, NULL,    sdr->AppContext);
836 				break;
837 			case query_request:
838 				if (sdr->AppCallback)((DNSServiceQueryRecordReply)sdr->AppCallback)(sdr, 0, 0, error, NULL, 0, 0, 0, NULL, 0, sdr->AppContext);
839 				break;
840 			case addrinfo_request:
841 				if (sdr->AppCallback)((DNSServiceGetAddrInfoReply)sdr->AppCallback)(sdr, 0, 0, error, NULL, NULL, 0,          sdr->AppContext);
842 				break;
843 			case browse_request:
844 				if (sdr->AppCallback)((DNSServiceBrowseReply)     sdr->AppCallback)(sdr, 0, 0, error, NULL, 0, NULL,          sdr->AppContext);
845 				break;
846 			case reg_service_request:
847 				if (sdr->AppCallback)((DNSServiceRegisterReply)   sdr->AppCallback)(sdr, 0,    error, NULL, 0, NULL,          sdr->AppContext);
848 				break;
849 			case enumeration_request:
850 				if (sdr->AppCallback)((DNSServiceDomainEnumReply) sdr->AppCallback)(sdr, 0, 0, error, NULL,                   sdr->AppContext);
851 				break;
852 			case sethost_request:
853 				if (sdr->AppCallback)((DNSServiceSetHostReply)    sdr->AppCallback)(sdr, 0,    error, NULL,                   sdr->AppContext);
854 				break;
855 			case connection_request:
856 				// This means Register Record, walk the list of DNSRecords to do the callback
857 				rec = sdr->rec;
858 				while (rec)
859 					{
860 					recnext = rec->recnext;
861 					if (rec->AppCallback) ((DNSServiceRegisterRecordReply)rec->AppCallback)(sdr, 0, 0, error, rec->AppContext);
862 					// The Callback can call DNSServiceRefDeallocate which in turn frees sdr and all the records.
863 					// Detect that and return early
864 					if (!morebytes){syslog(LOG_WARNING, "dnssdclientstub:Record: CallbackwithError morebytes zero"); return;}
865 					rec = recnext;
866 					}
867 				break;
868 			case port_mapping_request:
869 				if (sdr->AppCallback)((DNSServiceNATPortMappingReply)sdr->AppCallback)(sdr, 0, 0, error, 0, 0, 0, 0, 0, sdr->AppContext);
870 				break;
871 			default:
872 				syslog(LOG_WARNING, "dnssd_clientstub CallbackWithError called with bad op %d", sdr->op);
873 			}
874 		// If DNSServiceRefDeallocate was called in the callback, morebytes will be zero. It means
875 		// all other sdrefs have been freed. This happens for shared connections where the
876 		// DNSServiceRefDeallocate on the first sdRef frees all other sdrefs.
877 		if (!morebytes){syslog(LOG_WARNING, "dnssdclientstub:sdRef: CallbackwithError morebytes zero"); return;}
878 		sdr = sdrNext;
879 		}
880 	}
881 #endif // _DNS_SD_LIBDISPATCH
882 
883 // Handle reply from server, calling application client callback. If there is no reply
884 // from the daemon on the socket contained in sdRef, the call will block.
DNSServiceProcessResult(DNSServiceRef sdRef)885 DNSServiceErrorType DNSSD_API DNSServiceProcessResult(DNSServiceRef sdRef)
886 	{
887 	int morebytes = 0;
888 
889 	if (!sdRef) { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceProcessResult called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam; }
890 
891 	if (!DNSServiceRefValid(sdRef))
892 		{
893 		syslog(LOG_WARNING, "dnssd_clientstub DNSServiceProcessResult called with invalid DNSServiceRef %p %08X %08X", sdRef, sdRef->sockfd, sdRef->validator);
894 		return kDNSServiceErr_BadReference;
895 		}
896 
897 	if (sdRef->primary)
898 		{
899 		syslog(LOG_WARNING, "dnssd_clientstub DNSServiceProcessResult undefined for kDNSServiceFlagsShareConnection subordinate DNSServiceRef %p", sdRef);
900 		return kDNSServiceErr_BadReference;
901 		}
902 
903 	if (!sdRef->ProcessReply)
904 		{
905 		static int num_logs = 0;
906 		if (num_logs < 10) syslog(LOG_WARNING, "dnssd_clientstub DNSServiceProcessResult called with DNSServiceRef with no ProcessReply function");
907 		if (num_logs < 1000) num_logs++; else sleep(1);
908 		return kDNSServiceErr_BadReference;
909 		}
910 
911 	do
912 		{
913 		CallbackHeader cbh;
914 		char *data;
915 
916 		// return NoError on EWOULDBLOCK. This will handle the case
917 		// where a non-blocking socket is told there is data, but it was a false positive.
918 		// On error, read_all will write a message to syslog for us, so don't need to duplicate that here
919 		// Note: If we want to properly support using non-blocking sockets in the future
920 		int result = read_all(sdRef->sockfd, (void *)&cbh.ipc_hdr, sizeof(cbh.ipc_hdr));
921 		if (result == read_all_fail)
922 			{
923 			// Set the ProcessReply to NULL before callback as the sdRef can get deallocated
924 			// in the callback.
925 			sdRef->ProcessReply = NULL;
926 #if _DNS_SD_LIBDISPATCH
927 			// Call the callbacks with an error if using the dispatch API, as DNSServiceProcessResult
928 			// is not called by the application and hence need to communicate the error. Cancel the
929 			// source so that we don't get any more events
930 			if (sdRef->disp_source)
931 				{
932 				dispatch_source_cancel(sdRef->disp_source);
933 				dispatch_release(sdRef->disp_source);
934 				sdRef->disp_source = NULL;
935 				CallbackWithError(sdRef, kDNSServiceErr_ServiceNotRunning);
936 				}
937 #endif
938 			// Don't touch sdRef anymore as it might have been deallocated
939 			return kDNSServiceErr_ServiceNotRunning;
940 			}
941 		else if (result == read_all_wouldblock)
942 			{
943 			if (morebytes && sdRef->logcounter < 100)
944 				{
945 				sdRef->logcounter++;
946 				syslog(LOG_WARNING, "dnssd_clientstub DNSServiceProcessResult error: select indicated data was waiting but read_all returned EWOULDBLOCK");
947 				}
948 			return kDNSServiceErr_NoError;
949 			}
950 
951 		ConvertHeaderBytes(&cbh.ipc_hdr);
952 		if (cbh.ipc_hdr.version != VERSION)
953 			{
954 			syslog(LOG_WARNING, "dnssd_clientstub DNSServiceProcessResult daemon version %d does not match client version %d", cbh.ipc_hdr.version, VERSION);
955 			sdRef->ProcessReply = NULL;
956 			return kDNSServiceErr_Incompatible;
957 			}
958 
959 		data = malloc(cbh.ipc_hdr.datalen);
960 		if (!data) return kDNSServiceErr_NoMemory;
961 		if (read_all(sdRef->sockfd, data, cbh.ipc_hdr.datalen) < 0) // On error, read_all will write a message to syslog for us
962 			{
963 			// Set the ProcessReply to NULL before callback as the sdRef can get deallocated
964 			// in the callback.
965 			sdRef->ProcessReply = NULL;
966 #if _DNS_SD_LIBDISPATCH
967 			// Call the callbacks with an error if using the dispatch API, as DNSServiceProcessResult
968 			// is not called by the application and hence need to communicate the error. Cancel the
969 			// source so that we don't get any more events
970 			if (sdRef->disp_source)
971 				{
972 				dispatch_source_cancel(sdRef->disp_source);
973 				dispatch_release(sdRef->disp_source);
974 				sdRef->disp_source = NULL;
975 				CallbackWithError(sdRef, kDNSServiceErr_ServiceNotRunning);
976 				}
977 #endif
978 			// Don't touch sdRef anymore as it might have been deallocated
979 			free(data);
980 			return kDNSServiceErr_ServiceNotRunning;
981 			}
982 		else
983 			{
984 			const char *ptr = data;
985 			cbh.cb_flags     = get_flags     (&ptr, data + cbh.ipc_hdr.datalen);
986 			cbh.cb_interface = get_uint32    (&ptr, data + cbh.ipc_hdr.datalen);
987 			cbh.cb_err       = get_error_code(&ptr, data + cbh.ipc_hdr.datalen);
988 
989 			// CAUTION: We have to handle the case where the client calls DNSServiceRefDeallocate from within the callback function.
990 			// To do this we set moreptr to point to morebytes. If the client does call DNSServiceRefDeallocate(),
991 			// then that routine will clear morebytes for us, and cause us to exit our loop.
992 			morebytes = more_bytes(sdRef->sockfd);
993 			if (morebytes)
994 				{
995 				cbh.cb_flags |= kDNSServiceFlagsMoreComing;
996 				sdRef->moreptr = &morebytes;
997 				}
998 			if (ptr) sdRef->ProcessReply(sdRef, &cbh, ptr, data + cbh.ipc_hdr.datalen);
999 			// Careful code here:
1000 			// If morebytes is non-zero, that means we set sdRef->moreptr above, and the operation was not
1001 			// cancelled out from under us, so now we need to clear sdRef->moreptr so we don't leave a stray
1002 			// dangling pointer pointing to a long-gone stack variable.
1003 			// If morebytes is zero, then one of two thing happened:
1004 			// (a) morebytes was 0 above, so we didn't set sdRef->moreptr, so we don't need to clear it
1005 			// (b) morebytes was 1 above, and we set sdRef->moreptr, but the operation was cancelled (with DNSServiceRefDeallocate()),
1006 			//     so we MUST NOT try to dereference our stale sdRef pointer.
1007 			if (morebytes) sdRef->moreptr = NULL;
1008 			}
1009 		free(data);
1010 		} while (morebytes);
1011 
1012 	return kDNSServiceErr_NoError;
1013 	}
1014 
DNSServiceRefDeallocate(DNSServiceRef sdRef)1015 void DNSSD_API DNSServiceRefDeallocate(DNSServiceRef sdRef)
1016 	{
1017 	if (!sdRef) { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRefDeallocate called with NULL DNSServiceRef"); return; }
1018 
1019 	if (!DNSServiceRefValid(sdRef))		// Also verifies dnssd_SocketValid(sdRef->sockfd) for us too
1020 		{
1021 		syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRefDeallocate called with invalid DNSServiceRef %p %08X %08X", sdRef, sdRef->sockfd, sdRef->validator);
1022 		return;
1023 		}
1024 
1025 	// 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
1026 	if (sdRef->moreptr) *(sdRef->moreptr) = 0;
1027 
1028 	if (sdRef->primary)		// If this is a subordinate DNSServiceOp, just send a 'stop' command
1029 		{
1030 		DNSServiceOp **p = &sdRef->primary->next;
1031 		while (*p && *p != sdRef) p = &(*p)->next;
1032 		if (*p)
1033 			{
1034 			char *ptr;
1035 			size_t len = 0;
1036 			ipc_msg_hdr *hdr = create_hdr(cancel_request, &len, &ptr, 0, sdRef);
1037 			if (hdr)
1038 				{
1039 				ConvertHeaderBytes(hdr);
1040 				write_all(sdRef->sockfd, (char *)hdr, len);
1041 				free(hdr);
1042 				}
1043 			*p = sdRef->next;
1044 			FreeDNSServiceOp(sdRef);
1045 			}
1046 		}
1047 	else					// else, make sure to terminate all subordinates as well
1048 		{
1049 #if _DNS_SD_LIBDISPATCH
1050 		// The cancel handler will close the fd if a dispatch source has been set
1051 		if (sdRef->disp_source)
1052 			{
1053 			// By setting the ProcessReply to NULL, we make sure that we never call
1054 			// the application callbacks ever, after returning from this function. We
1055 			// assume that DNSServiceRefDeallocate is called from the serial queue
1056 			// that was passed to DNSServiceSetDispatchQueue. Hence, dispatch_source_cancel
1057 			// should cancel all the blocks on the queue and hence there should be no more
1058 			// callbacks when we return from this function. Setting ProcessReply to NULL
1059 			// provides extra protection.
1060 			sdRef->ProcessReply = NULL;
1061 			dispatch_source_cancel(sdRef->disp_source);
1062 			dispatch_release(sdRef->disp_source);
1063 			sdRef->disp_source = NULL;
1064 			}
1065 			// if disp_queue is set, it means it used the DNSServiceSetDispatchQueue API. In that case,
1066 			// when the source was cancelled, the fd was closed in the handler. Currently the source
1067 			// is cancelled only when the mDNSResponder daemon dies
1068 		else if (!sdRef->disp_queue) dnssd_close(sdRef->sockfd);
1069 #else
1070 		dnssd_close(sdRef->sockfd);
1071 #endif
1072 		// Free DNSRecords added in DNSRegisterRecord if they have not
1073 		// been freed in DNSRemoveRecord
1074 		while (sdRef)
1075 			{
1076 			DNSServiceOp *p = sdRef;
1077 			sdRef = sdRef->next;
1078 			FreeDNSServiceOp(p);
1079 			}
1080 		}
1081 	}
1082 
DNSServiceGetProperty(const char * property,void * result,uint32_t * size)1083 DNSServiceErrorType DNSSD_API DNSServiceGetProperty(const char *property, void *result, uint32_t *size)
1084 	{
1085 	char *ptr;
1086 	size_t len = strlen(property) + 1;
1087 	ipc_msg_hdr *hdr;
1088 	DNSServiceOp *tmp;
1089 	uint32_t actualsize;
1090 
1091 	DNSServiceErrorType err = ConnectToServer(&tmp, 0, getproperty_request, NULL, NULL, NULL);
1092 	if (err) return err;
1093 
1094 	hdr = create_hdr(getproperty_request, &len, &ptr, 0, tmp);
1095 	if (!hdr) { DNSServiceRefDeallocate(tmp); return kDNSServiceErr_NoMemory; }
1096 
1097 	put_string(property, &ptr);
1098 	err = deliver_request(hdr, tmp);		// Will free hdr for us
1099 	if (read_all(tmp->sockfd, (char*)&actualsize, (int)sizeof(actualsize)) < 0)
1100 		{ DNSServiceRefDeallocate(tmp); return kDNSServiceErr_ServiceNotRunning; }
1101 
1102 	actualsize = ntohl(actualsize);
1103 	if (read_all(tmp->sockfd, (char*)result, actualsize < *size ? actualsize : *size) < 0)
1104 		{ DNSServiceRefDeallocate(tmp); return kDNSServiceErr_ServiceNotRunning; }
1105 	DNSServiceRefDeallocate(tmp);
1106 
1107 	// Swap version result back to local process byte order
1108 	if (!strcmp(property, kDNSServiceProperty_DaemonVersion) && *size >= 4)
1109 		*(uint32_t*)result = ntohl(*(uint32_t*)result);
1110 
1111 	*size = actualsize;
1112 	return kDNSServiceErr_NoError;
1113 	}
1114 
handle_resolve_response(DNSServiceOp * const sdr,const CallbackHeader * const cbh,const char * data,const char * end)1115 static void handle_resolve_response(DNSServiceOp *const sdr, const CallbackHeader *const cbh, const char *data, const char *end)
1116 	{
1117 	char fullname[kDNSServiceMaxDomainName];
1118 	char target[kDNSServiceMaxDomainName];
1119 	uint16_t txtlen;
1120 	union { uint16_t s; u_char b[2]; } port;
1121 	unsigned char *txtrecord;
1122 
1123 	get_string(&data, end, fullname, kDNSServiceMaxDomainName);
1124 	get_string(&data, end, target,   kDNSServiceMaxDomainName);
1125 	if (!data || data + 2 > end) goto fail;
1126 
1127 	port.b[0] = *data++;
1128 	port.b[1] = *data++;
1129 	txtlen = get_uint16(&data, end);
1130 	txtrecord = (unsigned char *)get_rdata(&data, end, txtlen);
1131 
1132 	if (!data) goto fail;
1133 	((DNSServiceResolveReply)sdr->AppCallback)(sdr, cbh->cb_flags, cbh->cb_interface, cbh->cb_err, fullname, target, port.s, txtlen, txtrecord, sdr->AppContext);
1134 	return;
1135 	// MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1136 fail:
1137 	syslog(LOG_WARNING, "dnssd_clientstub handle_resolve_response: error reading result from daemon");
1138 	}
1139 
DNSServiceResolve(DNSServiceRef * sdRef,DNSServiceFlags flags,uint32_t interfaceIndex,const char * name,const char * regtype,const char * domain,DNSServiceResolveReply callBack,void * context)1140 DNSServiceErrorType DNSSD_API DNSServiceResolve
1141 	(
1142 	DNSServiceRef                 *sdRef,
1143 	DNSServiceFlags               flags,
1144 	uint32_t                      interfaceIndex,
1145 	const char                    *name,
1146 	const char                    *regtype,
1147 	const char                    *domain,
1148 	DNSServiceResolveReply        callBack,
1149 	void                          *context
1150 	)
1151 	{
1152 	char *ptr;
1153 	size_t len;
1154 	ipc_msg_hdr *hdr;
1155 	DNSServiceErrorType err;
1156 
1157 	if (!name || !regtype || !domain || !callBack) return kDNSServiceErr_BadParam;
1158 
1159 	// Need a real InterfaceID for WakeOnResolve
1160 	if ((flags & kDNSServiceFlagsWakeOnResolve) != 0 &&
1161 		((interfaceIndex == kDNSServiceInterfaceIndexAny) ||
1162 		(interfaceIndex == kDNSServiceInterfaceIndexLocalOnly) ||
1163 		(interfaceIndex == kDNSServiceInterfaceIndexUnicast) ||
1164 		(interfaceIndex == kDNSServiceInterfaceIndexP2P)))
1165 		{
1166 		return kDNSServiceErr_BadParam;
1167 		}
1168 
1169 	err = ConnectToServer(sdRef, flags, resolve_request, handle_resolve_response, callBack, context);
1170 	if (err) return err;	// On error ConnectToServer leaves *sdRef set to NULL
1171 
1172 	// Calculate total message length
1173 	len = sizeof(flags);
1174 	len += sizeof(interfaceIndex);
1175 	len += strlen(name) + 1;
1176 	len += strlen(regtype) + 1;
1177 	len += strlen(domain) + 1;
1178 
1179 	hdr = create_hdr(resolve_request, &len, &ptr, (*sdRef)->primary ? 1 : 0, *sdRef);
1180 	if (!hdr) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; return kDNSServiceErr_NoMemory; }
1181 
1182 	put_flags(flags, &ptr);
1183 	put_uint32(interfaceIndex, &ptr);
1184 	put_string(name, &ptr);
1185 	put_string(regtype, &ptr);
1186 	put_string(domain, &ptr);
1187 
1188 	err = deliver_request(hdr, *sdRef);		// Will free hdr for us
1189 	if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
1190 	return err;
1191 	}
1192 
handle_query_response(DNSServiceOp * const sdr,const CallbackHeader * const cbh,const char * data,const char * const end)1193 static void handle_query_response(DNSServiceOp *const sdr, const CallbackHeader *const cbh, const char *data, const char *const end)
1194 	{
1195 	uint32_t ttl;
1196 	char name[kDNSServiceMaxDomainName];
1197 	uint16_t rrtype, rrclass, rdlen;
1198 	const char *rdata;
1199 
1200 	get_string(&data, end, name, kDNSServiceMaxDomainName);
1201 	rrtype  = get_uint16(&data, end);
1202 	rrclass = get_uint16(&data, end);
1203 	rdlen   = get_uint16(&data, end);
1204 	rdata   = get_rdata(&data, end, rdlen);
1205 	ttl     = get_uint32(&data, end);
1206 
1207 	if (!data) syslog(LOG_WARNING, "dnssd_clientstub handle_query_response: error reading result from daemon");
1208 	else ((DNSServiceQueryRecordReply)sdr->AppCallback)(sdr, cbh->cb_flags, cbh->cb_interface, cbh->cb_err, name, rrtype, rrclass, rdlen, rdata, ttl, sdr->AppContext);
1209 	// MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1210 	}
1211 
DNSServiceQueryRecord(DNSServiceRef * sdRef,DNSServiceFlags flags,uint32_t interfaceIndex,const char * name,uint16_t rrtype,uint16_t rrclass,DNSServiceQueryRecordReply callBack,void * context)1212 DNSServiceErrorType DNSSD_API DNSServiceQueryRecord
1213 	(
1214 	DNSServiceRef              *sdRef,
1215 	DNSServiceFlags             flags,
1216 	uint32_t                    interfaceIndex,
1217 	const char                 *name,
1218 	uint16_t                    rrtype,
1219 	uint16_t                    rrclass,
1220 	DNSServiceQueryRecordReply  callBack,
1221 	void                       *context
1222 	)
1223 	{
1224 	char *ptr;
1225 	size_t len;
1226 	ipc_msg_hdr *hdr;
1227 	DNSServiceErrorType err = ConnectToServer(sdRef, flags, query_request, handle_query_response, callBack, context);
1228 	if (err) return err;	// On error ConnectToServer leaves *sdRef set to NULL
1229 
1230 	if (!name) name = "\0";
1231 
1232 	// Calculate total message length
1233 	len = sizeof(flags);
1234 	len += sizeof(uint32_t);  // interfaceIndex
1235 	len += strlen(name) + 1;
1236 	len += 2 * sizeof(uint16_t);  // rrtype, rrclass
1237 
1238 	hdr = create_hdr(query_request, &len, &ptr, (*sdRef)->primary ? 1 : 0, *sdRef);
1239 	if (!hdr) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; return kDNSServiceErr_NoMemory; }
1240 
1241 	put_flags(flags, &ptr);
1242 	put_uint32(interfaceIndex, &ptr);
1243 	put_string(name, &ptr);
1244 	put_uint16(rrtype, &ptr);
1245 	put_uint16(rrclass, &ptr);
1246 
1247 	err = deliver_request(hdr, *sdRef);		// Will free hdr for us
1248 	if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
1249 	return err;
1250 	}
1251 
handle_addrinfo_response(DNSServiceOp * const sdr,const CallbackHeader * const cbh,const char * data,const char * const end)1252 static void handle_addrinfo_response(DNSServiceOp *const sdr, const CallbackHeader *const cbh, const char *data, const char *const end)
1253 	{
1254 	char hostname[kDNSServiceMaxDomainName];
1255 	uint16_t rrtype, rrclass, rdlen;
1256 	const char *rdata;
1257 	uint32_t ttl;
1258 
1259 	get_string(&data, end, hostname, kDNSServiceMaxDomainName);
1260 	rrtype  = get_uint16(&data, end);
1261 	rrclass = get_uint16(&data, end);
1262 	rdlen   = get_uint16(&data, end);
1263 	rdata   = get_rdata (&data, end, rdlen);
1264 	ttl     = get_uint32(&data, end);
1265 
1266 	// We only generate client callbacks for A and AAAA results (including NXDOMAIN results for
1267 	// those types, if the client has requested those with the kDNSServiceFlagsReturnIntermediates).
1268 	// Other result types, specifically CNAME referrals, are not communicated to the client, because
1269 	// the DNSServiceGetAddrInfoReply interface doesn't have any meaningful way to communiate CNAME referrals.
1270 	if (!data) syslog(LOG_WARNING, "dnssd_clientstub handle_addrinfo_response: error reading result from daemon");
1271 	else if (rrtype == kDNSServiceType_A || rrtype == kDNSServiceType_AAAA)
1272 		{
1273 		struct sockaddr_in  sa4;
1274 		struct sockaddr_in6 sa6;
1275 		const struct sockaddr *const sa = (rrtype == kDNSServiceType_A) ? (struct sockaddr*)&sa4 : (struct sockaddr*)&sa6;
1276 		if (rrtype == kDNSServiceType_A)
1277 			{
1278 			memset(&sa4, 0, sizeof(sa4));
1279 			#ifndef NOT_HAVE_SA_LEN
1280 			sa4.sin_len = sizeof(struct sockaddr_in);
1281 			#endif
1282 			sa4.sin_family = AF_INET;
1283 			//  sin_port   = 0;
1284 			if (!cbh->cb_err) memcpy(&sa4.sin_addr, rdata, rdlen);
1285 			}
1286 		else
1287 			{
1288 			memset(&sa6, 0, sizeof(sa6));
1289 			#ifndef NOT_HAVE_SA_LEN
1290 			sa6.sin6_len = sizeof(struct sockaddr_in6);
1291 			#endif
1292 			sa6.sin6_family     = AF_INET6;
1293 			//  sin6_port     = 0;
1294 			//  sin6_flowinfo = 0;
1295 			//  sin6_scope_id = 0;
1296 			if (!cbh->cb_err)
1297 				{
1298 				memcpy(&sa6.sin6_addr, rdata, rdlen);
1299 				if (IN6_IS_ADDR_LINKLOCAL(&sa6.sin6_addr)) sa6.sin6_scope_id = cbh->cb_interface;
1300 				}
1301 			}
1302 		((DNSServiceGetAddrInfoReply)sdr->AppCallback)(sdr, cbh->cb_flags, cbh->cb_interface, cbh->cb_err, hostname, sa, ttl, sdr->AppContext);
1303 		// MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1304 		}
1305 	}
1306 
DNSServiceGetAddrInfo(DNSServiceRef * sdRef,DNSServiceFlags flags,uint32_t interfaceIndex,uint32_t protocol,const char * hostname,DNSServiceGetAddrInfoReply callBack,void * context)1307 DNSServiceErrorType DNSSD_API DNSServiceGetAddrInfo
1308 	(
1309 	DNSServiceRef                    *sdRef,
1310 	DNSServiceFlags                  flags,
1311 	uint32_t                         interfaceIndex,
1312 	uint32_t                         protocol,
1313 	const char                       *hostname,
1314 	DNSServiceGetAddrInfoReply       callBack,
1315 	void                             *context          /* may be NULL */
1316 	)
1317 	{
1318 	char *ptr;
1319 	size_t len;
1320 	ipc_msg_hdr *hdr;
1321 	DNSServiceErrorType err;
1322 
1323 	if (!hostname) return kDNSServiceErr_BadParam;
1324 
1325 	err = ConnectToServer(sdRef, flags, addrinfo_request, handle_addrinfo_response, callBack, context);
1326 	if (err) return err;	// On error ConnectToServer leaves *sdRef set to NULL
1327 
1328 	// Calculate total message length
1329 	len = sizeof(flags);
1330 	len += sizeof(uint32_t);      // interfaceIndex
1331 	len += sizeof(uint32_t);      // protocol
1332 	len += strlen(hostname) + 1;
1333 
1334 	hdr = create_hdr(addrinfo_request, &len, &ptr, (*sdRef)->primary ? 1 : 0, *sdRef);
1335 	if (!hdr) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; return kDNSServiceErr_NoMemory; }
1336 
1337 	put_flags(flags, &ptr);
1338 	put_uint32(interfaceIndex, &ptr);
1339 	put_uint32(protocol, &ptr);
1340 	put_string(hostname, &ptr);
1341 
1342 	err = deliver_request(hdr, *sdRef);		// Will free hdr for us
1343 	if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
1344 	return err;
1345 	}
1346 
handle_browse_response(DNSServiceOp * const sdr,const CallbackHeader * const cbh,const char * data,const char * const end)1347 static void handle_browse_response(DNSServiceOp *const sdr, const CallbackHeader *const cbh, const char *data, const char *const end)
1348 	{
1349 	char replyName[256], replyType[kDNSServiceMaxDomainName], replyDomain[kDNSServiceMaxDomainName];
1350 	get_string(&data, end, replyName, 256);
1351 	get_string(&data, end, replyType, kDNSServiceMaxDomainName);
1352 	get_string(&data, end, replyDomain, kDNSServiceMaxDomainName);
1353 	if (!data) syslog(LOG_WARNING, "dnssd_clientstub handle_browse_response: error reading result from daemon");
1354 	else ((DNSServiceBrowseReply)sdr->AppCallback)(sdr, cbh->cb_flags, cbh->cb_interface, cbh->cb_err, replyName, replyType, replyDomain, sdr->AppContext);
1355 	// MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1356 	}
1357 
DNSServiceBrowse(DNSServiceRef * sdRef,DNSServiceFlags flags,uint32_t interfaceIndex,const char * regtype,const char * domain,DNSServiceBrowseReply callBack,void * context)1358 DNSServiceErrorType DNSSD_API DNSServiceBrowse
1359 	(
1360 	DNSServiceRef         *sdRef,
1361 	DNSServiceFlags        flags,
1362 	uint32_t               interfaceIndex,
1363 	const char            *regtype,
1364 	const char            *domain,
1365 	DNSServiceBrowseReply  callBack,
1366 	void                  *context
1367 	)
1368 	{
1369 	char *ptr;
1370 	size_t len;
1371 	ipc_msg_hdr *hdr;
1372 	DNSServiceErrorType err = ConnectToServer(sdRef, flags, browse_request, handle_browse_response, callBack, context);
1373 	if (err) return err;	// On error ConnectToServer leaves *sdRef set to NULL
1374 
1375 	if (!domain) domain = "";
1376 	len = sizeof(flags);
1377 	len += sizeof(interfaceIndex);
1378 	len += strlen(regtype) + 1;
1379 	len += strlen(domain) + 1;
1380 
1381 	hdr = create_hdr(browse_request, &len, &ptr, (*sdRef)->primary ? 1 : 0, *sdRef);
1382 	if (!hdr) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; return kDNSServiceErr_NoMemory; }
1383 
1384 	put_flags(flags, &ptr);
1385 	put_uint32(interfaceIndex, &ptr);
1386 	put_string(regtype, &ptr);
1387 	put_string(domain, &ptr);
1388 
1389 	err = deliver_request(hdr, *sdRef);		// Will free hdr for us
1390 	if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
1391 	return err;
1392 	}
1393 
handle_hostname_changed_response(DNSServiceOp * const sdr,const CallbackHeader * const cbh,const char * data,const char * const end)1394 static void handle_hostname_changed_response(
1395 	DNSServiceOp         *const sdr,
1396 	const CallbackHeader *const cbh,
1397 	const char           *data,
1398 	const char           *const end)
1399 {
1400 	char replyHostname[256];
1401 	get_string(&data, end, replyHostname, sizeof(replyHostname));
1402 	if (!data) syslog(LOG_WARNING,
1403 		"dnssd_clientstub handle_hostname_changed_response: error reading result from daemon");
1404 	else ((DNSHostnameChangedReply)sdr->AppCallback)(
1405 		sdr, cbh->cb_flags, cbh->cb_err, replyHostname, sdr->AppContext);
1406 }
1407 
DNSSetHostname(DNSServiceRef * sdRef,DNSServiceFlags flags,const char * hostname,DNSHostnameChangedReply callBack,void * context)1408 DNSServiceErrorType DNSSD_API DNSSetHostname
1409 (
1410 	DNSServiceRef           *sdRef,
1411 	DNSServiceFlags         flags,
1412 	const char              *hostname,
1413 	DNSHostnameChangedReply callBack,
1414 	void                    *context
1415 )
1416 {
1417 	char *ptr;
1418 	size_t len;
1419 	ipc_msg_hdr *hdr;
1420 	DNSServiceErrorType err = ConnectToServer(sdRef, flags, sethost_request,
1421 		handle_hostname_changed_response, callBack, context);
1422 	if (err) return err;
1423 	len = sizeof(flags);
1424 	len += strlen(hostname) + 1;
1425 	hdr = create_hdr(sethost_request, &len, &ptr,
1426 		(*sdRef)->primary ? 1 : 0, *sdRef);
1427 	if (!hdr)
1428  	{
1429 		DNSServiceRefDeallocate(*sdRef);
1430 		*sdRef = NULL;
1431 		return kDNSServiceErr_NoMemory;
1432 	}
1433 	put_flags(flags, &ptr);
1434 	put_string(hostname, &ptr);
1435 	err = deliver_request(hdr, *sdRef);
1436 	if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
1437 	return err;
1438 }
1439 
1440 DNSServiceErrorType DNSSD_API DNSServiceSetDefaultDomainForUser(DNSServiceFlags flags, const char *domain);
DNSServiceSetDefaultDomainForUser(DNSServiceFlags flags,const char * domain)1441 DNSServiceErrorType DNSSD_API DNSServiceSetDefaultDomainForUser(DNSServiceFlags flags, const char *domain)
1442 	{
1443 	DNSServiceOp *tmp;
1444 	char *ptr;
1445 	size_t len = sizeof(flags) + strlen(domain) + 1;
1446 	ipc_msg_hdr *hdr;
1447 	DNSServiceErrorType err = ConnectToServer(&tmp, 0, setdomain_request, NULL, NULL, NULL);
1448 	if (err) return err;
1449 
1450 	hdr = create_hdr(setdomain_request, &len, &ptr, 0, tmp);
1451 	if (!hdr) { DNSServiceRefDeallocate(tmp); return kDNSServiceErr_NoMemory; }
1452 
1453 	put_flags(flags, &ptr);
1454 	put_string(domain, &ptr);
1455 	err = deliver_request(hdr, tmp);		// Will free hdr for us
1456 	DNSServiceRefDeallocate(tmp);
1457 	return err;
1458 	}
1459 
handle_regservice_response(DNSServiceOp * const sdr,const CallbackHeader * const cbh,const char * data,const char * const end)1460 static void handle_regservice_response(DNSServiceOp *const sdr, const CallbackHeader *const cbh, const char *data, const char *const end)
1461 	{
1462 	char name[256], regtype[kDNSServiceMaxDomainName], domain[kDNSServiceMaxDomainName];
1463 	get_string(&data, end, name, 256);
1464 	get_string(&data, end, regtype, kDNSServiceMaxDomainName);
1465 	get_string(&data, end, domain,  kDNSServiceMaxDomainName);
1466 	if (!data) syslog(LOG_WARNING, "dnssd_clientstub handle_regservice_response: error reading result from daemon");
1467 	else ((DNSServiceRegisterReply)sdr->AppCallback)(sdr, cbh->cb_flags, cbh->cb_err, name, regtype, domain, sdr->AppContext);
1468 	// MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1469 	}
1470 
DNSServiceRegister(DNSServiceRef * sdRef,DNSServiceFlags flags,uint32_t interfaceIndex,const char * name,const char * regtype,const char * domain,const char * host,uint16_t PortInNetworkByteOrder,uint16_t txtLen,const void * txtRecord,DNSServiceRegisterReply callBack,void * context)1471 DNSServiceErrorType DNSSD_API DNSServiceRegister
1472 	(
1473 	DNSServiceRef                       *sdRef,
1474 	DNSServiceFlags                     flags,
1475 	uint32_t                            interfaceIndex,
1476 	const char                          *name,
1477 	const char                          *regtype,
1478 	const char                          *domain,
1479 	const char                          *host,
1480 	uint16_t                            PortInNetworkByteOrder,
1481 	uint16_t                            txtLen,
1482 	const void                          *txtRecord,
1483 	DNSServiceRegisterReply             callBack,
1484 	void                                *context
1485 	)
1486 	{
1487 	char *ptr;
1488 	size_t len;
1489 	ipc_msg_hdr *hdr;
1490 	DNSServiceErrorType err;
1491 	union { uint16_t s; u_char b[2]; } port = { PortInNetworkByteOrder };
1492 
1493 	if (!name) name = "";
1494 	if (!regtype) return kDNSServiceErr_BadParam;
1495 	if (!domain) domain = "";
1496 	if (!host) host = "";
1497 	if (!txtRecord) txtRecord = (void*)"";
1498 
1499 	// No callback must have auto-rename
1500 	if (!callBack && (flags & kDNSServiceFlagsNoAutoRename)) return kDNSServiceErr_BadParam;
1501 
1502 	err = ConnectToServer(sdRef, flags, reg_service_request, callBack ? handle_regservice_response : NULL, callBack, context);
1503 	if (err) return err;	// On error ConnectToServer leaves *sdRef set to NULL
1504 
1505 	len = sizeof(DNSServiceFlags);
1506 	len += sizeof(uint32_t);  // interfaceIndex
1507 	len += strlen(name) + strlen(regtype) + strlen(domain) + strlen(host) + 4;
1508 	len += 2 * sizeof(uint16_t);  // port, txtLen
1509 	len += txtLen;
1510 
1511 	hdr = create_hdr(reg_service_request, &len, &ptr, (*sdRef)->primary ? 1 : 0, *sdRef);
1512 	if (!hdr) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; return kDNSServiceErr_NoMemory; }
1513 	if (!callBack) hdr->ipc_flags |= IPC_FLAGS_NOREPLY;
1514 
1515 	put_flags(flags, &ptr);
1516 	put_uint32(interfaceIndex, &ptr);
1517 	put_string(name, &ptr);
1518 	put_string(regtype, &ptr);
1519 	put_string(domain, &ptr);
1520 	put_string(host, &ptr);
1521 	*ptr++ = port.b[0];
1522 	*ptr++ = port.b[1];
1523 	put_uint16(txtLen, &ptr);
1524 	put_rdata(txtLen, txtRecord, &ptr);
1525 
1526 	err = deliver_request(hdr, *sdRef);		// Will free hdr for us
1527 	if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
1528 	return err;
1529 	}
1530 
handle_enumeration_response(DNSServiceOp * const sdr,const CallbackHeader * const cbh,const char * data,const char * const end)1531 static void handle_enumeration_response(DNSServiceOp *const sdr, const CallbackHeader *const cbh, const char *data, const char *const end)
1532 	{
1533 	char domain[kDNSServiceMaxDomainName];
1534 	get_string(&data, end, domain, kDNSServiceMaxDomainName);
1535 	if (!data) syslog(LOG_WARNING, "dnssd_clientstub handle_enumeration_response: error reading result from daemon");
1536 	else ((DNSServiceDomainEnumReply)sdr->AppCallback)(sdr, cbh->cb_flags, cbh->cb_interface, cbh->cb_err, domain, sdr->AppContext);
1537 	// MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1538 	}
1539 
DNSServiceEnumerateDomains(DNSServiceRef * sdRef,DNSServiceFlags flags,uint32_t interfaceIndex,DNSServiceDomainEnumReply callBack,void * context)1540 DNSServiceErrorType DNSSD_API DNSServiceEnumerateDomains
1541 	(
1542 	DNSServiceRef             *sdRef,
1543 	DNSServiceFlags            flags,
1544 	uint32_t                   interfaceIndex,
1545 	DNSServiceDomainEnumReply  callBack,
1546 	void                      *context
1547 	)
1548 	{
1549 	char *ptr;
1550 	size_t len;
1551 	ipc_msg_hdr *hdr;
1552 	DNSServiceErrorType err;
1553 
1554 	int f1 = (flags & kDNSServiceFlagsBrowseDomains) != 0;
1555 	int f2 = (flags & kDNSServiceFlagsRegistrationDomains) != 0;
1556 	if (f1 + f2 != 1) return kDNSServiceErr_BadParam;
1557 
1558 	err = ConnectToServer(sdRef, flags, enumeration_request, handle_enumeration_response, callBack, context);
1559 	if (err) return err;	// On error ConnectToServer leaves *sdRef set to NULL
1560 
1561 	len = sizeof(DNSServiceFlags);
1562 	len += sizeof(uint32_t);
1563 
1564 	hdr = create_hdr(enumeration_request, &len, &ptr, (*sdRef)->primary ? 1 : 0, *sdRef);
1565 	if (!hdr) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; return kDNSServiceErr_NoMemory; }
1566 
1567 	put_flags(flags, &ptr);
1568 	put_uint32(interfaceIndex, &ptr);
1569 
1570 	err = deliver_request(hdr, *sdRef);		// Will free hdr for us
1571 	if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
1572 	return err;
1573 	}
1574 
ConnectionResponse(DNSServiceOp * const sdr,const CallbackHeader * const cbh,const char * const data,const char * const end)1575 static void ConnectionResponse(DNSServiceOp *const sdr, const CallbackHeader *const cbh, const char *const data, const char *const end)
1576 	{
1577 	DNSRecordRef rref = cbh->ipc_hdr.client_context.context;
1578 	(void)data; // Unused
1579 
1580 	//printf("ConnectionResponse got %d\n", cbh->ipc_hdr.op);
1581 	if (cbh->ipc_hdr.op != reg_record_reply_op)
1582 		{
1583 		// When using kDNSServiceFlagsShareConnection, need to search the list of associated DNSServiceOps
1584 		// to find the one this response is intended for, and then call through to its ProcessReply handler.
1585 		// We start with our first subordinate DNSServiceRef -- don't want to accidentally match the parent DNSServiceRef.
1586 		DNSServiceOp *op = sdr->next;
1587 		while (op && (op->uid.u32[0] != cbh->ipc_hdr.client_context.u32[0] || op->uid.u32[1] != cbh->ipc_hdr.client_context.u32[1]))
1588 			op = op->next;
1589 		// Note: We may sometimes not find a matching DNSServiceOp, in the case where the client has
1590 		// cancelled the subordinate DNSServiceOp, but there are still messages in the pipeline from the daemon
1591 		if (op && op->ProcessReply) op->ProcessReply(op, cbh, data, end);
1592 		// WARNING: Don't touch op or sdr after this -- client may have called DNSServiceRefDeallocate
1593 		return;
1594 		}
1595 
1596 	if (sdr->op == connection_request)
1597 		rref->AppCallback(rref->sdr, rref, cbh->cb_flags, cbh->cb_err, rref->AppContext);
1598 	else
1599 		{
1600 		syslog(LOG_WARNING, "dnssd_clientstub ConnectionResponse: sdr->op != connection_request");
1601 		rref->AppCallback(rref->sdr, rref, 0, kDNSServiceErr_Unknown, rref->AppContext);
1602 		}
1603 	// MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1604 	}
1605 
DNSServiceCreateConnection(DNSServiceRef * sdRef)1606 DNSServiceErrorType DNSSD_API DNSServiceCreateConnection(DNSServiceRef *sdRef)
1607 	{
1608 	char *ptr;
1609 	size_t len = 0;
1610 	ipc_msg_hdr *hdr;
1611 	DNSServiceErrorType err = ConnectToServer(sdRef, 0, connection_request, ConnectionResponse, NULL, NULL);
1612 	if (err) return err;	// On error ConnectToServer leaves *sdRef set to NULL
1613 
1614 	hdr = create_hdr(connection_request, &len, &ptr, 0, *sdRef);
1615 	if (!hdr) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; return kDNSServiceErr_NoMemory; }
1616 
1617 	err = deliver_request(hdr, *sdRef);		// Will free hdr for us
1618 	if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
1619 	return err;
1620 	}
1621 
DNSServiceRegisterRecord(DNSServiceRef sdRef,DNSRecordRef * RecordRef,DNSServiceFlags flags,uint32_t interfaceIndex,const char * fullname,uint16_t rrtype,uint16_t rrclass,uint16_t rdlen,const void * rdata,uint32_t ttl,DNSServiceRegisterRecordReply callBack,void * context)1622 DNSServiceErrorType DNSSD_API DNSServiceRegisterRecord
1623 	(
1624 	DNSServiceRef                  sdRef,
1625 	DNSRecordRef                  *RecordRef,
1626 	DNSServiceFlags                flags,
1627 	uint32_t                       interfaceIndex,
1628 	const char                    *fullname,
1629 	uint16_t                       rrtype,
1630 	uint16_t                       rrclass,
1631 	uint16_t                       rdlen,
1632 	const void                    *rdata,
1633 	uint32_t                       ttl,
1634 	DNSServiceRegisterRecordReply  callBack,
1635 	void                          *context
1636 	)
1637 	{
1638 	char *ptr;
1639 	size_t len;
1640 	ipc_msg_hdr *hdr = NULL;
1641 	DNSRecordRef rref = NULL;
1642 	DNSRecord **p;
1643 	int f1 = (flags & kDNSServiceFlagsShared) != 0;
1644 	int f2 = (flags & kDNSServiceFlagsUnique) != 0;
1645 	if (f1 + f2 != 1) return kDNSServiceErr_BadParam;
1646 
1647 	if (!sdRef) { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRegisterRecord called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam; }
1648 
1649 	if (!DNSServiceRefValid(sdRef))
1650 		{
1651 		syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRegisterRecord called with invalid DNSServiceRef %p %08X %08X", sdRef, sdRef->sockfd, sdRef->validator);
1652 		return kDNSServiceErr_BadReference;
1653 		}
1654 
1655 	if (sdRef->op != connection_request)
1656 		{
1657 		syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRegisterRecord called with non-DNSServiceCreateConnection DNSServiceRef %p %d", sdRef, sdRef->op);
1658 		return kDNSServiceErr_BadReference;
1659 		}
1660 
1661 	*RecordRef = NULL;
1662 
1663 	len = sizeof(DNSServiceFlags);
1664 	len += 2 * sizeof(uint32_t);  // interfaceIndex, ttl
1665 	len += 3 * sizeof(uint16_t);  // rrtype, rrclass, rdlen
1666 	len += strlen(fullname) + 1;
1667 	len += rdlen;
1668 
1669 	hdr = create_hdr(reg_record_request, &len, &ptr, 1, sdRef);
1670 	if (!hdr) return kDNSServiceErr_NoMemory;
1671 
1672 	put_flags(flags, &ptr);
1673 	put_uint32(interfaceIndex, &ptr);
1674 	put_string(fullname, &ptr);
1675 	put_uint16(rrtype, &ptr);
1676 	put_uint16(rrclass, &ptr);
1677 	put_uint16(rdlen, &ptr);
1678 	put_rdata(rdlen, rdata, &ptr);
1679 	put_uint32(ttl, &ptr);
1680 
1681 	rref = malloc(sizeof(DNSRecord));
1682 	if (!rref) { free(hdr); return kDNSServiceErr_NoMemory; }
1683 	rref->AppContext = context;
1684 	rref->AppCallback = callBack;
1685 	rref->record_index = sdRef->max_index++;
1686 	rref->sdr = sdRef;
1687 	rref->recnext = NULL;
1688 	*RecordRef = rref;
1689 	hdr->client_context.context = rref;
1690 	hdr->reg_index = rref->record_index;
1691 
1692 	p = &(sdRef)->rec;
1693 	while (*p) p = &(*p)->recnext;
1694 	*p = rref;
1695 
1696 	return deliver_request(hdr, sdRef);		// Will free hdr for us
1697 	}
1698 
1699 // sdRef returned by DNSServiceRegister()
DNSServiceAddRecord(DNSServiceRef sdRef,DNSRecordRef * RecordRef,DNSServiceFlags flags,uint16_t rrtype,uint16_t rdlen,const void * rdata,uint32_t ttl)1700 DNSServiceErrorType DNSSD_API DNSServiceAddRecord
1701 	(
1702 	DNSServiceRef    sdRef,
1703 	DNSRecordRef    *RecordRef,
1704 	DNSServiceFlags  flags,
1705 	uint16_t         rrtype,
1706 	uint16_t         rdlen,
1707 	const void      *rdata,
1708 	uint32_t         ttl
1709 	)
1710 	{
1711 	ipc_msg_hdr *hdr;
1712 	size_t len = 0;
1713 	char *ptr;
1714 	DNSRecordRef rref;
1715 	DNSRecord **p;
1716 
1717 	if (!sdRef)     { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceAddRecord called with NULL DNSServiceRef");        return kDNSServiceErr_BadParam; }
1718 	if (!RecordRef) { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceAddRecord called with NULL DNSRecordRef pointer"); return kDNSServiceErr_BadParam; }
1719 	if (sdRef->op != reg_service_request)
1720 		{
1721 		syslog(LOG_WARNING, "dnssd_clientstub DNSServiceAddRecord called with non-DNSServiceRegister DNSServiceRef %p %d", sdRef, sdRef->op);
1722 		return kDNSServiceErr_BadReference;
1723 		}
1724 
1725 	if (!DNSServiceRefValid(sdRef))
1726 		{
1727 		syslog(LOG_WARNING, "dnssd_clientstub DNSServiceAddRecord called with invalid DNSServiceRef %p %08X %08X", sdRef, sdRef->sockfd, sdRef->validator);
1728 		return kDNSServiceErr_BadReference;
1729 		}
1730 
1731 	*RecordRef = NULL;
1732 
1733 	len += 2 * sizeof(uint16_t);  // rrtype, rdlen
1734 	len += rdlen;
1735 	len += sizeof(uint32_t);
1736 	len += sizeof(DNSServiceFlags);
1737 
1738 	hdr = create_hdr(add_record_request, &len, &ptr, 1, sdRef);
1739 	if (!hdr) return kDNSServiceErr_NoMemory;
1740 	put_flags(flags, &ptr);
1741 	put_uint16(rrtype, &ptr);
1742 	put_uint16(rdlen, &ptr);
1743 	put_rdata(rdlen, rdata, &ptr);
1744 	put_uint32(ttl, &ptr);
1745 
1746 	rref = malloc(sizeof(DNSRecord));
1747 	if (!rref) { free(hdr); return kDNSServiceErr_NoMemory; }
1748 	rref->AppContext = NULL;
1749 	rref->AppCallback = NULL;
1750 	rref->record_index = sdRef->max_index++;
1751 	rref->sdr = sdRef;
1752 	rref->recnext = NULL;
1753 	*RecordRef = rref;
1754 	hdr->reg_index = rref->record_index;
1755 
1756 	p = &(sdRef)->rec;
1757 	while (*p) p = &(*p)->recnext;
1758 	*p = rref;
1759 
1760 	return deliver_request(hdr, sdRef);		// Will free hdr for us
1761 	}
1762 
1763 // DNSRecordRef returned by DNSServiceRegisterRecord or DNSServiceAddRecord
DNSServiceUpdateRecord(DNSServiceRef sdRef,DNSRecordRef RecordRef,DNSServiceFlags flags,uint16_t rdlen,const void * rdata,uint32_t ttl)1764 DNSServiceErrorType DNSSD_API DNSServiceUpdateRecord
1765 	(
1766 	DNSServiceRef    sdRef,
1767 	DNSRecordRef     RecordRef,
1768 	DNSServiceFlags  flags,
1769 	uint16_t         rdlen,
1770 	const void      *rdata,
1771 	uint32_t         ttl
1772 	)
1773 	{
1774 	ipc_msg_hdr *hdr;
1775 	size_t len = 0;
1776 	char *ptr;
1777 
1778 	if (!sdRef) { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceUpdateRecord called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam; }
1779 
1780 	if (!DNSServiceRefValid(sdRef))
1781 		{
1782 		syslog(LOG_WARNING, "dnssd_clientstub DNSServiceUpdateRecord called with invalid DNSServiceRef %p %08X %08X", sdRef, sdRef->sockfd, sdRef->validator);
1783 		return kDNSServiceErr_BadReference;
1784 		}
1785 
1786 	// Note: RecordRef is allowed to be NULL
1787 
1788 	len += sizeof(uint16_t);
1789 	len += rdlen;
1790 	len += sizeof(uint32_t);
1791 	len += sizeof(DNSServiceFlags);
1792 
1793 	hdr = create_hdr(update_record_request, &len, &ptr, 1, sdRef);
1794 	if (!hdr) return kDNSServiceErr_NoMemory;
1795 	hdr->reg_index = RecordRef ? RecordRef->record_index : TXT_RECORD_INDEX;
1796 	put_flags(flags, &ptr);
1797 	put_uint16(rdlen, &ptr);
1798 	put_rdata(rdlen, rdata, &ptr);
1799 	put_uint32(ttl, &ptr);
1800 	return deliver_request(hdr, sdRef);		// Will free hdr for us
1801 	}
1802 
DNSServiceRemoveRecord(DNSServiceRef sdRef,DNSRecordRef RecordRef,DNSServiceFlags flags)1803 DNSServiceErrorType DNSSD_API DNSServiceRemoveRecord
1804 	(
1805 	DNSServiceRef    sdRef,
1806 	DNSRecordRef     RecordRef,
1807 	DNSServiceFlags  flags
1808 	)
1809 	{
1810 	ipc_msg_hdr *hdr;
1811 	size_t len = 0;
1812 	char *ptr;
1813 	DNSServiceErrorType err;
1814 
1815 	if (!sdRef)            { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRemoveRecord called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam; }
1816 	if (!RecordRef)        { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRemoveRecord called with NULL DNSRecordRef");  return kDNSServiceErr_BadParam; }
1817 	if (!sdRef->max_index) { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRemoveRecord called with bad DNSServiceRef");  return kDNSServiceErr_BadReference; }
1818 
1819 	if (!DNSServiceRefValid(sdRef))
1820 		{
1821 		syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRemoveRecord called with invalid DNSServiceRef %p %08X %08X", sdRef, sdRef->sockfd, sdRef->validator);
1822 		return kDNSServiceErr_BadReference;
1823 		}
1824 
1825 	len += sizeof(flags);
1826 	hdr = create_hdr(remove_record_request, &len, &ptr, 1, sdRef);
1827 	if (!hdr) return kDNSServiceErr_NoMemory;
1828 	hdr->reg_index = RecordRef->record_index;
1829 	put_flags(flags, &ptr);
1830 	err = deliver_request(hdr, sdRef);		// Will free hdr for us
1831 	if (!err)
1832 		{
1833 		// This RecordRef could have been allocated in DNSServiceRegisterRecord or DNSServiceAddRecord.
1834 		// If so, delink from the list before freeing
1835 		DNSRecord **p = &sdRef->rec;
1836 		while (*p && *p != RecordRef) p = &(*p)->recnext;
1837 		if (*p) *p = RecordRef->recnext;
1838 		free(RecordRef);
1839 		}
1840 	return err;
1841 	}
1842 
DNSServiceReconfirmRecord(DNSServiceFlags flags,uint32_t interfaceIndex,const char * fullname,uint16_t rrtype,uint16_t rrclass,uint16_t rdlen,const void * rdata)1843 DNSServiceErrorType DNSSD_API DNSServiceReconfirmRecord
1844 	(
1845 	DNSServiceFlags  flags,
1846 	uint32_t         interfaceIndex,
1847 	const char      *fullname,
1848 	uint16_t         rrtype,
1849 	uint16_t         rrclass,
1850 	uint16_t         rdlen,
1851 	const void      *rdata
1852 	)
1853 	{
1854 	char *ptr;
1855 	size_t len;
1856 	ipc_msg_hdr *hdr;
1857 	DNSServiceOp *tmp;
1858 
1859 	DNSServiceErrorType err = ConnectToServer(&tmp, flags, reconfirm_record_request, NULL, NULL, NULL);
1860 	if (err) return err;
1861 
1862 	len = sizeof(DNSServiceFlags);
1863 	len += sizeof(uint32_t);
1864 	len += strlen(fullname) + 1;
1865 	len += 3 * sizeof(uint16_t);
1866 	len += rdlen;
1867 	hdr = create_hdr(reconfirm_record_request, &len, &ptr, 0, tmp);
1868 	if (!hdr) { DNSServiceRefDeallocate(tmp); return kDNSServiceErr_NoMemory; }
1869 
1870 	put_flags(flags, &ptr);
1871 	put_uint32(interfaceIndex, &ptr);
1872 	put_string(fullname, &ptr);
1873 	put_uint16(rrtype, &ptr);
1874 	put_uint16(rrclass, &ptr);
1875 	put_uint16(rdlen, &ptr);
1876 	put_rdata(rdlen, rdata, &ptr);
1877 
1878 	err = deliver_request(hdr, tmp);		// Will free hdr for us
1879 	DNSServiceRefDeallocate(tmp);
1880 	return err;
1881 	}
1882 
handle_port_mapping_response(DNSServiceOp * const sdr,const CallbackHeader * const cbh,const char * data,const char * const end)1883 static void handle_port_mapping_response(DNSServiceOp *const sdr, const CallbackHeader *const cbh, const char *data, const char *const end)
1884 	{
1885 	union { uint32_t l; u_char b[4]; } addr;
1886 	uint8_t protocol;
1887 	union { uint16_t s; u_char b[2]; } internalPort;
1888 	union { uint16_t s; u_char b[2]; } externalPort;
1889 	uint32_t ttl;
1890 
1891 	if (!data || data + 13 > end) goto fail;
1892 
1893 	addr        .b[0] = *data++;
1894 	addr        .b[1] = *data++;
1895 	addr        .b[2] = *data++;
1896 	addr        .b[3] = *data++;
1897 	protocol          = *data++;
1898 	internalPort.b[0] = *data++;
1899 	internalPort.b[1] = *data++;
1900 	externalPort.b[0] = *data++;
1901 	externalPort.b[1] = *data++;
1902 	ttl               = get_uint32(&data, end);
1903 	if (!data) goto fail;
1904 
1905 	((DNSServiceNATPortMappingReply)sdr->AppCallback)(sdr, cbh->cb_flags, cbh->cb_interface, cbh->cb_err, addr.l, protocol, internalPort.s, externalPort.s, ttl, sdr->AppContext);
1906 	return;
1907 	// MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1908 
1909 fail:
1910 	syslog(LOG_WARNING, "dnssd_clientstub handle_port_mapping_response: error reading result from daemon");
1911 	}
1912 
DNSServiceNATPortMappingCreate(DNSServiceRef * sdRef,DNSServiceFlags flags,uint32_t interfaceIndex,uint32_t protocol,uint16_t internalPortInNetworkByteOrder,uint16_t externalPortInNetworkByteOrder,uint32_t ttl,DNSServiceNATPortMappingReply callBack,void * context)1913 DNSServiceErrorType DNSSD_API DNSServiceNATPortMappingCreate
1914 	(
1915 	DNSServiceRef                       *sdRef,
1916 	DNSServiceFlags                     flags,
1917 	uint32_t                            interfaceIndex,
1918 	uint32_t                            protocol,     /* TCP and/or UDP */
1919 	uint16_t                            internalPortInNetworkByteOrder,
1920 	uint16_t                            externalPortInNetworkByteOrder,
1921 	uint32_t                            ttl,          /* time to live in seconds */
1922 	DNSServiceNATPortMappingReply       callBack,
1923 	void                                *context      /* may be NULL */
1924 	)
1925 	{
1926 	char *ptr;
1927 	size_t len;
1928 	ipc_msg_hdr *hdr;
1929 	union { uint16_t s; u_char b[2]; } internalPort = { internalPortInNetworkByteOrder };
1930 	union { uint16_t s; u_char b[2]; } externalPort = { externalPortInNetworkByteOrder };
1931 
1932 	DNSServiceErrorType err = ConnectToServer(sdRef, flags, port_mapping_request, handle_port_mapping_response, callBack, context);
1933 	if (err) return err;	// On error ConnectToServer leaves *sdRef set to NULL
1934 
1935 	len = sizeof(flags);
1936 	len += sizeof(interfaceIndex);
1937 	len += sizeof(protocol);
1938 	len += sizeof(internalPort);
1939 	len += sizeof(externalPort);
1940 	len += sizeof(ttl);
1941 
1942 	hdr = create_hdr(port_mapping_request, &len, &ptr, (*sdRef)->primary ? 1 : 0, *sdRef);
1943 	if (!hdr) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; return kDNSServiceErr_NoMemory; }
1944 
1945 	put_flags(flags, &ptr);
1946 	put_uint32(interfaceIndex, &ptr);
1947 	put_uint32(protocol, &ptr);
1948 	*ptr++ = internalPort.b[0];
1949 	*ptr++ = internalPort.b[1];
1950 	*ptr++ = externalPort.b[0];
1951 	*ptr++ = externalPort.b[1];
1952 	put_uint32(ttl, &ptr);
1953 
1954 	err = deliver_request(hdr, *sdRef);		// Will free hdr for us
1955 	if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
1956 	return err;
1957 	}
1958 
1959 #if _DNS_SD_LIBDISPATCH
DNSServiceSetDispatchQueue(DNSServiceRef service,dispatch_queue_t queue)1960 DNSServiceErrorType DNSSD_API DNSServiceSetDispatchQueue
1961 	(
1962 	DNSServiceRef service,
1963 	dispatch_queue_t queue
1964 	)
1965 	{
1966 	int dnssd_fd  = DNSServiceRefSockFD(service);
1967 	if (dnssd_fd == dnssd_InvalidSocket) return kDNSServiceErr_BadParam;
1968 	if (!queue)
1969 		{
1970 		syslog(LOG_WARNING, "dnssd_clientstub: DNSServiceSetDispatchQueue dispatch queue NULL");
1971 		return kDNSServiceErr_BadParam;
1972 		}
1973 	if (service->disp_queue)
1974 		{
1975 		syslog(LOG_WARNING, "dnssd_clientstub DNSServiceSetDispatchQueue dispatch queue set already");
1976 		return kDNSServiceErr_BadParam;
1977 		}
1978 	if (service->disp_source)
1979 		{
1980 		syslog(LOG_WARNING, "DNSServiceSetDispatchQueue dispatch source set already");
1981 		return kDNSServiceErr_BadParam;
1982 		}
1983 	service->disp_source = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, dnssd_fd, 0, queue);
1984 	if (!service->disp_source)
1985 		{
1986 		syslog(LOG_WARNING, "DNSServiceSetDispatchQueue dispatch_source_create failed");
1987 		return kDNSServiceErr_NoMemory;
1988 		}
1989 	service->disp_queue = queue;
1990 	dispatch_source_set_event_handler(service->disp_source, ^{DNSServiceProcessResult(service);});
1991 	dispatch_source_set_cancel_handler(service->disp_source, ^{dnssd_close(dnssd_fd);});
1992 	dispatch_resume(service->disp_source);
1993 	return kDNSServiceErr_NoError;
1994 	}
1995 #endif // _DNS_SD_LIBDISPATCH
1996