]> git.saurik.com Git - apple/mdnsresponder.git/blob - mDNSShared/dnssd_clientstub.c
mDNSResponder-379.27.tar.gz
[apple/mdnsresponder.git] / mDNSShared / dnssd_clientstub.c
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 #if APPLE_OSX_mDNSResponder
33 #include <mach-o/dyld.h>
34 #endif
35
36 #include "dnssd_ipc.h"
37
38 static int gDaemonErr = kDNSServiceErr_NoError;
39
40 #if defined(_WIN32)
41
42 #define _SSIZE_T
43 #include <CommonServices.h>
44 #include <DebugServices.h>
45 #include <winsock2.h>
46 #include <ws2tcpip.h>
47 #include <windows.h>
48 #include <stdarg.h>
49 #include <stdio.h>
50
51 #define sockaddr_mdns sockaddr_in
52 #define AF_MDNS AF_INET
53
54 // Disable warning: "'type cast' : from data pointer 'void *' to function pointer"
55 #pragma warning(disable:4055)
56
57 // Disable warning: "nonstandard extension, function/data pointer conversion in expression"
58 #pragma warning(disable:4152)
59
60 extern BOOL IsSystemServiceDisabled();
61
62 #define sleep(X) Sleep((X) * 1000)
63
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, ...)
68 {
69 va_list args;
70 int len;
71 char * buffer;
72 DWORD err = WSAGetLastError();
73 (void) priority;
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 );
79 }
80 #else
81
82 #include <sys/fcntl.h> // For O_RDWR etc.
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 #if !defined(_WIN32)
117 typedef struct
118 {
119 void *AppCallback; // Client callback function and context
120 void *AppContext;
121 } SleepKAContext;
122 #endif
123
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);
126
127 #define ValidatorBits 0x12345678
128 #define DNSServiceRefValid(X) (dnssd_SocketValid((X)->sockfd) && (((X)->sockfd ^ (X)->validator) == ValidatorBits))
129
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
133 //
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
137 {
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
150 void *AppContext;
151 DNSRecord *rec;
152 #if _DNS_SD_LIBDISPATCH
153 dispatch_source_t disp_source;
154 dispatch_queue_t disp_queue;
155 #endif
156 void *kacontext;
157 };
158
159 struct _DNSRecordRef_t
160 {
161 DNSRecord *recnext;
162 void *AppContext;
163 DNSServiceRegisterRecordReply AppCallback;
164 DNSRecordRef recref;
165 uint32_t record_index; // index is unique to the ServiceDiscoveryRef
166 DNSServiceOp *sdr;
167 };
168
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)
171 {
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;
174 while (len)
175 {
176 ssize_t num_written = send(sd, buf, (long)len, 0);
177 if (num_written < 0 || (size_t)num_written > len)
178 {
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)
182 int defunct;
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));
186 if (!defunct)
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) : "");
191 else
192 syslog(LOG_INFO, "dnssd_clientstub write_all(%d) DEFUNCT", sd);
193 #else
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) : "");
198 #endif
199 return -1;
200 }
201 buf += num_written;
202 len -= num_written;
203 }
204 return 0;
205 }
206
207 enum { read_all_success = 0, read_all_fail = -1, read_all_wouldblock = -2 };
208
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)
211 {
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;
214
215 while (len)
216 {
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))
222 {
223 int printWarn = 0;
224 int defunct = 0;
225 // Should never happen. If it does, it indicates some OS bug,
226 // or that the mDNSResponder daemon crashed (which should never happen).
227 #if defined(WIN32)
228 // <rdar://problem/7481776> Suppress logs for "A non-blocking socket operation
229 // could not be completed immediately"
230 if (WSAGetLastError() != WSAEWOULDBLOCK)
231 printWarn = 1;
232 #endif
233 #if !defined(__ppc__) && defined(SO_ISDEFUNCT)
234 {
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));
238 }
239 if (!defunct)
240 printWarn = 1;
241 #endif
242 if (printWarn)
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) : "");
247 else if (defunct)
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;
250 }
251 buf += num_read;
252 len -= num_read;
253 }
254 return read_all_success;
255 }
256
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)
259 {
260 struct timeval tv = { 0, 0 };
261 fd_set readfds;
262 fd_set *fs;
263 int ret;
264
265 if (sd < FD_SETSIZE)
266 {
267 fs = &readfds;
268 FD_ZERO(fs);
269 }
270 else
271 {
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; }
280 }
281 FD_SET(sd, fs);
282 ret = select((int)sd+1, fs, (fd_set*)NULL, (fd_set*)NULL, &tv);
283 if (fs != &readfds) free(fs);
284 return (ret > 0);
285 }
286
287 // Wait for daemon to write to socket
288 static int wait_for_daemon(dnssd_sock_t sock, int timeout)
289 {
290 #ifndef WIN32
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.
294 (void) sock;
295 (void) timeout;
296 #else
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.
301 if (!gDaemonErr)
302 {
303 struct timeval tv;
304 fd_set set;
305
306 FD_ZERO(&set);
307 FD_SET(sock, &set);
308 tv.tv_sec = timeout;
309 tv.tv_usec = 0;
310 if (!select((int)(sock + 1), &set, NULL, NULL, &tv))
311 {
312 syslog(LOG_WARNING, "dnssd_clientstub wait_for_daemon timed out");
313 gDaemonErr = kDNSServiceErr_Timeout;
314 }
315 }
316 #endif
317 return gDaemonErr;
318 }
319
320 /* create_hdr
321 *
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.
329 */
330 static ipc_msg_hdr *create_hdr(uint32_t op, size_t *len, char **data_start, int SeparateReturnSocket, DNSServiceOp *ref)
331 {
332 char *msg = NULL;
333 ipc_msg_hdr *hdr;
334 int datalen;
335 #if !defined(USE_TCP_LOOPBACK)
336 char ctrl_path[64] = ""; // "/var/tmp/dnssd_result_socket.xxxxxxxxxx-xxx-xxxxxx"
337 #endif
338
339 if (SeparateReturnSocket)
340 {
341 #if defined(USE_TCP_LOOPBACK)
342 *len += 2; // Allocate space for two-byte port number
343 #elif defined(USE_NAMED_ERROR_RETURN_SOCKET)
344 struct timeval tv;
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;
350 #else
351 *len += 1; // Allocate space for single zero byte (empty C string)
352 #endif
353 }
354
355 datalen = (int) *len;
356 *len += sizeof(ipc_msg_hdr);
357
358 // Write message to buffer
359 msg = malloc(*len);
360 if (!msg) { syslog(LOG_WARNING, "dnssd_clientstub create_hdr: malloc failed"); return NULL; }
361
362 memset(msg, 0, *len);
363 hdr = (ipc_msg_hdr *)msg;
364 hdr->version = VERSION;
365 hdr->datalen = datalen;
366 hdr->ipc_flags = 0;
367 hdr->op = op;
368 hdr->client_context = ref->uid;
369 hdr->reg_index = 0;
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);
375 #else
376 if (SeparateReturnSocket) put_string(ctrl_path, data_start);
377 #endif
378 return hdr;
379 }
380
381 static void FreeDNSRecords(DNSServiceOp *sdRef)
382 {
383 DNSRecord *rec = sdRef->rec;
384 while (rec)
385 {
386 DNSRecord *next = rec->recnext;
387 free(rec);
388 rec = next;
389 }
390 }
391
392 static void FreeDNSServiceOp(DNSServiceOp *x)
393 {
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);
398 else
399 {
400 x->next = NULL;
401 x->primary = NULL;
402 x->sockfd = dnssd_InvalidSocket;
403 x->validator = 0xDDDDDDDD;
404 x->op = request_op_none;
405 x->max_index = 0;
406 x->logcounter = 0;
407 x->moreptr = NULL;
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;
415 #endif
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
419 FreeDNSRecords(x);
420 if (x->kacontext)
421 {
422 free(x->kacontext);
423 x->kacontext = NULL;
424 }
425 free(x);
426 }
427 }
428
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)
431 {
432 #if APPLE_OSX_mDNSResponder
433 int NumTries = DNSSD_CLIENT_MAXTRIES;
434 #else
435 int NumTries = 0;
436 #endif
437
438 dnssd_sockaddr_t saddr;
439 DNSServiceOp *sdr;
440
441 if (!ref) { syslog(LOG_WARNING, "dnssd_clientstub DNSService operation with NULL DNSServiceRef"); return kDNSServiceErr_BadParam; }
442
443 if (flags & kDNSServiceFlagsShareConnection)
444 {
445 if (!*ref)
446 {
447 syslog(LOG_WARNING, "dnssd_clientstub kDNSServiceFlagsShareConnection used with NULL DNSServiceRef");
448 return kDNSServiceErr_BadParam;
449 }
450 if (!DNSServiceRefValid(*ref) || (*ref)->op != connection_request || (*ref)->primary)
451 {
452 syslog(LOG_WARNING, "dnssd_clientstub kDNSServiceFlagsShareConnection used with invalid DNSServiceRef %p %08X %08X",
453 (*ref), (*ref)->sockfd, (*ref)->validator);
454 *ref = NULL;
455 return kDNSServiceErr_BadReference;
456 }
457 }
458
459 #if defined(_WIN32)
460 if (!g_initWinsock)
461 {
462 WSADATA wsaData;
463 g_initWinsock = 1;
464 if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) { *ref = NULL; return kDNSServiceErr_ServiceNotRunning; }
465 }
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;
468 #endif
469
470 sdr = malloc(sizeof(DNSServiceOp));
471 if (!sdr) { syslog(LOG_WARNING, "dnssd_clientstub ConnectToServer: malloc failed"); *ref = NULL; return kDNSServiceErr_NoMemory; }
472 sdr->next = NULL;
473 sdr->primary = NULL;
474 sdr->sockfd = dnssd_InvalidSocket;
475 sdr->validator = sdr->sockfd ^ ValidatorBits;
476 sdr->op = op;
477 sdr->max_index = 0;
478 sdr->logcounter = 0;
479 sdr->moreptr = NULL;
480 sdr->uid.u32[0] = 0;
481 sdr->uid.u32[1] = 0;
482 sdr->ProcessReply = ProcessReply;
483 sdr->AppCallback = AppCallback;
484 sdr->AppContext = AppContext;
485 sdr->rec = NULL;
486 #if _DNS_SD_LIBDISPATCH
487 sdr->disp_source = NULL;
488 sdr->disp_queue = NULL;
489 #endif
490 sdr->kacontext = NULL;
491
492 if (flags & kDNSServiceFlagsShareConnection)
493 {
494 DNSServiceOp **p = &(*ref)->next; // Append ourselves to end of primary's list
495 while (*p) p = &(*p)->next;
496 *p = sdr;
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);
504 }
505 else
506 {
507 #ifdef SO_NOSIGPIPE
508 const unsigned long optval = 1;
509 #endif
510 *ref = NULL;
511 sdr->sockfd = socket(AF_DNSSD, SOCK_STREAM, 0);
512 sdr->validator = sdr->sockfd ^ ValidatorBits;
513 if (!dnssd_SocketValid(sdr->sockfd))
514 {
515 syslog(LOG_WARNING, "dnssd_clientstub ConnectToServer: socket failed %d %s", dnssd_errno, dnssd_strerror(dnssd_errno));
516 FreeDNSServiceOp(sdr);
517 return kDNSServiceErr_NoMemory;
518 }
519 #ifdef SO_NOSIGPIPE
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));
523 #endif
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);
528 #else
529 saddr.sun_family = AF_LOCAL;
530 strcpy(saddr.sun_path, MDNS_UDS_SERVERPATH);
531 #if !defined(__ppc__) && defined(SO_DEFUNCTOK)
532 {
533 int defunct = 1;
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));
536 }
537 #endif
538 #endif
539
540 while (1)
541 {
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; }
551 }
552 //printf("ConnectToServer opened socket %d\n", sdr->sockfd);
553 }
554
555 *ref = sdr;
556 return kDNSServiceErr_NoError;
557 }
558
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)
561
562 static DNSServiceErrorType deliver_request(ipc_msg_hdr *hdr, DNSServiceOp *sdr)
563 {
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);
567 #endif
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;
571
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)
576 if (sdr->primary ||
577 hdr->op == reg_record_request || hdr->op == add_record_request || hdr->op == update_record_request || hdr->op == remove_record_request)
578 MakeSeparateReturnSocket = 1;
579
580 if (!DNSServiceRefValid(sdr))
581 {
582 syslog(LOG_WARNING, "dnssd_clientstub deliver_request: invalid DNSServiceRef %p %08X %08X", sdr, sdr->sockfd, sdr->validator);
583 return kDNSServiceErr_BadReference;
584 }
585
586 if (!hdr) { syslog(LOG_WARNING, "dnssd_clientstub deliver_request: !hdr"); return kDNSServiceErr_Unknown; }
587
588 if (MakeSeparateReturnSocket)
589 {
590 #if defined(USE_TCP_LOOPBACK)
591 {
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");
597
598 caddr.sin_family = AF_INET;
599 caddr.sin_port = 0;
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
607 }
608 #elif defined(USE_NAMED_ERROR_RETURN_SOCKET)
609 {
610 mode_t mask;
611 int bindresult;
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");
615
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);
621 #endif
622 strcpy(caddr.sun_path, data);
623 mask = umask(0);
624 bindresult = bind(listenfd, (struct sockaddr *)&caddr, sizeof(caddr));
625 umask(mask);
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");
628 }
629 #else
630 {
631 dnssd_sock_t sp[2];
632 if (socketpair(AF_DNSSD, SOCK_STREAM, 0, sp) < 0) deliver_request_bailout("socketpair");
633 else
634 {
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)
638 {
639 int defunct = 1;
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));
642 }
643 #endif
644 }
645 }
646 #endif
647 }
648
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
657 #endif
658
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
664 unsigned int i;
665 for (i=0; i<datalen + sizeof(ipc_msg_hdr); i++)
666 {
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; }
670 usleep(10000);
671 }
672 #else
673 if (write_all(sdr->sockfd, (char *)hdr, datalen + sizeof(ipc_msg_hdr)) < 0)
674 {
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)));
680 goto cleanup;
681 }
682 #endif
683
684 if (!MakeSeparateReturnSocket) errsd = sdr->sockfd;
685 if (MakeSeparateReturnSocket || sdr->op == send_bpf) // Okay to use sdr->op when checking for op == send_bpf
686 {
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");
695 #else
696
697 struct iovec vec = { ((char *)hdr) + sizeof(ipc_msg_hdr) + datalen, 1 }; // Send the last byte along with the SCM_RIGHTS
698 struct msghdr msg;
699 struct cmsghdr *cmsg;
700 char cbuf[CMSG_SPACE(sizeof(dnssd_sock_t))];
701
702 if (sdr->op == send_bpf) // Okay to use sdr->op when checking for op == send_bpf
703 {
704 int i;
705 char p[12]; // Room for "/dev/bpf999" with terminating null
706 for (i=0; i<100; i++)
707 {
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;
714 }
715 }
716
717 msg.msg_name = 0;
718 msg.msg_namelen = 0;
719 msg.msg_iov = &vec;
720 msg.msg_iovlen = 1;
721 msg.msg_control = cbuf;
722 msg.msg_controllen = CMSG_LEN(sizeof(dnssd_sock_t));
723 msg.msg_flags = 0;
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;
729
730 #if TEST_KQUEUE_CONTROL_MESSAGE_BUG
731 sleep(1);
732 #endif
733
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
741
742 if (sendmsg(sdr->sockfd, &msg, 0) < 0)
743 {
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;
747 goto cleanup;
748 }
749
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
753
754 #endif
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
760 }
761
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)
767 {
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
770 else
771 err = ntohl(err);
772 }
773
774 //syslog(LOG_WARNING, "dnssd_clientstub deliver_request: retrieved error code %d", err);
775
776 cleanup:
777 if (MakeSeparateReturnSocket)
778 {
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);
786 #endif
787 }
788
789 free(hdr);
790 return err;
791 }
792
793 int DNSSD_API DNSServiceRefSockFD(DNSServiceRef sdRef)
794 {
795 if (!sdRef) { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRefSockFD called with NULL DNSServiceRef"); return dnssd_InvalidSocket; }
796
797 if (!DNSServiceRefValid(sdRef))
798 {
799 syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRefSockFD called with invalid DNSServiceRef %p %08X %08X",
800 sdRef, sdRef->sockfd, sdRef->validator);
801 return dnssd_InvalidSocket;
802 }
803
804 if (sdRef->primary)
805 {
806 syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRefSockFD undefined for kDNSServiceFlagsShareConnection subordinate DNSServiceRef %p", sdRef);
807 return dnssd_InvalidSocket;
808 }
809
810 return (int) sdRef->sockfd;
811 }
812
813 #if _DNS_SD_LIBDISPATCH
814 static void CallbackWithError(DNSServiceRef sdRef, DNSServiceErrorType error)
815 {
816 DNSServiceOp *sdr = sdRef;
817 DNSServiceOp *sdrNext;
818 DNSRecord *rec;
819 DNSRecord *recnext;
820 int morebytes;
821
822 while (sdr)
823 {
824 // We can't touch the sdr after the callback as it can be deallocated in the callback
825 sdrNext = sdr->next;
826 morebytes = 1;
827 sdr->moreptr = &morebytes;
828 switch (sdr->op)
829 {
830 case resolve_request:
831 if (sdr->AppCallback) ((DNSServiceResolveReply) sdr->AppCallback)(sdr, 0, 0, error, NULL, 0, 0, 0, NULL, sdr->AppContext);
832 break;
833 case query_request:
834 if (sdr->AppCallback) ((DNSServiceQueryRecordReply)sdr->AppCallback)(sdr, 0, 0, error, NULL, 0, 0, 0, NULL, 0, sdr->AppContext);
835 break;
836 case addrinfo_request:
837 if (sdr->AppCallback) ((DNSServiceGetAddrInfoReply)sdr->AppCallback)(sdr, 0, 0, error, NULL, NULL, 0, sdr->AppContext);
838 break;
839 case browse_request:
840 if (sdr->AppCallback) ((DNSServiceBrowseReply) sdr->AppCallback)(sdr, 0, 0, error, NULL, 0, NULL, sdr->AppContext);
841 break;
842 case reg_service_request:
843 if (sdr->AppCallback) ((DNSServiceRegisterReply) sdr->AppCallback)(sdr, 0, error, NULL, 0, NULL, sdr->AppContext);
844 break;
845 case enumeration_request:
846 if (sdr->AppCallback) ((DNSServiceDomainEnumReply) sdr->AppCallback)(sdr, 0, 0, error, NULL, sdr->AppContext);
847 break;
848 case connection_request:
849 // This means Register Record, walk the list of DNSRecords to do the callback
850 rec = sdr->rec;
851 while (rec)
852 {
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;}
858 rec = recnext;
859 }
860 break;
861 case port_mapping_request:
862 if (sdr->AppCallback) ((DNSServiceNATPortMappingReply)sdr->AppCallback)(sdr, 0, 0, error, 0, 0, 0, 0, 0, sdr->AppContext);
863 break;
864 default:
865 syslog(LOG_WARNING, "dnssd_clientstub CallbackWithError called with bad op %d", sdr->op);
866 }
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.
872 //
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;}
877 sdr = sdrNext;
878 }
879 }
880 #endif // _DNS_SD_LIBDISPATCH
881
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)
885 {
886 int morebytes = 0;
887
888 if (!sdRef) { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceProcessResult called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam; }
889
890 if (!DNSServiceRefValid(sdRef))
891 {
892 syslog(LOG_WARNING, "dnssd_clientstub DNSServiceProcessResult called with invalid DNSServiceRef %p %08X %08X", sdRef, sdRef->sockfd, sdRef->validator);
893 return kDNSServiceErr_BadReference;
894 }
895
896 if (sdRef->primary)
897 {
898 syslog(LOG_WARNING, "dnssd_clientstub DNSServiceProcessResult undefined for kDNSServiceFlagsShareConnection subordinate DNSServiceRef %p", sdRef);
899 return kDNSServiceErr_BadReference;
900 }
901
902 if (!sdRef->ProcessReply)
903 {
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;
908 }
909
910 do
911 {
912 CallbackHeader cbh;
913 char *data;
914
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)
921 {
922 // Set the ProcessReply to NULL before callback as the sdRef can get deallocated
923 // in the callback.
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)
932 {
933 dispatch_source_cancel(sdRef->disp_source);
934 dispatch_release(sdRef->disp_source);
935 sdRef->disp_source = NULL;
936 CallbackWithError(sdRef, kDNSServiceErr_ServiceNotRunning);
937 }
938 #endif
939 // Don't touch sdRef anymore as it might have been deallocated
940 return kDNSServiceErr_ServiceNotRunning;
941 }
942 else if (result == read_all_wouldblock)
943 {
944 if (morebytes && sdRef->logcounter < 100)
945 {
946 sdRef->logcounter++;
947 syslog(LOG_WARNING, "dnssd_clientstub DNSServiceProcessResult error: select indicated data was waiting but read_all returned EWOULDBLOCK");
948 }
949 return kDNSServiceErr_NoError;
950 }
951
952 ConvertHeaderBytes(&cbh.ipc_hdr);
953 if (cbh.ipc_hdr.version != VERSION)
954 {
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;
958 }
959
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
963 {
964 // Set the ProcessReply to NULL before callback as the sdRef can get deallocated
965 // in the callback.
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)
972 {
973 dispatch_source_cancel(sdRef->disp_source);
974 dispatch_release(sdRef->disp_source);
975 sdRef->disp_source = NULL;
976 CallbackWithError(sdRef, kDNSServiceErr_ServiceNotRunning);
977 }
978 #endif
979 // Don't touch sdRef anymore as it might have been deallocated
980 free(data);
981 return kDNSServiceErr_ServiceNotRunning;
982 }
983 else
984 {
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);
989
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);
994 if (morebytes)
995 {
996 cbh.cb_flags |= kDNSServiceFlagsMoreComing;
997 sdRef->moreptr = &morebytes;
998 }
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;
1009 }
1010 free(data);
1011 } while (morebytes);
1012
1013 return kDNSServiceErr_NoError;
1014 }
1015
1016 void DNSSD_API DNSServiceRefDeallocate(DNSServiceRef sdRef)
1017 {
1018 if (!sdRef) { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRefDeallocate called with NULL DNSServiceRef"); return; }
1019
1020 if (!DNSServiceRefValid(sdRef)) // Also verifies dnssd_SocketValid(sdRef->sockfd) for us too
1021 {
1022 syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRefDeallocate called with invalid DNSServiceRef %p %08X %08X", sdRef, sdRef->sockfd, sdRef->validator);
1023 return;
1024 }
1025
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;
1028
1029 if (sdRef->primary) // If this is a subordinate DNSServiceOp, just send a 'stop' command
1030 {
1031 DNSServiceOp **p = &sdRef->primary->next;
1032 while (*p && *p != sdRef) p = &(*p)->next;
1033 if (*p)
1034 {
1035 char *ptr;
1036 size_t len = 0;
1037 ipc_msg_hdr *hdr = create_hdr(cancel_request, &len, &ptr, 0, sdRef);
1038 if (hdr)
1039 {
1040 ConvertHeaderBytes(hdr);
1041 write_all(sdRef->sockfd, (char *)hdr, len);
1042 free(hdr);
1043 }
1044 *p = sdRef->next;
1045 FreeDNSServiceOp(sdRef);
1046 }
1047 }
1048 else // else, make sure to terminate all subordinates as well
1049 {
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)
1053 {
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;
1065 }
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);
1070 #else
1071 dnssd_close(sdRef->sockfd);
1072 #endif
1073 // Free DNSRecords added in DNSRegisterRecord if they have not
1074 // been freed in DNSRemoveRecord
1075 while (sdRef)
1076 {
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);
1087 }
1088 }
1089 }
1090
1091 DNSServiceErrorType DNSSD_API DNSServiceGetProperty(const char *property, void *result, uint32_t *size)
1092 {
1093 char *ptr;
1094 size_t len = strlen(property) + 1;
1095 ipc_msg_hdr *hdr;
1096 DNSServiceOp *tmp;
1097 uint32_t actualsize;
1098
1099 DNSServiceErrorType err = ConnectToServer(&tmp, 0, getproperty_request, NULL, NULL, NULL);
1100 if (err) return err;
1101
1102 hdr = create_hdr(getproperty_request, &len, &ptr, 0, tmp);
1103 if (!hdr) { DNSServiceRefDeallocate(tmp); return kDNSServiceErr_NoMemory; }
1104
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; }
1109
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);
1114
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);
1118
1119 *size = actualsize;
1120 return kDNSServiceErr_NoError;
1121 }
1122
1123 static void handle_resolve_response(DNSServiceOp *const sdr, const CallbackHeader *const cbh, const char *data, const char *end)
1124 {
1125 char fullname[kDNSServiceMaxDomainName];
1126 char target[kDNSServiceMaxDomainName];
1127 uint16_t txtlen;
1128 union { uint16_t s; u_char b[2]; } port;
1129 unsigned char *txtrecord;
1130
1131 get_string(&data, end, fullname, kDNSServiceMaxDomainName);
1132 get_string(&data, end, target, kDNSServiceMaxDomainName);
1133 if (!data || data + 2 > end) goto fail;
1134
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);
1139
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);
1142 return;
1143 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1144 fail:
1145 syslog(LOG_WARNING, "dnssd_clientstub handle_resolve_response: error reading result from daemon");
1146 }
1147
1148 #if APPLE_OSX_mDNSResponder
1149
1150 static int32_t libSystemVersion = 0;
1151
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()
1156 {
1157 if (libSystemVersion == 0)
1158 libSystemVersion = NSVersionOfLinkTimeLibrary("System");
1159
1160 if (libSystemVersion < 0xa00000)
1161 return 1;
1162 else
1163 return 0;
1164 }
1165
1166 #else // APPLE_OSX_mDNSResponder
1167
1168 // always return false for non Apple platforms
1169 static int includeP2PWithIndexAny()
1170 {
1171 return 0;
1172 }
1173
1174 #endif // APPLE_OSX_mDNSResponder
1175
1176 DNSServiceErrorType DNSSD_API DNSServiceResolve
1177 (
1178 DNSServiceRef *sdRef,
1179 DNSServiceFlags flags,
1180 uint32_t interfaceIndex,
1181 const char *name,
1182 const char *regtype,
1183 const char *domain,
1184 DNSServiceResolveReply callBack,
1185 void *context
1186 )
1187 {
1188 char *ptr;
1189 size_t len;
1190 ipc_msg_hdr *hdr;
1191 DNSServiceErrorType err;
1192
1193 if (!name || !regtype || !domain || !callBack) return kDNSServiceErr_BadParam;
1194
1195 // Need a real InterfaceID for WakeOnResolve
1196 if ((flags & kDNSServiceFlagsWakeOnResolve) != 0 &&
1197 ((interfaceIndex == kDNSServiceInterfaceIndexAny) ||
1198 (interfaceIndex == kDNSServiceInterfaceIndexLocalOnly) ||
1199 (interfaceIndex == kDNSServiceInterfaceIndexUnicast) ||
1200 (interfaceIndex == kDNSServiceInterfaceIndexP2P)))
1201 {
1202 return kDNSServiceErr_BadParam;
1203 }
1204
1205 if ((interfaceIndex == kDNSServiceInterfaceIndexAny) && includeP2PWithIndexAny())
1206 flags |= kDNSServiceFlagsIncludeP2P;
1207
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
1210
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;
1217
1218 hdr = create_hdr(resolve_request, &len, &ptr, (*sdRef)->primary ? 1 : 0, *sdRef);
1219 if (!hdr) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; return kDNSServiceErr_NoMemory; }
1220
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);
1226
1227 err = deliver_request(hdr, *sdRef); // Will free hdr for us
1228 if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
1229 return err;
1230 }
1231
1232 static void handle_query_response(DNSServiceOp *const sdr, const CallbackHeader *const cbh, const char *data, const char *const end)
1233 {
1234 uint32_t ttl;
1235 char name[kDNSServiceMaxDomainName];
1236 uint16_t rrtype, rrclass, rdlen;
1237 const char *rdata;
1238
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);
1245
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
1249 }
1250
1251 DNSServiceErrorType DNSSD_API DNSServiceQueryRecord
1252 (
1253 DNSServiceRef *sdRef,
1254 DNSServiceFlags flags,
1255 uint32_t interfaceIndex,
1256 const char *name,
1257 uint16_t rrtype,
1258 uint16_t rrclass,
1259 DNSServiceQueryRecordReply callBack,
1260 void *context
1261 )
1262 {
1263 char *ptr;
1264 size_t len;
1265 ipc_msg_hdr *hdr;
1266 DNSServiceErrorType err;
1267
1268 if ((interfaceIndex == kDNSServiceInterfaceIndexAny) && includeP2PWithIndexAny())
1269 flags |= kDNSServiceFlagsIncludeP2P;
1270
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
1273
1274 if (!name) name = "\0";
1275
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
1281
1282 hdr = create_hdr(query_request, &len, &ptr, (*sdRef)->primary ? 1 : 0, *sdRef);
1283 if (!hdr) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; return kDNSServiceErr_NoMemory; }
1284
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);
1290
1291 err = deliver_request(hdr, *sdRef); // Will free hdr for us
1292 if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
1293 return err;
1294 }
1295
1296 static void handle_addrinfo_response(DNSServiceOp *const sdr, const CallbackHeader *const cbh, const char *data, const char *const end)
1297 {
1298 char hostname[kDNSServiceMaxDomainName];
1299 uint16_t rrtype, rrclass, rdlen;
1300 const char *rdata;
1301 uint32_t ttl;
1302
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);
1309
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)
1316 {
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)
1321 {
1322 memset(&sa4, 0, sizeof(sa4));
1323 #ifndef NOT_HAVE_SA_LEN
1324 sa4.sin_len = sizeof(struct sockaddr_in);
1325 #endif
1326 sa4.sin_family = AF_INET;
1327 // sin_port = 0;
1328 if (!cbh->cb_err) memcpy(&sa4.sin_addr, rdata, rdlen);
1329 }
1330 else
1331 {
1332 memset(&sa6, 0, sizeof(sa6));
1333 #ifndef NOT_HAVE_SA_LEN
1334 sa6.sin6_len = sizeof(struct sockaddr_in6);
1335 #endif
1336 sa6.sin6_family = AF_INET6;
1337 // sin6_port = 0;
1338 // sin6_flowinfo = 0;
1339 // sin6_scope_id = 0;
1340 if (!cbh->cb_err)
1341 {
1342 memcpy(&sa6.sin6_addr, rdata, rdlen);
1343 if (IN6_IS_ADDR_LINKLOCAL(&sa6.sin6_addr)) sa6.sin6_scope_id = cbh->cb_interface;
1344 }
1345 }
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
1348 }
1349 }
1350
1351 DNSServiceErrorType DNSSD_API DNSServiceGetAddrInfo
1352 (
1353 DNSServiceRef *sdRef,
1354 DNSServiceFlags flags,
1355 uint32_t interfaceIndex,
1356 uint32_t protocol,
1357 const char *hostname,
1358 DNSServiceGetAddrInfoReply callBack,
1359 void *context /* may be NULL */
1360 )
1361 {
1362 char *ptr;
1363 size_t len;
1364 ipc_msg_hdr *hdr;
1365 DNSServiceErrorType err;
1366
1367 if (!hostname) return kDNSServiceErr_BadParam;
1368
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
1371
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;
1377
1378 hdr = create_hdr(addrinfo_request, &len, &ptr, (*sdRef)->primary ? 1 : 0, *sdRef);
1379 if (!hdr) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; return kDNSServiceErr_NoMemory; }
1380
1381 put_flags(flags, &ptr);
1382 put_uint32(interfaceIndex, &ptr);
1383 put_uint32(protocol, &ptr);
1384 put_string(hostname, &ptr);
1385
1386 err = deliver_request(hdr, *sdRef); // Will free hdr for us
1387 if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
1388 return err;
1389 }
1390
1391 static void handle_browse_response(DNSServiceOp *const sdr, const CallbackHeader *const cbh, const char *data, const char *const end)
1392 {
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
1400 }
1401
1402 DNSServiceErrorType DNSSD_API DNSServiceBrowse
1403 (
1404 DNSServiceRef *sdRef,
1405 DNSServiceFlags flags,
1406 uint32_t interfaceIndex,
1407 const char *regtype,
1408 const char *domain,
1409 DNSServiceBrowseReply callBack,
1410 void *context
1411 )
1412 {
1413 char *ptr;
1414 size_t len;
1415 ipc_msg_hdr *hdr;
1416 DNSServiceErrorType err;
1417
1418 if ((interfaceIndex == kDNSServiceInterfaceIndexAny) && includeP2PWithIndexAny())
1419 flags |= kDNSServiceFlagsIncludeP2P;
1420
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
1423
1424 if (!domain) domain = "";
1425 len = sizeof(flags);
1426 len += sizeof(interfaceIndex);
1427 len += strlen(regtype) + 1;
1428 len += strlen(domain) + 1;
1429
1430 hdr = create_hdr(browse_request, &len, &ptr, (*sdRef)->primary ? 1 : 0, *sdRef);
1431 if (!hdr) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; return kDNSServiceErr_NoMemory; }
1432
1433 put_flags(flags, &ptr);
1434 put_uint32(interfaceIndex, &ptr);
1435 put_string(regtype, &ptr);
1436 put_string(domain, &ptr);
1437
1438 err = deliver_request(hdr, *sdRef); // Will free hdr for us
1439 if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
1440 return err;
1441 }
1442
1443 DNSServiceErrorType DNSSD_API DNSServiceSetDefaultDomainForUser(DNSServiceFlags flags, const char *domain);
1444 DNSServiceErrorType DNSSD_API DNSServiceSetDefaultDomainForUser(DNSServiceFlags flags, const char *domain)
1445 {
1446 DNSServiceOp *tmp;
1447 char *ptr;
1448 size_t len = sizeof(flags) + strlen(domain) + 1;
1449 ipc_msg_hdr *hdr;
1450 DNSServiceErrorType err = ConnectToServer(&tmp, 0, setdomain_request, NULL, NULL, NULL);
1451 if (err) return err;
1452
1453 hdr = create_hdr(setdomain_request, &len, &ptr, 0, tmp);
1454 if (!hdr) { DNSServiceRefDeallocate(tmp); return kDNSServiceErr_NoMemory; }
1455
1456 put_flags(flags, &ptr);
1457 put_string(domain, &ptr);
1458 err = deliver_request(hdr, tmp); // Will free hdr for us
1459 DNSServiceRefDeallocate(tmp);
1460 return err;
1461 }
1462
1463 static void handle_regservice_response(DNSServiceOp *const sdr, const CallbackHeader *const cbh, const char *data, const char *const end)
1464 {
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
1472 }
1473
1474 DNSServiceErrorType DNSSD_API DNSServiceRegister
1475 (
1476 DNSServiceRef *sdRef,
1477 DNSServiceFlags flags,
1478 uint32_t interfaceIndex,
1479 const char *name,
1480 const char *regtype,
1481 const char *domain,
1482 const char *host,
1483 uint16_t PortInNetworkByteOrder,
1484 uint16_t txtLen,
1485 const void *txtRecord,
1486 DNSServiceRegisterReply callBack,
1487 void *context
1488 )
1489 {
1490 char *ptr;
1491 size_t len;
1492 ipc_msg_hdr *hdr;
1493 DNSServiceErrorType err;
1494 union { uint16_t s; u_char b[2]; } port = { PortInNetworkByteOrder };
1495
1496 if (!name) name = "";
1497 if (!regtype) return kDNSServiceErr_BadParam;
1498 if (!domain) domain = "";
1499 if (!host) host = "";
1500 if (!txtRecord) txtRecord = (void*)"";
1501
1502 // No callback must have auto-rename
1503 if (!callBack && (flags & kDNSServiceFlagsNoAutoRename)) return kDNSServiceErr_BadParam;
1504
1505 if ((interfaceIndex == kDNSServiceInterfaceIndexAny) && includeP2PWithIndexAny())
1506 flags |= kDNSServiceFlagsIncludeP2P;
1507
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
1510
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
1515 len += txtLen;
1516
1517 hdr = create_hdr(reg_service_request, &len, &ptr, (*sdRef)->primary ? 1 : 0, *sdRef);
1518 if (!hdr) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; return kDNSServiceErr_NoMemory; }
1519
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.
1524
1525 if (!(flags & kDNSServiceFlagsShareConnection) && !callBack) hdr->ipc_flags |= IPC_FLAGS_NOREPLY;
1526
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);
1533 *ptr++ = port.b[0];
1534 *ptr++ = port.b[1];
1535 put_uint16(txtLen, &ptr);
1536 put_rdata(txtLen, txtRecord, &ptr);
1537
1538 err = deliver_request(hdr, *sdRef); // Will free hdr for us
1539 if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
1540 return err;
1541 }
1542
1543 static void handle_enumeration_response(DNSServiceOp *const sdr, const CallbackHeader *const cbh, const char *data, const char *const end)
1544 {
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
1550 }
1551
1552 DNSServiceErrorType DNSSD_API DNSServiceEnumerateDomains
1553 (
1554 DNSServiceRef *sdRef,
1555 DNSServiceFlags flags,
1556 uint32_t interfaceIndex,
1557 DNSServiceDomainEnumReply callBack,
1558 void *context
1559 )
1560 {
1561 char *ptr;
1562 size_t len;
1563 ipc_msg_hdr *hdr;
1564 DNSServiceErrorType err;
1565
1566 int f1 = (flags & kDNSServiceFlagsBrowseDomains) != 0;
1567 int f2 = (flags & kDNSServiceFlagsRegistrationDomains) != 0;
1568 if (f1 + f2 != 1) return kDNSServiceErr_BadParam;
1569
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
1572
1573 len = sizeof(DNSServiceFlags);
1574 len += sizeof(uint32_t);
1575
1576 hdr = create_hdr(enumeration_request, &len, &ptr, (*sdRef)->primary ? 1 : 0, *sdRef);
1577 if (!hdr) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; return kDNSServiceErr_NoMemory; }
1578
1579 put_flags(flags, &ptr);
1580 put_uint32(interfaceIndex, &ptr);
1581
1582 err = deliver_request(hdr, *sdRef); // Will free hdr for us
1583 if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
1584 return err;
1585 }
1586
1587 static void ConnectionResponse(DNSServiceOp *const sdr, const CallbackHeader *const cbh, const char *const data, const char *const end)
1588 {
1589 DNSRecordRef rref = cbh->ipc_hdr.client_context.context;
1590 (void)data; // Unused
1591
1592 //printf("ConnectionResponse got %d\n", cbh->ipc_hdr.op);
1593 if (cbh->ipc_hdr.op != reg_record_reply_op)
1594 {
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]))
1600 op = op->next;
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
1605 return;
1606 }
1607
1608 if (sdr->op == connection_request)
1609 rref->AppCallback(rref->sdr, rref, cbh->cb_flags, cbh->cb_err, rref->AppContext);
1610 else
1611 {
1612 syslog(LOG_WARNING, "dnssd_clientstub ConnectionResponse: sdr->op != connection_request");
1613 rref->AppCallback(rref->sdr, rref, 0, kDNSServiceErr_Unknown, rref->AppContext);
1614 }
1615 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1616 }
1617
1618 DNSServiceErrorType DNSSD_API DNSServiceCreateConnection(DNSServiceRef *sdRef)
1619 {
1620 char *ptr;
1621 size_t len = 0;
1622 ipc_msg_hdr *hdr;
1623 DNSServiceErrorType err = ConnectToServer(sdRef, 0, connection_request, ConnectionResponse, NULL, NULL);
1624 if (err) return err; // On error ConnectToServer leaves *sdRef set to NULL
1625
1626 hdr = create_hdr(connection_request, &len, &ptr, 0, *sdRef);
1627 if (!hdr) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; return kDNSServiceErr_NoMemory; }
1628
1629 err = deliver_request(hdr, *sdRef); // Will free hdr for us
1630 if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
1631 return err;
1632 }
1633
1634 DNSServiceErrorType DNSSD_API DNSServiceRegisterRecord
1635 (
1636 DNSServiceRef sdRef,
1637 DNSRecordRef *RecordRef,
1638 DNSServiceFlags flags,
1639 uint32_t interfaceIndex,
1640 const char *fullname,
1641 uint16_t rrtype,
1642 uint16_t rrclass,
1643 uint16_t rdlen,
1644 const void *rdata,
1645 uint32_t ttl,
1646 DNSServiceRegisterRecordReply callBack,
1647 void *context
1648 )
1649 {
1650 char *ptr;
1651 size_t len;
1652 ipc_msg_hdr *hdr = NULL;
1653 DNSRecordRef rref = NULL;
1654 DNSRecord **p;
1655 int f1 = (flags & kDNSServiceFlagsShared) != 0;
1656 int f2 = (flags & kDNSServiceFlagsUnique) != 0;
1657 if (f1 + f2 != 1) return kDNSServiceErr_BadParam;
1658
1659 if ((interfaceIndex == kDNSServiceInterfaceIndexAny) && includeP2PWithIndexAny())
1660 flags |= kDNSServiceFlagsIncludeP2P;
1661
1662 if (!sdRef) { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRegisterRecord called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam; }
1663
1664 if (!DNSServiceRefValid(sdRef))
1665 {
1666 syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRegisterRecord called with invalid DNSServiceRef %p %08X %08X", sdRef, sdRef->sockfd, sdRef->validator);
1667 return kDNSServiceErr_BadReference;
1668 }
1669
1670 if (sdRef->op != connection_request)
1671 {
1672 syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRegisterRecord called with non-DNSServiceCreateConnection DNSServiceRef %p %d", sdRef, sdRef->op);
1673 return kDNSServiceErr_BadReference;
1674 }
1675
1676 *RecordRef = NULL;
1677
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;
1682 len += rdlen;
1683
1684 hdr = create_hdr(reg_record_request, &len, &ptr, 1, sdRef);
1685 if (!hdr) return kDNSServiceErr_NoMemory;
1686
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);
1695
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++;
1701 rref->sdr = sdRef;
1702 rref->recnext = NULL;
1703 *RecordRef = rref;
1704 hdr->client_context.context = rref;
1705 hdr->reg_index = rref->record_index;
1706
1707 p = &(sdRef)->rec;
1708 while (*p) p = &(*p)->recnext;
1709 *p = rref;
1710
1711 return deliver_request(hdr, sdRef); // Will free hdr for us
1712 }
1713
1714 // sdRef returned by DNSServiceRegister()
1715 DNSServiceErrorType DNSSD_API DNSServiceAddRecord
1716 (
1717 DNSServiceRef sdRef,
1718 DNSRecordRef *RecordRef,
1719 DNSServiceFlags flags,
1720 uint16_t rrtype,
1721 uint16_t rdlen,
1722 const void *rdata,
1723 uint32_t ttl
1724 )
1725 {
1726 ipc_msg_hdr *hdr;
1727 size_t len = 0;
1728 char *ptr;
1729 DNSRecordRef rref;
1730 DNSRecord **p;
1731
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)
1735 {
1736 syslog(LOG_WARNING, "dnssd_clientstub DNSServiceAddRecord called with non-DNSServiceRegister DNSServiceRef %p %d", sdRef, sdRef->op);
1737 return kDNSServiceErr_BadReference;
1738 }
1739
1740 if (!DNSServiceRefValid(sdRef))
1741 {
1742 syslog(LOG_WARNING, "dnssd_clientstub DNSServiceAddRecord called with invalid DNSServiceRef %p %08X %08X", sdRef, sdRef->sockfd, sdRef->validator);
1743 return kDNSServiceErr_BadReference;
1744 }
1745
1746 *RecordRef = NULL;
1747
1748 len += 2 * sizeof(uint16_t); // rrtype, rdlen
1749 len += rdlen;
1750 len += sizeof(uint32_t);
1751 len += sizeof(DNSServiceFlags);
1752
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);
1760
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++;
1766 rref->sdr = sdRef;
1767 rref->recnext = NULL;
1768 *RecordRef = rref;
1769 hdr->reg_index = rref->record_index;
1770
1771 p = &(sdRef)->rec;
1772 while (*p) p = &(*p)->recnext;
1773 *p = rref;
1774
1775 return deliver_request(hdr, sdRef); // Will free hdr for us
1776 }
1777
1778 // DNSRecordRef returned by DNSServiceRegisterRecord or DNSServiceAddRecord
1779 DNSServiceErrorType DNSSD_API DNSServiceUpdateRecord
1780 (
1781 DNSServiceRef sdRef,
1782 DNSRecordRef RecordRef,
1783 DNSServiceFlags flags,
1784 uint16_t rdlen,
1785 const void *rdata,
1786 uint32_t ttl
1787 )
1788 {
1789 ipc_msg_hdr *hdr;
1790 size_t len = 0;
1791 char *ptr;
1792
1793 if (!sdRef) { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceUpdateRecord called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam; }
1794
1795 if (!DNSServiceRefValid(sdRef))
1796 {
1797 syslog(LOG_WARNING, "dnssd_clientstub DNSServiceUpdateRecord called with invalid DNSServiceRef %p %08X %08X", sdRef, sdRef->sockfd, sdRef->validator);
1798 return kDNSServiceErr_BadReference;
1799 }
1800
1801 // Note: RecordRef is allowed to be NULL
1802
1803 len += sizeof(uint16_t);
1804 len += rdlen;
1805 len += sizeof(uint32_t);
1806 len += sizeof(DNSServiceFlags);
1807
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
1816 }
1817
1818 DNSServiceErrorType DNSSD_API DNSServiceRemoveRecord
1819 (
1820 DNSServiceRef sdRef,
1821 DNSRecordRef RecordRef,
1822 DNSServiceFlags flags
1823 )
1824 {
1825 ipc_msg_hdr *hdr;
1826 size_t len = 0;
1827 char *ptr;
1828 DNSServiceErrorType err;
1829
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; }
1833
1834 if (!DNSServiceRefValid(sdRef))
1835 {
1836 syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRemoveRecord called with invalid DNSServiceRef %p %08X %08X", sdRef, sdRef->sockfd, sdRef->validator);
1837 return kDNSServiceErr_BadReference;
1838 }
1839
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
1846 if (!err)
1847 {
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;
1853 free(RecordRef);
1854 }
1855 return err;
1856 }
1857
1858 DNSServiceErrorType DNSSD_API DNSServiceReconfirmRecord
1859 (
1860 DNSServiceFlags flags,
1861 uint32_t interfaceIndex,
1862 const char *fullname,
1863 uint16_t rrtype,
1864 uint16_t rrclass,
1865 uint16_t rdlen,
1866 const void *rdata
1867 )
1868 {
1869 char *ptr;
1870 size_t len;
1871 ipc_msg_hdr *hdr;
1872 DNSServiceOp *tmp;
1873
1874 DNSServiceErrorType err = ConnectToServer(&tmp, flags, reconfirm_record_request, NULL, NULL, NULL);
1875 if (err) return err;
1876
1877 len = sizeof(DNSServiceFlags);
1878 len += sizeof(uint32_t);
1879 len += strlen(fullname) + 1;
1880 len += 3 * sizeof(uint16_t);
1881 len += rdlen;
1882 hdr = create_hdr(reconfirm_record_request, &len, &ptr, 0, tmp);
1883 if (!hdr) { DNSServiceRefDeallocate(tmp); return kDNSServiceErr_NoMemory; }
1884
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);
1892
1893 err = deliver_request(hdr, tmp); // Will free hdr for us
1894 DNSServiceRefDeallocate(tmp);
1895 return err;
1896 }
1897
1898 static void handle_port_mapping_response(DNSServiceOp *const sdr, const CallbackHeader *const cbh, const char *data, const char *const end)
1899 {
1900 union { uint32_t l; u_char b[4]; } addr;
1901 uint8_t protocol;
1902 union { uint16_t s; u_char b[2]; } internalPort;
1903 union { uint16_t s; u_char b[2]; } externalPort;
1904 uint32_t ttl;
1905
1906 if (!data || data + 13 > end) goto fail;
1907
1908 addr.b[0] = *data++;
1909 addr.b[1] = *data++;
1910 addr.b[2] = *data++;
1911 addr.b[3] = *data++;
1912 protocol = *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;
1919
1920 ((DNSServiceNATPortMappingReply)sdr->AppCallback)(sdr, cbh->cb_flags, cbh->cb_interface, cbh->cb_err, addr.l, protocol, internalPort.s, externalPort.s, ttl, sdr->AppContext);
1921 return;
1922 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1923
1924 fail :
1925 syslog(LOG_WARNING, "dnssd_clientstub handle_port_mapping_response: error reading result from daemon");
1926 }
1927
1928 DNSServiceErrorType DNSSD_API DNSServiceNATPortMappingCreate
1929 (
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 */
1939 )
1940 {
1941 char *ptr;
1942 size_t len;
1943 ipc_msg_hdr *hdr;
1944 union { uint16_t s; u_char b[2]; } internalPort = { internalPortInNetworkByteOrder };
1945 union { uint16_t s; u_char b[2]; } externalPort = { externalPortInNetworkByteOrder };
1946
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
1949
1950 len = sizeof(flags);
1951 len += sizeof(interfaceIndex);
1952 len += sizeof(protocol);
1953 len += sizeof(internalPort);
1954 len += sizeof(externalPort);
1955 len += sizeof(ttl);
1956
1957 hdr = create_hdr(port_mapping_request, &len, &ptr, (*sdRef)->primary ? 1 : 0, *sdRef);
1958 if (!hdr) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; return kDNSServiceErr_NoMemory; }
1959
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);
1968
1969 err = deliver_request(hdr, *sdRef); // Will free hdr for us
1970 if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
1971 return err;
1972 }
1973
1974 #if _DNS_SD_LIBDISPATCH
1975 DNSServiceErrorType DNSSD_API DNSServiceSetDispatchQueue
1976 (
1977 DNSServiceRef service,
1978 dispatch_queue_t queue
1979 )
1980 {
1981 int dnssd_fd = DNSServiceRefSockFD(service);
1982 if (dnssd_fd == dnssd_InvalidSocket) return kDNSServiceErr_BadParam;
1983 if (!queue)
1984 {
1985 syslog(LOG_WARNING, "dnssd_clientstub: DNSServiceSetDispatchQueue dispatch queue NULL");
1986 return kDNSServiceErr_BadParam;
1987 }
1988 if (service->disp_queue)
1989 {
1990 syslog(LOG_WARNING, "dnssd_clientstub DNSServiceSetDispatchQueue dispatch queue set already");
1991 return kDNSServiceErr_BadParam;
1992 }
1993 if (service->disp_source)
1994 {
1995 syslog(LOG_WARNING, "DNSServiceSetDispatchQueue dispatch source set already");
1996 return kDNSServiceErr_BadParam;
1997 }
1998 service->disp_source = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, dnssd_fd, 0, queue);
1999 if (!service->disp_source)
2000 {
2001 syslog(LOG_WARNING, "DNSServiceSetDispatchQueue dispatch_source_create failed");
2002 return kDNSServiceErr_NoMemory;
2003 }
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;
2009 }
2010 #endif // _DNS_SD_LIBDISPATCH
2011
2012 #if !defined(_WIN32)
2013
2014 static void DNSSD_API SleepKeepaliveCallback(DNSServiceRef sdRef, DNSRecordRef rec, const DNSServiceFlags flags,
2015 DNSServiceErrorType errorCode, void *context)
2016 {
2017 SleepKAContext *ka = (SleepKAContext *)context;
2018 (void)rec; // Unused
2019 (void)flags; // Unused
2020
2021 if (sdRef->kacontext != context)
2022 syslog(LOG_WARNING, "SleepKeepaliveCallback context mismatch");
2023
2024 if (ka->AppCallback)
2025 ((DNSServiceSleepKeepaliveReply)ka->AppCallback)(sdRef, errorCode, ka->AppContext);
2026 }
2027
2028 DNSServiceErrorType DNSSD_API DNSServiceSleepKeepalive
2029 (
2030 DNSServiceRef *sdRef,
2031 DNSServiceFlags flags,
2032 int fd,
2033 unsigned int timeout,
2034 DNSServiceSleepKeepaliveReply callBack,
2035 void *context
2036 )
2037 {
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;
2044 char buf[256];
2045 DNSServiceErrorType err;
2046 DNSRecordRef record = NULL;
2047 char name[10];
2048 char recname[128];
2049 SleepKAContext *ka;
2050 unsigned int i, unique;
2051
2052
2053 (void) flags; //unused
2054 if (!timeout) return kDNSServiceErr_BadParam;
2055
2056
2057 len1 = sizeof(lss);
2058 if (getsockname(fd, (struct sockaddr *)&lss, &len1) < 0)
2059 {
2060 syslog(LOG_WARNING, "DNSServiceSleepKeepalive: getsockname %d\n", errno);
2061 return kDNSServiceErr_BadParam;
2062 }
2063
2064 len2 = sizeof(rss);
2065 if (getpeername(fd, (struct sockaddr *)&rss, &len2) < 0)
2066 {
2067 syslog(LOG_WARNING, "DNSServiceSleepKeepalive: getpeername %d\n", errno);
2068 return kDNSServiceErr_BadParam;
2069 }
2070
2071 if (len1 != len2)
2072 {
2073 syslog(LOG_WARNING, "DNSServiceSleepKeepalive local/remote info not same");
2074 return kDNSServiceErr_Unknown;
2075 }
2076
2077 unique = 0;
2078 if (lss.ss_family == AF_INET)
2079 {
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;
2083
2084 if (!inet_ntop(AF_INET, (const void *)&sr->sin_addr, target_str, sizeof (target_str)))
2085 {
2086 syslog(LOG_WARNING, "DNSServiceSleepKeepalive remote info failed %d", errno);
2087 return kDNSServiceErr_Unknown;
2088 }
2089 if (!inet_ntop(AF_INET, (const void *)&sl->sin_addr, source_str, sizeof (source_str)))
2090 {
2091 syslog(LOG_WARNING, "DNSServiceSleepKeepalive local info failed %d", errno);
2092 return kDNSServiceErr_Unknown;
2093 }
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++)
2097 unique += ptr[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));
2100 }
2101 else
2102 {
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;
2106
2107 if (!inet_ntop(AF_INET6, (const void *)&sr6->sin6_addr, target_str, sizeof (target_str)))
2108 {
2109 syslog(LOG_WARNING, "DNSServiceSleepKeepalive remote6 info failed %d", errno);
2110 return kDNSServiceErr_Unknown;
2111 }
2112 if (!inet_ntop(AF_INET6, (const void *)&sl6->sin6_addr, source_str, sizeof (source_str)))
2113 {
2114 syslog(LOG_WARNING, "DNSServiceSleepKeepalive local6 info failed %d", errno);
2115 return kDNSServiceErr_Unknown;
2116 }
2117 for (i = 0; i < sizeof(struct in6_addr); i++)
2118 unique += ptr[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));
2121 }
2122
2123 if (len >= (sizeof(buf) - 1))
2124 {
2125 syslog(LOG_WARNING, "DNSServiceSleepKeepalive could not fit local/remote info");
2126 return kDNSServiceErr_Unknown;
2127 }
2128 // Include the NULL byte also in the first byte. The total length of the record includes the
2129 // first byte also.
2130 buf[0] = len + 1;
2131 proxyreclen = len + 2;
2132
2133 len = snprintf(name, sizeof(name), "%u", unique);
2134 if (len >= sizeof(name))
2135 {
2136 syslog(LOG_WARNING, "DNSServiceSleepKeepalive could not fit unique");
2137 return kDNSServiceErr_Unknown;
2138 }
2139
2140 len = snprintf(recname, sizeof(recname), "%s.%s", name, "_keepalive._dns-sd._udp.local");
2141 if (len >= sizeof(recname))
2142 {
2143 syslog(LOG_WARNING, "DNSServiceSleepKeepalive could not fit name");
2144 return kDNSServiceErr_Unknown;
2145 }
2146
2147 ka = malloc(sizeof(SleepKAContext));
2148 if (!ka) return kDNSServiceErr_NoMemory;
2149 ka->AppCallback = callBack;
2150 ka->AppContext = context;
2151
2152 err = DNSServiceCreateConnection(sdRef);
2153 if (err)
2154 {
2155 syslog(LOG_WARNING, "DNSServiceSleepKeepalive cannot create connection");
2156 free(ka);
2157 return err;
2158 }
2159
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);
2163 if (err)
2164 {
2165 syslog(LOG_WARNING, "DNSServiceSleepKeepalive cannot create connection");
2166 free(ka);
2167 return err;
2168 }
2169 (*sdRef)->kacontext = ka;
2170 return kDNSServiceErr_NoError;
2171 }
2172 #endif