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