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