]> git.saurik.com Git - apple/mdnsresponder.git/blob - mDNSShared/dnssd_clientstub.c
mDNSResponder-171.4.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 Change History (most recent first):
29
30 $Log: dnssd_clientstub.c,v $
31 Revision 1.102 2008/02/25 19:16:19 cheshire
32 <rdar://problem/5708953> Problems with DNSServiceGetAddrInfo API
33 Was returning a bogus result (NULL pointer) when following a CNAME referral
34
35 Revision 1.101 2008/02/20 21:18:21 cheshire
36 <rdar://problem/5708953> DNSServiceGetAddrInfo doesn't set the scope ID of returned IPv6 link local addresses
37
38 Revision 1.100 2007/11/02 17:56:37 cheshire
39 <rdar://problem/5565787> Bonjour API broken for 64-bit apps (SCM_RIGHTS sendmsg fails)
40 Wrap hack code in "#if APPLE_OSX_mDNSResponder" since (as far as we know right now)
41 we don't want to do this on 64-bit Linux, Solaris, etc.
42
43 Revision 1.99 2007/11/02 17:29:40 cheshire
44 <rdar://problem/5565787> Bonjour API broken for 64-bit apps (SCM_RIGHTS sendmsg fails)
45 To get 64-bit code that works, we need to NOT use the standard CMSG_* macros
46
47 Revision 1.98 2007/11/01 19:52:43 cheshire
48 Wrap debugging messages in "#if DEBUG_64BIT_SCM_RIGHTS"
49
50 Revision 1.97 2007/11/01 19:45:55 cheshire
51 Added "DEBUG_64BIT_SCM_RIGHTS" debugging code
52 See <rdar://problem/5565787> Bonjour API broken for 64-bit apps (SCM_RIGHTS sendmsg fails)
53
54 Revision 1.96 2007/11/01 15:59:33 cheshire
55 umask not being set and restored properly in USE_NAMED_ERROR_RETURN_SOCKET code
56 (no longer used on OS X, but relevant for other platforms)
57
58 Revision 1.95 2007/10/31 20:07:16 cheshire
59 <rdar://problem/5541498> Set SO_NOSIGPIPE on client socket
60 Refinement: the cleanup code still needs to close listenfd when necesssary
61
62 Revision 1.94 2007/10/15 22:34:27 cheshire
63 <rdar://problem/5541498> Set SO_NOSIGPIPE on client socket
64
65 Revision 1.93 2007/10/10 00:48:54 cheshire
66 <rdar://problem/5526379> Daemon spins in an infinite loop when it doesn't get the control message it's expecting
67
68 Revision 1.92 2007/10/06 03:44:44 cheshire
69 Testing code for <rdar://problem/5526374> kqueue does not get a kevent to wake it up when a control message arrives on a socket
70
71 Revision 1.91 2007/10/04 20:53:59 cheshire
72 Improved debugging message when sendmsg fails
73
74 Revision 1.90 2007/09/30 00:09:27 cheshire
75 <rdar://problem/5492315> Pass socket fd via SCM_RIGHTS sendmsg instead of using named UDS in the filesystem
76
77 Revision 1.89 2007/09/19 23:53:12 cheshire
78 Fixed spelling mistake in comment
79
80 Revision 1.88 2007/09/07 23:18:27 cheshire
81 <rdar://problem/5467542> Change "client_context" to be an incrementing 64-bit counter
82
83 Revision 1.87 2007/09/07 22:50:09 cheshire
84 Added comment explaining moreptr field in DNSServiceOp structure
85
86 Revision 1.86 2007/09/07 20:21:22 cheshire
87 <rdar://problem/5462371> Make DNSSD library more resilient
88 Add more comments explaining the moreptr/morebytes logic; don't allow DNSServiceRefSockFD or
89 DNSServiceProcessResult for subordinate DNSServiceRefs created using kDNSServiceFlagsShareConnection
90
91 Revision 1.85 2007/09/06 21:43:23 cheshire
92 <rdar://problem/5462371> Make DNSSD library more resilient
93 Allow DNSServiceRefDeallocate from within DNSServiceProcessResult callback
94
95 Revision 1.84 2007/09/06 18:31:47 cheshire
96 <rdar://problem/5462371> Make DNSSD library more resilient against client programming errors
97
98 Revision 1.83 2007/08/28 20:45:45 cheshire
99 Typo: ctrl_path needs to be 64 bytes, not 44 bytes
100
101 Revision 1.82 2007/08/28 19:53:52 cheshire
102 <rdar://problem/5437423> Bonjour failures when /tmp is not writable (e.g. when booted from installer disc)
103
104 Revision 1.81 2007/07/27 00:03:20 cheshire
105 Fixed compiler warnings that showed up now we're building optimized ("-Os")
106
107 Revision 1.80 2007/07/23 22:12:53 cheshire
108 <rdar://problem/5352299> Make mDNSResponder more defensive against malicious local clients
109
110 Revision 1.79 2007/07/23 19:58:24 cheshire
111 <rdar://problem/5351640> Library: Leak in DNSServiceRefDeallocate
112
113 Revision 1.78 2007/07/12 20:42:27 cheshire
114 <rdar://problem/5280735> If daemon is killed, return kDNSServiceErr_ServiceNotRunning
115 to clients instead of kDNSServiceErr_Unknown
116
117 Revision 1.77 2007/07/02 23:07:13 cheshire
118 <rdar://problem/5308280> Reduce DNS-SD client syslog error messages
119
120 Revision 1.76 2007/06/22 20:12:18 cheshire
121 <rdar://problem/5277024> Leak in DNSServiceRefDeallocate
122
123 Revision 1.75 2007/05/23 18:59:22 cheshire
124 Remove unnecessary IPC_FLAGS_REUSE_SOCKET
125
126 Revision 1.74 2007/05/22 18:28:38 cheshire
127 Fixed compile errors in posix build
128
129 Revision 1.73 2007/05/22 01:20:47 cheshire
130 To determine current operation, need to check hdr->op, not sdr->op
131
132 Revision 1.72 2007/05/22 01:07:42 cheshire
133 <rdar://problem/3563675> API: Need a way to get version/feature information
134
135 Revision 1.71 2007/05/18 23:55:22 cheshire
136 <rdar://problem/4454655> Allow multiple register/browse/resolve operations to share single Unix Domain Socket
137
138 Revision 1.70 2007/05/17 20:58:22 cheshire
139 <rdar://problem/4647145> DNSServiceQueryRecord should return useful information with NXDOMAIN
140
141 Revision 1.69 2007/05/16 16:58:27 cheshire
142 <rdar://problem/4471320> Improve reliability of kDNSServiceFlagsMoreComing flag on multiprocessor machines
143 As long as select indicates that data is waiting, loop within DNSServiceProcessResult delivering additional results
144
145 Revision 1.68 2007/05/16 01:06:52 cheshire
146 <rdar://problem/4471320> Improve reliability of kDNSServiceFlagsMoreComing flag on multiprocessor machines
147
148 Revision 1.67 2007/05/15 21:57:16 cheshire
149 <rdar://problem/4608220> Use dnssd_SocketValid(x) macro instead of just
150 assuming that all negative values (or zero!) are invalid socket numbers
151
152 Revision 1.66 2007/03/27 22:23:04 cheshire
153 Add "dnssd_clientstub" prefix onto syslog messages
154
155 Revision 1.65 2007/03/21 22:25:23 cheshire
156 <rdar://problem/4172796> Remove client retry logic now that mDNSResponder uses launchd for its Unix Domain Socket
157
158 Revision 1.64 2007/03/21 19:01:56 cheshire
159 <rdar://problem/5078494> IPC code not 64-bit-savvy: assumes long=32bits, and short=16bits
160
161 Revision 1.63 2007/03/12 21:48:21 cheshire
162 <rdar://problem/5000162> Scary unlink errors in system.log
163 Code was using memory after it had been freed
164
165 Revision 1.62 2007/02/28 01:44:30 cheshire
166 <rdar://problem/5027863> Byte order bugs in uDNS.c, uds_daemon.c, dnssd_clientstub.c
167
168 Revision 1.61 2007/02/09 03:09:42 cheshire
169 <rdar://problem/3869251> Cleanup: Stop returning kDNSServiceErr_Unknown so often
170 <rdar://problem/4177924> API: Should return kDNSServiceErr_ServiceNotRunning
171
172 Revision 1.60 2007/02/08 20:33:44 cheshire
173 <rdar://problem/4985095> Leak on error path in DNSServiceProcessResult
174
175 Revision 1.59 2007/01/05 08:30:55 cheshire
176 Trim excessive "$Log" checkin history from before 2006
177 (checkin history still available via "cvs log ..." of course)
178
179 Revision 1.58 2006/10/27 00:38:22 cheshire
180 Strip accidental trailing whitespace from lines
181
182 Revision 1.57 2006/09/30 01:06:54 cheshire
183 Protocol field should be uint32_t
184
185 Revision 1.56 2006/09/27 00:44:16 herscher
186 <rdar://problem/4249761> API: Need DNSServiceGetAddrInfo()
187
188 Revision 1.55 2006/09/26 01:52:01 herscher
189 <rdar://problem/4245016> NAT Port Mapping API (for both NAT-PMP and UPnP Gateway Protocol)
190
191 Revision 1.54 2006/09/21 21:34:09 cheshire
192 <rdar://problem/4100000> Allow empty string name when using kDNSServiceFlagsNoAutoRename
193
194 Revision 1.53 2006/09/07 04:43:12 herscher
195 Fix compile error on Win32 platform by moving inclusion of syslog.h
196
197 Revision 1.52 2006/08/15 23:04:21 mkrochma
198 <rdar://problem/4090354> Client should be able to specify service name w/o callback
199
200 Revision 1.51 2006/07/24 23:45:55 cheshire
201 <rdar://problem/4605276> DNSServiceReconfirmRecord() should return error code
202
203 Revision 1.50 2006/06/28 08:22:27 cheshire
204 <rdar://problem/4605264> dnssd_clientstub.c needs to report unlink failures in syslog
205
206 Revision 1.49 2006/06/28 07:58:59 cheshire
207 Minor textual tidying
208
209 */
210
211 #include <errno.h>
212 #include <stdlib.h>
213
214 #include "dnssd_ipc.h"
215
216 #if defined(_WIN32)
217
218 #include <winsock2.h>
219 #include <ws2tcpip.h>
220 #include <windows.h>
221
222 #define sockaddr_mdns sockaddr_in
223 #define AF_MDNS AF_INET
224
225 // Disable warning: "'type cast' : from data pointer 'void *' to function pointer"
226 #pragma warning(disable:4055)
227
228 // Disable warning: "nonstandard extension, function/data pointer conversion in expression"
229 #pragma warning(disable:4152)
230
231 extern BOOL IsSystemServiceDisabled();
232
233 #define sleep(X) Sleep((X) * 1000)
234
235 static int g_initWinsock = 0;
236
237 #else
238
239 #include <sys/time.h>
240 #include <sys/socket.h>
241 #include <syslog.h>
242
243 #define sockaddr_mdns sockaddr_un
244 #define AF_MDNS AF_LOCAL
245
246 #endif
247
248 // <rdar://problem/4096913> Specifies how many times we'll try and connect to the server.
249
250 #define DNSSD_CLIENT_MAXTRIES 4
251
252 // Uncomment the line below to use the old error return mechanism of creating a temporary named socket (e.g. in /var/tmp)
253 //#define USE_NAMED_ERROR_RETURN_SOCKET 1
254
255 #ifndef CTL_PATH_PREFIX
256 #define CTL_PATH_PREFIX "/var/tmp/dnssd_result_socket."
257 #endif
258
259 typedef struct
260 {
261 ipc_msg_hdr ipc_hdr;
262 DNSServiceFlags cb_flags;
263 uint32_t cb_interface;
264 DNSServiceErrorType cb_err;
265 } CallbackHeader;
266
267 typedef struct _DNSServiceRef_t DNSServiceOp;
268 typedef struct _DNSRecordRef_t DNSRecord;
269
270 // client stub callback to process message from server and deliver results to client application
271 typedef void (*ProcessReplyFn)(DNSServiceOp *sdr, CallbackHeader *cbh, char *msg, char *end);
272
273 #define ValidatorBits 0x12345678
274 #define DNSServiceRefValid(X) (dnssd_SocketValid((X)->sockfd) && (((X)->sockfd ^ (X)->validator) == ValidatorBits))
275
276 // When using kDNSServiceFlagsShareConnection, there is one primary _DNSServiceOp_t, and zero or more subordinates
277 // For the primary, the 'next' field points to the first subordinate, and its 'next' field points to the next, and so on.
278 // For the primary, the 'primary' field is NULL; for subordinates the 'primary' field points back to the associated primary
279 struct _DNSServiceRef_t
280 {
281 DNSServiceOp *next; // For shared connection
282 DNSServiceOp *primary; // For shared connection
283 dnssd_sock_t sockfd; // Connected socket between client and daemon
284 dnssd_sock_t validator; // Used to detect memory corruption, double disposals, etc.
285 client_context_t uid; // For shared connection requests, each subordinate DNSServiceRef has its own ID,
286 // unique within the scope of the same shared parent DNSServiceRef
287 uint32_t op; // request_op_t or reply_op_t
288 uint32_t max_index; // Largest assigned record index - 0 if no additional records registered
289 uint32_t logcounter; // Counter used to control number of syslog messages we write
290 int *moreptr; // Set while DNSServiceProcessResult working on this particular DNSServiceRef
291 ProcessReplyFn ProcessReply; // Function pointer to the code to handle received messages
292 void *AppCallback; // Client callback function and context
293 void *AppContext;
294 };
295
296 struct _DNSRecordRef_t
297 {
298 void *AppContext;
299 DNSServiceRegisterRecordReply AppCallback;
300 DNSRecordRef recref;
301 uint32_t record_index; // index is unique to the ServiceDiscoveryRef
302 DNSServiceOp *sdr;
303 };
304
305 // Write len bytes. Return 0 on success, -1 on error
306 static int write_all(dnssd_sock_t sd, char *buf, int len)
307 {
308 // Don't use "MSG_WAITALL"; it returns "Invalid argument" on some Linux versions; use an explicit while() loop instead.
309 //if (send(sd, buf, len, MSG_WAITALL) != len) return -1;
310 while (len)
311 {
312 ssize_t num_written = send(sd, buf, len, 0);
313 if (num_written < 0 || num_written > len)
314 {
315 // Should never happen. If it does, it indicates some OS bug,
316 // or that the mDNSResponder daemon crashed (which should never happen).
317 syslog(LOG_WARNING, "dnssd_clientstub write_all(%d) failed %d/%d %d %s", sd, num_written, len,
318 (num_written < 0) ? errno : 0,
319 (num_written < 0) ? strerror(errno) : "");
320 return -1;
321 }
322 buf += num_written;
323 len -= num_written;
324 }
325 return 0;
326 }
327
328 // Read len bytes. Return 0 on success, -1 on error
329 static int read_all(dnssd_sock_t sd, char *buf, int len)
330 {
331 // Don't use "MSG_WAITALL"; it returns "Invalid argument" on some Linux versions; use an explicit while() loop instead.
332 //if (recv(sd, buf, len, MSG_WAITALL) != len) return -1;
333
334 while (len)
335 {
336 ssize_t num_read = recv(sd, buf, len, 0);
337 if ((num_read == 0) || (num_read < 0) || (num_read > len))
338 {
339 // Should never happen. If it does, it indicates some OS bug,
340 // or that the mDNSResponder daemon crashed (which should never happen).
341 syslog(LOG_WARNING, "dnssd_clientstub read_all(%d) failed %d/%d %d %s", sd, num_read, len,
342 (num_read < 0) ? errno : 0,
343 (num_read < 0) ? strerror(errno) : "");
344 return -1;
345 }
346 buf += num_read;
347 len -= num_read;
348 }
349 return 0;
350 }
351
352 // Returns 1 if more bytes remain to be read on socket descriptor sd, 0 otherwise
353 static int more_bytes(dnssd_sock_t sd)
354 {
355 struct timeval tv = { 0, 0 };
356 fd_set readfds;
357 FD_ZERO(&readfds);
358 FD_SET(sd, &readfds);
359 return(select(sd+1, &readfds, (fd_set*)NULL, (fd_set*)NULL, &tv) > 0);
360 }
361
362 /* create_hdr
363 *
364 * allocate and initialize an ipc message header. Value of len should initially be the
365 * length of the data, and is set to the value of the data plus the header. data_start
366 * is set to point to the beginning of the data section. SeparateReturnSocket should be
367 * non-zero for calls that can't receive an immediate error return value on their primary
368 * socket, and therefore require a separate return path for the error code result.
369 * if zero, the path to a control socket is appended at the beginning of the message buffer.
370 * data_start is set past this string.
371 */
372 static ipc_msg_hdr *create_hdr(uint32_t op, size_t *len, char **data_start, int SeparateReturnSocket, DNSServiceOp *ref)
373 {
374 char *msg = NULL;
375 ipc_msg_hdr *hdr;
376 int datalen;
377 #if !defined(USE_TCP_LOOPBACK)
378 char ctrl_path[64] = ""; // "/var/tmp/dnssd_result_socket.xxxxxxxxxx-xxx-xxxxxx"
379 #endif
380
381 if (SeparateReturnSocket)
382 {
383 #if defined(USE_TCP_LOOPBACK)
384 *len += 2; // Allocate space for two-byte port number
385 #elif defined(USE_NAMED_ERROR_RETURN_SOCKET)
386 struct timeval time;
387 if (gettimeofday(&time, NULL) < 0)
388 { syslog(LOG_WARNING, "dnssd_clientstub create_hdr: gettimeofday failed %d %s", errno, strerror(errno)); return NULL; }
389 sprintf(ctrl_path, "%s%d-%.3lx-%.6lu", CTL_PATH_PREFIX, (int)getpid(),
390 (unsigned long)(time.tv_sec & 0xFFF), (unsigned long)(time.tv_usec));
391 *len += strlen(ctrl_path) + 1;
392 #else
393 *len += 1; // Allocate space for single zero byte (empty C string)
394 #endif
395 }
396
397 datalen = (int) *len;
398 *len += sizeof(ipc_msg_hdr);
399
400 // Write message to buffer
401 msg = malloc(*len);
402 if (!msg) { syslog(LOG_WARNING, "dnssd_clientstub create_hdr: malloc failed"); return NULL; }
403
404 bzero(msg, *len);
405 hdr = (ipc_msg_hdr *)msg;
406 hdr->version = VERSION;
407 hdr->datalen = datalen;
408 hdr->ipc_flags = 0;
409 hdr->op = op;
410 hdr->client_context = ref->uid;
411 hdr->reg_index = 0;
412 *data_start = msg + sizeof(ipc_msg_hdr);
413 #if defined(USE_TCP_LOOPBACK)
414 // Put dummy data in for the port, since we don't know what it is yet.
415 // The data will get filled in before we send the message. This happens in deliver_request().
416 if (SeparateReturnSocket) put_uint16(0, data_start);
417 #else
418 if (SeparateReturnSocket) put_string(ctrl_path, data_start);
419 #endif
420 return hdr;
421 }
422
423 static void FreeDNSServiceOp(DNSServiceOp *x)
424 {
425 // We don't use our DNSServiceRefValid macro here because if we're cleaning up after a socket() call failed
426 // then sockfd could legitimately contain a failing value (e.g. dnssd_InvalidSocket)
427 if ((x->sockfd ^ x->validator) != ValidatorBits)
428 syslog(LOG_WARNING, "dnssd_clientstub attempt to dispose invalid DNSServiceRef %p %08X %08X", x, x->sockfd, x->validator);
429 else
430 {
431 x->next = NULL;
432 x->primary = NULL;
433 x->sockfd = dnssd_InvalidSocket;
434 x->validator = 0xDDDDDDDD;
435 x->op = request_op_none;
436 x->max_index = 0;
437 x->logcounter = 0;
438 x->moreptr = NULL;
439 x->ProcessReply = NULL;
440 x->AppCallback = NULL;
441 x->AppContext = NULL;
442 free(x);
443 }
444 }
445
446 // Return a connected service ref (deallocate with DNSServiceRefDeallocate)
447 static DNSServiceErrorType ConnectToServer(DNSServiceRef *ref, DNSServiceFlags flags, uint32_t op, ProcessReplyFn ProcessReply, void *AppCallback, void *AppContext)
448 {
449 #if APPLE_OSX_mDNSResponder
450 int NumTries = DNSSD_CLIENT_MAXTRIES;
451 #else
452 int NumTries = 0;
453 #endif
454
455 dnssd_sockaddr_t saddr;
456 DNSServiceOp *sdr;
457
458 if (!ref) { syslog(LOG_WARNING, "dnssd_clientstub DNSService operation with NULL DNSServiceRef"); return kDNSServiceErr_BadParam; }
459
460 if (flags & kDNSServiceFlagsShareConnection)
461 {
462 if (!*ref)
463 {
464 syslog(LOG_WARNING, "dnssd_clientstub kDNSServiceFlagsShareConnection used with NULL DNSServiceRef");
465 return kDNSServiceErr_BadParam;
466 }
467 if (!DNSServiceRefValid(*ref))
468 {
469 syslog(LOG_WARNING, "dnssd_clientstub kDNSServiceFlagsShareConnection used with invalid DNSServiceRef %p %08X %08X",
470 (*ref), (*ref)->sockfd, (*ref)->validator);
471 *ref = NULL;
472 return kDNSServiceErr_BadReference;
473 }
474 }
475
476 #if defined(_WIN32)
477 if (!g_initWinsock)
478 {
479 WSADATA wsaData;
480 g_initWinsock = 1;
481 if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) { *ref = NULL; return kDNSServiceErr_ServiceNotRunning; }
482 }
483 // <rdar://problem/4096913> If the system service is disabled, we only want to try to connect once
484 if (IsSystemServiceDisabled()) NumTries = DNSSD_CLIENT_MAXTRIES;
485 #endif
486
487 sdr = malloc(sizeof(DNSServiceOp));
488 if (!sdr) { syslog(LOG_WARNING, "dnssd_clientstub ConnectToServer: malloc failed"); *ref = NULL; return kDNSServiceErr_NoMemory; }
489 sdr->next = NULL;
490 sdr->primary = NULL;
491 sdr->sockfd = dnssd_InvalidSocket;
492 sdr->validator = sdr->sockfd ^ ValidatorBits;
493 sdr->op = op;
494 sdr->max_index = 0;
495 sdr->logcounter = 0;
496 sdr->moreptr = NULL;
497 sdr->uid.u32[0] = 0;
498 sdr->uid.u32[1] = 0;
499 sdr->ProcessReply = ProcessReply;
500 sdr->AppCallback = AppCallback;
501 sdr->AppContext = AppContext;
502
503 if (flags & kDNSServiceFlagsShareConnection)
504 {
505 DNSServiceOp **p = &(*ref)->next; // Append ourselves to end of primary's list
506 while (*p) p = &(*p)->next;
507 *p = sdr;
508 sdr->primary = *ref; // Set our primary pointer
509 sdr->sockfd = (*ref)->sockfd; // Inherit primary's socket
510 sdr->validator = (*ref)->validator;
511 sdr->uid = (*ref)->uid;
512 if (++(*ref)->uid.u32[0] == 0) ++(*ref)->uid.u32[1]; // In parent DNSServiceOp increment UID counter
513 //printf("ConnectToServer sharing socket %d\n", sdr->sockfd);
514 }
515 else
516 {
517 #ifdef SO_NOSIGPIPE
518 const unsigned long optval = 1;
519 #endif
520 *ref = NULL;
521 sdr->sockfd = socket(AF_DNSSD, SOCK_STREAM, 0);
522 sdr->validator = sdr->sockfd ^ ValidatorBits;
523 if (!dnssd_SocketValid(sdr->sockfd))
524 {
525 syslog(LOG_WARNING, "dnssd_clientstub ConnectToServer: socket failed %d %s", errno, strerror(errno));
526 FreeDNSServiceOp(sdr);
527 return kDNSServiceErr_NoMemory;
528 }
529 #ifdef SO_NOSIGPIPE
530 // Some environments (e.g. OS X) support turning off SIGPIPE for a socket
531 if (setsockopt(sdr->sockfd, SOL_SOCKET, SO_NOSIGPIPE, &optval, sizeof(optval)) < 0)
532 syslog(LOG_WARNING, "dnssd_clientstub ConnectToServer: SO_NOSIGPIPE failed %d %s", errno, strerror(errno));
533 #endif
534 #if defined(USE_TCP_LOOPBACK)
535 saddr.sin_family = AF_INET;
536 saddr.sin_addr.s_addr = inet_addr(MDNS_TCP_SERVERADDR);
537 saddr.sin_port = htons(MDNS_TCP_SERVERPORT);
538 #else
539 saddr.sun_family = AF_LOCAL;
540 strcpy(saddr.sun_path, MDNS_UDS_SERVERPATH);
541 #endif
542
543 while (1)
544 {
545 int err = connect(sdr->sockfd, (struct sockaddr *) &saddr, sizeof(saddr));
546 if (!err) break; // If we succeeded, return sdr
547 // If we failed, then it may be because the daemon is still launching.
548 // This can happen for processes that launch early in the boot process, while the
549 // daemon is still coming up. Rather than fail here, we'll wait a bit and try again.
550 // If, after four seconds, we still can't connect to the daemon,
551 // then we give up and return a failure code.
552 if (++NumTries < DNSSD_CLIENT_MAXTRIES) sleep(1); // Sleep a bit, then try again
553 else { dnssd_close(sdr->sockfd); FreeDNSServiceOp(sdr); return kDNSServiceErr_ServiceNotRunning; }
554 }
555 //printf("ConnectToServer opened socket %d\n", sdr->sockfd);
556 }
557
558 *ref = sdr;
559 return kDNSServiceErr_NoError;
560 }
561
562 static DNSServiceErrorType deliver_request(ipc_msg_hdr *hdr, DNSServiceOp *sdr)
563 {
564 uint32_t datalen = hdr->datalen; // We take a copy here because we're going to convert hdr->datalen to network byte order
565 #if defined(USE_TCP_LOOPBACK) || defined(USE_NAMED_ERROR_RETURN_SOCKET)
566 char *const data = (char *)hdr + sizeof(ipc_msg_hdr);
567 #endif
568 dnssd_sock_t listenfd = dnssd_InvalidSocket, errsd = dnssd_InvalidSocket;
569 DNSServiceErrorType err;
570 int MakeSeparateReturnSocket = 0;
571
572 // Note: need to check hdr->op, not sdr->op.
573 // hdr->op contains the code for the specific operation we're currently doing, whereas sdr->op
574 // contains the original parent DNSServiceOp (e.g. for an add_record_request, hdr->op will be
575 // add_record_request but the parent sdr->op will be connection_request or reg_service_request)
576 if (sdr->primary ||
577 hdr->op == reg_record_request || hdr->op == add_record_request || hdr->op == update_record_request || hdr->op == remove_record_request)
578 MakeSeparateReturnSocket = 1;
579
580 if (!DNSServiceRefValid(sdr))
581 {
582 syslog(LOG_WARNING, "dnssd_clientstub deliver_request: invalid DNSServiceRef %p %08X %08X", sdr, sdr->sockfd, sdr->validator);
583 return kDNSServiceErr_BadReference;
584 }
585
586 if (!hdr) { syslog(LOG_WARNING, "dnssd_clientstub deliver_request: !hdr"); return kDNSServiceErr_Unknown; }
587
588 if (MakeSeparateReturnSocket)
589 {
590 #if defined(USE_TCP_LOOPBACK)
591 {
592 union { uint16_t s; u_char b[2]; } port;
593 dnssd_sockaddr_t caddr;
594 dnssd_socklen_t len = (dnssd_socklen_t) sizeof(caddr);
595 listenfd = socket(AF_DNSSD, SOCK_STREAM, 0);
596 if (!dnssd_SocketValid(listenfd)) goto cleanup;
597
598 caddr.sin_family = AF_INET;
599 caddr.sin_port = 0;
600 caddr.sin_addr.s_addr = inet_addr(MDNS_TCP_SERVERADDR);
601 if (bind(listenfd, (struct sockaddr*) &caddr, sizeof(caddr)) < 0) goto cleanup;
602 if (getsockname(listenfd, (struct sockaddr*) &caddr, &len) < 0) goto cleanup;
603 listen(listenfd, 1);
604 port.s = caddr.sin_port;
605 data[0] = port.b[0]; // don't switch the byte order, as the
606 data[1] = port.b[1]; // daemon expects it in network byte order
607 }
608 #elif defined(USE_NAMED_ERROR_RETURN_SOCKET)
609 {
610 mode_t mask;
611 int bindresult;
612 dnssd_sockaddr_t caddr;
613 listenfd = socket(AF_DNSSD, SOCK_STREAM, 0);
614 if (!dnssd_SocketValid(listenfd)) goto cleanup;
615
616 caddr.sun_family = AF_LOCAL;
617 // According to Stevens (section 3.2), there is no portable way to
618 // determine whether sa_len is defined on a particular platform.
619 #ifndef NOT_HAVE_SA_LEN
620 caddr.sun_len = sizeof(struct sockaddr_un);
621 #endif
622 strcpy(caddr.sun_path, data);
623 mask = umask(0);
624 bindresult = bind(listenfd, (struct sockaddr *)&caddr, sizeof(caddr));
625 umask(mask);
626 if (bindresult < 0) goto cleanup;
627 listen(listenfd, 1);
628 }
629 #else
630 {
631 dnssd_sock_t sp[2];
632 //if (pipe(sp) < 0)
633 // syslog(LOG_WARNING, "dnssd_clientstub ERROR: pipe() failed errno %d (%s)", errno, strerror(errno));
634 if (socketpair(AF_DNSSD, SOCK_STREAM, 0, sp) < 0)
635 syslog(LOG_WARNING, "dnssd_clientstub ERROR: socketpair() failed errno %d (%s)", errno, strerror(errno));
636 else
637 {
638 errsd = sp[0]; // We'll read our four-byte error code from sp[0]
639 listenfd = sp[1]; // We'll send sp[1] to the daemon
640 }
641 }
642 #endif
643 }
644
645 #if !defined(USE_TCP_LOOPBACK) && !defined(USE_NAMED_ERROR_RETURN_SOCKET)
646 // If we're going to make a separate error return socket, and pass it to the daemon
647 // using sendmsg, then we'll hold back one data byte to go with it.
648 // On some versions of Unix (including Leopard) sending a control message without
649 // any associated data does not work reliably -- e.g. one particular issue we ran
650 // into is that if the receiving program is in a kqueue loop waiting to be notified
651 // of the received message, it doesn't get woken up when the control message arrives.
652 if (MakeSeparateReturnSocket) datalen--;
653 #endif
654
655 // At this point, our listening socket is set up and waiting, if necessary, for the daemon to connect back to
656 ConvertHeaderBytes(hdr);
657 //syslog(LOG_WARNING, "dnssd_clientstub deliver_request writing %ld bytes", datalen + sizeof(ipc_msg_hdr));
658 //if (MakeSeparateReturnSocket) syslog(LOG_WARNING, "dnssd_clientstub deliver_request name is %s", data);
659 #if TEST_SENDING_ONE_BYTE_AT_A_TIME
660 unsigned int i;
661 for (i=0; i<datalen + sizeof(ipc_msg_hdr); i++)
662 {
663 syslog(LOG_WARNING, "dnssd_clientstub writing %d", i);
664 if (write_all(sdr->sockfd, ((char *)hdr)+i, 1) < 0) goto cleanup;
665 usleep(10000);
666 }
667 #else
668 if (write_all(sdr->sockfd, (char *)hdr, datalen + sizeof(ipc_msg_hdr)) < 0) goto cleanup;
669 #endif
670
671 if (!MakeSeparateReturnSocket) errsd = sdr->sockfd;
672 else
673 {
674 #if defined(USE_TCP_LOOPBACK) || defined(USE_NAMED_ERROR_RETURN_SOCKET)
675 // At this point we may block in accept for a few milliseconds waiting for the daemon to connect back to us,
676 // but that's okay -- the daemon is a trusted service and we know if won't take more than a few milliseconds to respond.
677 dnssd_sockaddr_t daddr;
678 dnssd_socklen_t len = sizeof(daddr);
679 errsd = accept(listenfd, (struct sockaddr *)&daddr, &len);
680 if (!dnssd_SocketValid(errsd)) goto cleanup;
681 #else
682
683 #if APPLE_OSX_mDNSResponder
684 // On Leopard, the stock definitions of the CMSG_* macros in /usr/include/sys/socket.h,
685 // while arguably correct in theory, nonetheless in practice produce code that doesn't work on 64-bit machines
686 // For details see <rdar://problem/5565787> Bonjour API broken for 64-bit apps (SCM_RIGHTS sendmsg fails)
687 #undef CMSG_DATA
688 #define CMSG_DATA(cmsg) ((unsigned char *)(cmsg) + (sizeof(struct cmsghdr)))
689 #undef CMSG_SPACE
690 #define CMSG_SPACE(l) ((sizeof(struct cmsghdr)) + (l))
691 #undef CMSG_LEN
692 #define CMSG_LEN(l) ((sizeof(struct cmsghdr)) + (l))
693 #endif
694
695 struct iovec vec = { ((char *)hdr) + sizeof(ipc_msg_hdr) + datalen, 1 }; // Send the last byte along with the SCM_RIGHTS
696 struct msghdr msg;
697 struct cmsghdr *cmsg;
698 char cbuf[CMSG_SPACE(sizeof(dnssd_sock_t))];
699 msg.msg_name = 0;
700 msg.msg_namelen = 0;
701 msg.msg_iov = &vec;
702 msg.msg_iovlen = 1;
703 msg.msg_control = cbuf;
704 msg.msg_controllen = CMSG_LEN(sizeof(dnssd_sock_t));
705 msg.msg_flags = 0;
706 cmsg = CMSG_FIRSTHDR(&msg);
707 cmsg->cmsg_len = CMSG_LEN(sizeof(dnssd_sock_t));
708 cmsg->cmsg_level = SOL_SOCKET;
709 cmsg->cmsg_type = SCM_RIGHTS;
710 *((dnssd_sock_t *)CMSG_DATA(cmsg)) = listenfd;
711
712 #if TEST_KQUEUE_CONTROL_MESSAGE_BUG
713 sleep(1);
714 #endif
715
716 #if DEBUG_64BIT_SCM_RIGHTS
717 syslog(LOG_WARNING, "dnssd_clientstub sendmsg read sd=%d write sd=%d %ld %ld %ld/%ld/%ld/%ld",
718 errsd, listenfd, sizeof(dnssd_sock_t), sizeof(void*),
719 sizeof(struct cmsghdr) + sizeof(dnssd_sock_t),
720 CMSG_LEN(sizeof(dnssd_sock_t)), (long)CMSG_SPACE(sizeof(dnssd_sock_t)),
721 (long)((char*)CMSG_DATA(cmsg) + 4 - cbuf));
722 #endif DEBUG_64BIT_SCM_RIGHTS
723
724 if (sendmsg(sdr->sockfd, &msg, 0) < 0)
725 {
726 syslog(LOG_WARNING, "dnssd_clientstub ERROR: sendmsg failed read sd=%d write sd=%d errno %d (%s)",
727 errsd, listenfd, errno, strerror(errno));
728 err = kDNSServiceErr_Incompatible;
729 goto cleanup;
730 }
731
732 #if DEBUG_64BIT_SCM_RIGHTS
733 syslog(LOG_WARNING, "dnssd_clientstub sendmsg read sd=%d write sd=%d okay", errsd, listenfd);
734 #endif DEBUG_64BIT_SCM_RIGHTS
735
736 #endif
737 // Close our end of the socketpair *before* blocking in read_all to get the four-byte error code.
738 // Otherwise, if the daemon closes our socket (or crashes), we block in read_all() forever
739 // because the socket is not closed (we still have an open reference to it ourselves).
740 dnssd_close(listenfd);
741 listenfd = dnssd_InvalidSocket; // Make sure we don't close it a second time in the cleanup handling below
742 }
743
744 // At this point we may block in read_all for a few milliseconds waiting for the daemon to send us the error code,
745 // but that's okay -- the daemon is a trusted service and we know if won't take more than a few milliseconds to respond.
746 if (read_all(errsd, (char*)&err, (int)sizeof(err)) < 0)
747 err = kDNSServiceErr_ServiceNotRunning; // On failure read_all will have written a message to syslog for us
748 else
749 err = ntohl(err);
750
751 //syslog(LOG_WARNING, "dnssd_clientstub deliver_request: retrieved error code %d", err);
752
753 cleanup:
754 if (MakeSeparateReturnSocket)
755 {
756 if (dnssd_SocketValid(listenfd)) dnssd_close(listenfd);
757 if (dnssd_SocketValid(errsd)) dnssd_close(errsd);
758 #if defined(USE_NAMED_ERROR_RETURN_SOCKET)
759 // syslog(LOG_WARNING, "dnssd_clientstub deliver_request: removing UDS: %s", data);
760 if (unlink(data) != 0)
761 syslog(LOG_WARNING, "dnssd_clientstub WARNING: unlink(\"%s\") failed errno %d (%s)", data, errno, strerror(errno));
762 // else syslog(LOG_WARNING, "dnssd_clientstub deliver_request: removed UDS: %s", data);
763 #endif
764 }
765 free(hdr);
766 return err;
767 }
768
769 int DNSSD_API DNSServiceRefSockFD(DNSServiceRef sdRef)
770 {
771 if (!sdRef) { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRefSockFD called with NULL DNSServiceRef"); return dnssd_InvalidSocket; }
772
773 if (!DNSServiceRefValid(sdRef))
774 {
775 syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRefSockFD called with invalid DNSServiceRef %p %08X %08X",
776 sdRef, sdRef->sockfd, sdRef->validator);
777 return dnssd_InvalidSocket;
778 }
779
780 if (sdRef->primary)
781 {
782 syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRefSockFD undefined for kDNSServiceFlagsShareConnection subordinate DNSServiceRef %p", sdRef);
783 return dnssd_InvalidSocket;
784 }
785
786 return (int) sdRef->sockfd;
787 }
788
789 // Handle reply from server, calling application client callback. If there is no reply
790 // from the daemon on the socket contained in sdRef, the call will block.
791 DNSServiceErrorType DNSSD_API DNSServiceProcessResult(DNSServiceRef sdRef)
792 {
793 int morebytes = 0;
794
795 if (!sdRef) { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceProcessResult called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam; }
796
797 if (!DNSServiceRefValid(sdRef))
798 {
799 syslog(LOG_WARNING, "dnssd_clientstub DNSServiceProcessResult called with invalid DNSServiceRef %p %08X %08X", sdRef, sdRef->sockfd, sdRef->validator);
800 return kDNSServiceErr_BadReference;
801 }
802
803 if (sdRef->primary)
804 {
805 syslog(LOG_WARNING, "dnssd_clientstub DNSServiceProcessResult undefined for kDNSServiceFlagsShareConnection subordinate DNSServiceRef %p", sdRef);
806 return kDNSServiceErr_BadReference;
807 }
808
809 if (!sdRef->ProcessReply)
810 {
811 syslog(LOG_WARNING, "dnssd_clientstub DNSServiceProcessResult called with DNSServiceRef with no ProcessReply function");
812 return kDNSServiceErr_BadReference;
813 }
814
815 do
816 {
817 CallbackHeader cbh;
818 char *data;
819
820 // return NoError on EWOULDBLOCK. This will handle the case
821 // where a non-blocking socket is told there is data, but it was a false positive.
822 // On error, read_all will write a message to syslog for us, so don't need to duplicate that here
823 if (read_all(sdRef->sockfd, (void *)&cbh.ipc_hdr, sizeof(cbh.ipc_hdr)) < 0)
824 {
825 if (dnssd_errno() != dnssd_EWOULDBLOCK)
826 {
827 sdRef->ProcessReply = NULL;
828 return kDNSServiceErr_ServiceNotRunning;
829 }
830 else
831 {
832 if (morebytes && sdRef->logcounter < 100)
833 {
834 sdRef->logcounter++;
835 syslog(LOG_WARNING, "dnssd_clientstub DNSServiceProcessResult error: select indicated data was waiting but read_all returned EWOULDBLOCK");
836 }
837 return kDNSServiceErr_NoError;
838 }
839 }
840
841 ConvertHeaderBytes(&cbh.ipc_hdr);
842 if (cbh.ipc_hdr.version != VERSION)
843 {
844 syslog(LOG_WARNING, "dnssd_clientstub DNSServiceProcessResult daemon version %d does not match client version %d", cbh.ipc_hdr.version, VERSION);
845 sdRef->ProcessReply = NULL;
846 return kDNSServiceErr_Incompatible;
847 }
848
849 data = malloc(cbh.ipc_hdr.datalen);
850 if (!data) return kDNSServiceErr_NoMemory;
851 if (read_all(sdRef->sockfd, data, cbh.ipc_hdr.datalen) < 0) // On error, read_all will write a message to syslog for us
852 {
853 free(data);
854 sdRef->ProcessReply = NULL;
855 return kDNSServiceErr_ServiceNotRunning;
856 }
857 else
858 {
859 char *ptr = data;
860 cbh.cb_flags = get_flags (&ptr, data + cbh.ipc_hdr.datalen);
861 cbh.cb_interface = get_uint32 (&ptr, data + cbh.ipc_hdr.datalen);
862 cbh.cb_err = get_error_code(&ptr, data + cbh.ipc_hdr.datalen);
863
864 // CAUTION: We have to handle the case where the client calls DNSServiceRefDeallocate from within the callback function.
865 // To do this we set moreptr to point to morebytes. If the client does call DNSServiceRefDeallocate(),
866 // then that routine will clear morebytes for us, and cause us to exit our loop.
867 morebytes = more_bytes(sdRef->sockfd);
868 if (morebytes)
869 {
870 cbh.cb_flags |= kDNSServiceFlagsMoreComing;
871 sdRef->moreptr = &morebytes;
872 }
873 if (ptr) sdRef->ProcessReply(sdRef, &cbh, ptr, data + cbh.ipc_hdr.datalen);
874 // Careful code here:
875 // If morebytes is non-zero, that means we set sdRef->moreptr above, and the operation was not
876 // cancelled out from under us, so now we need to clear sdRef->moreptr so we don't leave a stray
877 // dangling pointer pointing to a long-gone stack variable.
878 // If morebytes is zero, then one of two thing happened:
879 // (a) morebytes was 0 above, so we didn't set sdRef->moreptr, so we don't need to clear it
880 // (b) morebytes was 1 above, and we set sdRef->moreptr, but the operation was cancelled (with DNSServiceRefDeallocate()),
881 // so we MUST NOT try to dereference our stale sdRef pointer.
882 if (morebytes) sdRef->moreptr = NULL;
883 }
884 free(data);
885 } while (morebytes);
886
887 return kDNSServiceErr_NoError;
888 }
889
890 void DNSSD_API DNSServiceRefDeallocate(DNSServiceRef sdRef)
891 {
892 if (!sdRef) { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRefDeallocate called with NULL DNSServiceRef"); return; }
893
894 if (!DNSServiceRefValid(sdRef)) // Also verifies dnssd_SocketValid(sdRef->sockfd) for us too
895 {
896 syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRefDeallocate called with invalid DNSServiceRef %p %08X %08X", sdRef, sdRef->sockfd, sdRef->validator);
897 return;
898 }
899
900 // 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
901 if (sdRef->moreptr) *(sdRef->moreptr) = 0;
902
903 if (sdRef->primary) // If this is a subordinate DNSServiceOp, just send a 'stop' command
904 {
905 DNSServiceOp **p = &sdRef->primary->next;
906 while (*p && *p != sdRef) p = &(*p)->next;
907 if (*p)
908 {
909 char *ptr;
910 size_t len = 0;
911 ipc_msg_hdr *hdr = create_hdr(cancel_request, &len, &ptr, 0, sdRef);
912 ConvertHeaderBytes(hdr);
913 write_all(sdRef->sockfd, (char *)hdr, len);
914 free(hdr);
915 *p = sdRef->next;
916 FreeDNSServiceOp(sdRef);
917 }
918 }
919 else // else, make sure to terminate all subordinates as well
920 {
921 dnssd_close(sdRef->sockfd);
922 while (sdRef)
923 {
924 DNSServiceOp *p = sdRef;
925 sdRef = sdRef->next;
926 FreeDNSServiceOp(p);
927 }
928 }
929 }
930
931 DNSServiceErrorType DNSSD_API DNSServiceGetProperty(const char *property, void *result, uint32_t *size)
932 {
933 char *ptr;
934 size_t len = strlen(property) + 1;
935 ipc_msg_hdr *hdr;
936 DNSServiceOp *tmp;
937 uint32_t actualsize;
938
939 DNSServiceErrorType err = ConnectToServer(&tmp, 0, getproperty_request, NULL, NULL, NULL);
940 if (err) return err;
941
942 hdr = create_hdr(getproperty_request, &len, &ptr, 0, tmp);
943 if (!hdr) { DNSServiceRefDeallocate(tmp); return kDNSServiceErr_NoMemory; }
944
945 put_string(property, &ptr);
946 err = deliver_request(hdr, tmp); // Will free hdr for us
947 if (read_all(tmp->sockfd, (char*)&actualsize, (int)sizeof(actualsize)) < 0)
948 { DNSServiceRefDeallocate(tmp); return kDNSServiceErr_ServiceNotRunning; }
949
950 actualsize = ntohl(actualsize);
951 if (read_all(tmp->sockfd, (char*)result, actualsize < *size ? actualsize : *size) < 0)
952 { DNSServiceRefDeallocate(tmp); return kDNSServiceErr_ServiceNotRunning; }
953 DNSServiceRefDeallocate(tmp);
954
955 // Swap version result back to local process byte order
956 if (!strcmp(property, kDNSServiceProperty_DaemonVersion) && *size >= 4)
957 *(uint32_t*)result = ntohl(*(uint32_t*)result);
958
959 *size = actualsize;
960 return kDNSServiceErr_NoError;
961 }
962
963 static void handle_resolve_response(DNSServiceOp *sdr, CallbackHeader *cbh, char *data, char *end)
964 {
965 char fullname[kDNSServiceMaxDomainName];
966 char target[kDNSServiceMaxDomainName];
967 uint16_t txtlen;
968 union { uint16_t s; u_char b[2]; } port;
969 unsigned char *txtrecord;
970
971 get_string(&data, end, fullname, kDNSServiceMaxDomainName);
972 get_string(&data, end, target, kDNSServiceMaxDomainName);
973 if (data + 2 > end) data = NULL;
974 else
975 {
976 port.b[0] = *data++;
977 port.b[1] = *data++;
978 }
979 txtlen = get_uint16(&data, end);
980 txtrecord = (unsigned char *)get_rdata(&data, end, txtlen);
981
982 if (!data) syslog(LOG_WARNING, "dnssd_clientstub handle_resolve_response: error reading result from daemon");
983 else ((DNSServiceResolveReply)sdr->AppCallback)(sdr, cbh->cb_flags, cbh->cb_interface, cbh->cb_err, fullname, target, port.s, txtlen, txtrecord, sdr->AppContext);
984 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
985 }
986
987 DNSServiceErrorType DNSSD_API DNSServiceResolve
988 (
989 DNSServiceRef *sdRef,
990 DNSServiceFlags flags,
991 uint32_t interfaceIndex,
992 const char *name,
993 const char *regtype,
994 const char *domain,
995 DNSServiceResolveReply callBack,
996 void *context
997 )
998 {
999 char *ptr;
1000 size_t len;
1001 ipc_msg_hdr *hdr;
1002 DNSServiceErrorType err;
1003
1004 if (!name || !regtype || !domain || !callBack) return kDNSServiceErr_BadParam;
1005
1006 err = ConnectToServer(sdRef, flags, resolve_request, handle_resolve_response, callBack, context);
1007 if (err) return err; // On error ConnectToServer leaves *sdRef set to NULL
1008
1009 // Calculate total message length
1010 len = sizeof(flags);
1011 len += sizeof(interfaceIndex);
1012 len += strlen(name) + 1;
1013 len += strlen(regtype) + 1;
1014 len += strlen(domain) + 1;
1015
1016 hdr = create_hdr(resolve_request, &len, &ptr, (*sdRef)->primary ? 1 : 0, *sdRef);
1017 if (!hdr) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; return kDNSServiceErr_NoMemory; }
1018
1019 put_flags(flags, &ptr);
1020 put_uint32(interfaceIndex, &ptr);
1021 put_string(name, &ptr);
1022 put_string(regtype, &ptr);
1023 put_string(domain, &ptr);
1024
1025 err = deliver_request(hdr, *sdRef); // Will free hdr for us
1026 if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
1027 return err;
1028 }
1029
1030 static void handle_query_response(DNSServiceOp *sdr, CallbackHeader *cbh, char *data, char *end)
1031 {
1032 uint32_t ttl;
1033 char name[kDNSServiceMaxDomainName];
1034 uint16_t rrtype, rrclass, rdlen;
1035 char *rdata;
1036
1037 get_string(&data, end, name, kDNSServiceMaxDomainName);
1038 rrtype = get_uint16(&data, end);
1039 rrclass = get_uint16(&data, end);
1040 rdlen = get_uint16(&data, end);
1041 rdata = get_rdata(&data, end, rdlen);
1042 ttl = get_uint32(&data, end);
1043
1044 if (!data) syslog(LOG_WARNING, "dnssd_clientstub handle_query_response: error reading result from daemon");
1045 else ((DNSServiceQueryRecordReply)sdr->AppCallback)(sdr, cbh->cb_flags, cbh->cb_interface, cbh->cb_err, name, rrtype, rrclass, rdlen, rdata, ttl, sdr->AppContext);
1046 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1047 }
1048
1049 DNSServiceErrorType DNSSD_API DNSServiceQueryRecord
1050 (
1051 DNSServiceRef *sdRef,
1052 DNSServiceFlags flags,
1053 uint32_t interfaceIndex,
1054 const char *name,
1055 uint16_t rrtype,
1056 uint16_t rrclass,
1057 DNSServiceQueryRecordReply callBack,
1058 void *context
1059 )
1060 {
1061 char *ptr;
1062 size_t len;
1063 ipc_msg_hdr *hdr;
1064 DNSServiceErrorType err = ConnectToServer(sdRef, flags, query_request, handle_query_response, callBack, context);
1065 if (err) return err; // On error ConnectToServer leaves *sdRef set to NULL
1066
1067 if (!name) name = "\0";
1068
1069 // Calculate total message length
1070 len = sizeof(flags);
1071 len += sizeof(uint32_t); // interfaceIndex
1072 len += strlen(name) + 1;
1073 len += 2 * sizeof(uint16_t); // rrtype, rrclass
1074
1075 hdr = create_hdr(query_request, &len, &ptr, (*sdRef)->primary ? 1 : 0, *sdRef);
1076 if (!hdr) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; return kDNSServiceErr_NoMemory; }
1077
1078 put_flags(flags, &ptr);
1079 put_uint32(interfaceIndex, &ptr);
1080 put_string(name, &ptr);
1081 put_uint16(rrtype, &ptr);
1082 put_uint16(rrclass, &ptr);
1083
1084 err = deliver_request(hdr, *sdRef); // Will free hdr for us
1085 if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
1086 return err;
1087 }
1088
1089 static void handle_addrinfo_response(DNSServiceOp *sdr, CallbackHeader *cbh, char *data, char *end)
1090 {
1091 char hostname[kDNSServiceMaxDomainName];
1092 uint16_t rrtype, rrclass, rdlen;
1093 char *rdata;
1094 uint32_t ttl;
1095
1096 get_string(&data, end, hostname, kDNSServiceMaxDomainName);
1097 rrtype = get_uint16(&data, end);
1098 rrclass = get_uint16(&data, end);
1099 rdlen = get_uint16(&data, end);
1100 rdata = get_rdata (&data, end, rdlen);
1101 ttl = get_uint32(&data, end);
1102
1103 // We only generate client callbacks for A and AAAA results (including NXDOMAIN results for
1104 // those types, if the client has requested those with the kDNSServiceFlagsReturnIntermediates).
1105 // Other result types, specifically CNAME referrals, are not communicated to the client, because
1106 // the DNSServiceGetAddrInfoReply interface doesn't have any meaningful way to communiate CNAME referrals.
1107 if (!data) syslog(LOG_WARNING, "dnssd_clientstub handle_addrinfo_response: error reading result from daemon");
1108 else if (rrtype == kDNSServiceType_A || rrtype == kDNSServiceType_AAAA)
1109 {
1110 struct sockaddr_in sa4;
1111 struct sockaddr_in6 sa6;
1112 const struct sockaddr *const sa = (rrtype == kDNSServiceType_A) ? (struct sockaddr*)&sa4 : (struct sockaddr*)&sa6;
1113 if (rrtype == kDNSServiceType_A)
1114 {
1115 bzero(&sa4, sizeof(sa4));
1116 #ifndef NOT_HAVE_SA_LEN
1117 sa4.sin_len = sizeof(struct sockaddr_in);
1118 #endif
1119 sa4.sin_family = AF_INET;
1120 // sin_port = 0;
1121 if (!cbh->cb_err) memcpy(&sa4.sin_addr, rdata, rdlen);
1122 }
1123 else
1124 {
1125 bzero(&sa6, sizeof(sa6));
1126 #ifndef NOT_HAVE_SA_LEN
1127 sa6.sin6_len = sizeof(struct sockaddr_in6);
1128 #endif
1129 sa6.sin6_family = AF_INET6;
1130 // sin6_port = 0;
1131 // sin6_flowinfo = 0;
1132 // sin6_scope_id = 0;
1133 if (!cbh->cb_err)
1134 {
1135 memcpy(&sa6.sin6_addr, rdata, rdlen);
1136 if (IN6_IS_ADDR_LINKLOCAL(&sa6.sin6_addr)) sa6.sin6_scope_id = cbh->cb_interface;
1137 }
1138 }
1139 ((DNSServiceGetAddrInfoReply)sdr->AppCallback)(sdr, cbh->cb_flags, cbh->cb_interface, cbh->cb_err, hostname, sa, ttl, sdr->AppContext);
1140 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1141 }
1142 }
1143
1144 DNSServiceErrorType DNSSD_API DNSServiceGetAddrInfo
1145 (
1146 DNSServiceRef *sdRef,
1147 DNSServiceFlags flags,
1148 uint32_t interfaceIndex,
1149 uint32_t protocol,
1150 const char *hostname,
1151 DNSServiceGetAddrInfoReply callBack,
1152 void *context /* may be NULL */
1153 )
1154 {
1155 char *ptr;
1156 size_t len;
1157 ipc_msg_hdr *hdr;
1158 DNSServiceErrorType err;
1159
1160 if (!hostname) return kDNSServiceErr_BadParam;
1161
1162 err = ConnectToServer(sdRef, flags, addrinfo_request, handle_addrinfo_response, callBack, context);
1163 if (err) return err; // On error ConnectToServer leaves *sdRef set to NULL
1164
1165 // Calculate total message length
1166 len = sizeof(flags);
1167 len += sizeof(uint32_t); // interfaceIndex
1168 len += sizeof(uint32_t); // protocol
1169 len += strlen(hostname) + 1;
1170
1171 hdr = create_hdr(addrinfo_request, &len, &ptr, (*sdRef)->primary ? 1 : 0, *sdRef);
1172 if (!hdr) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; return kDNSServiceErr_NoMemory; }
1173
1174 put_flags(flags, &ptr);
1175 put_uint32(interfaceIndex, &ptr);
1176 put_uint32(protocol, &ptr);
1177 put_string(hostname, &ptr);
1178
1179 err = deliver_request(hdr, *sdRef); // Will free hdr for us
1180 if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
1181 return err;
1182 }
1183
1184 static void handle_browse_response(DNSServiceOp *sdr, CallbackHeader *cbh, char *data, char *end)
1185 {
1186 char replyName[256], replyType[kDNSServiceMaxDomainName], replyDomain[kDNSServiceMaxDomainName];
1187 get_string(&data, end, replyName, 256);
1188 get_string(&data, end, replyType, kDNSServiceMaxDomainName);
1189 get_string(&data, end, replyDomain, kDNSServiceMaxDomainName);
1190 if (!data) syslog(LOG_WARNING, "dnssd_clientstub handle_browse_response: error reading result from daemon");
1191 else ((DNSServiceBrowseReply)sdr->AppCallback)(sdr, cbh->cb_flags, cbh->cb_interface, cbh->cb_err, replyName, replyType, replyDomain, sdr->AppContext);
1192 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1193 }
1194
1195 DNSServiceErrorType DNSSD_API DNSServiceBrowse
1196 (
1197 DNSServiceRef *sdRef,
1198 DNSServiceFlags flags,
1199 uint32_t interfaceIndex,
1200 const char *regtype,
1201 const char *domain,
1202 DNSServiceBrowseReply callBack,
1203 void *context
1204 )
1205 {
1206 char *ptr;
1207 size_t len;
1208 ipc_msg_hdr *hdr;
1209 DNSServiceErrorType err = ConnectToServer(sdRef, flags, browse_request, handle_browse_response, callBack, context);
1210 if (err) return err; // On error ConnectToServer leaves *sdRef set to NULL
1211
1212 if (!domain) domain = "";
1213 len = sizeof(flags);
1214 len += sizeof(interfaceIndex);
1215 len += strlen(regtype) + 1;
1216 len += strlen(domain) + 1;
1217
1218 hdr = create_hdr(browse_request, &len, &ptr, (*sdRef)->primary ? 1 : 0, *sdRef);
1219 if (!hdr) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; return kDNSServiceErr_NoMemory; }
1220
1221 put_flags(flags, &ptr);
1222 put_uint32(interfaceIndex, &ptr);
1223 put_string(regtype, &ptr);
1224 put_string(domain, &ptr);
1225
1226 err = deliver_request(hdr, *sdRef); // Will free hdr for us
1227 if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
1228 return err;
1229 }
1230
1231 DNSServiceErrorType DNSSD_API DNSServiceSetDefaultDomainForUser(DNSServiceFlags flags, const char *domain)
1232 {
1233 DNSServiceOp *tmp;
1234 char *ptr;
1235 size_t len = sizeof(flags) + strlen(domain) + 1;
1236 ipc_msg_hdr *hdr;
1237 DNSServiceErrorType err = ConnectToServer(&tmp, 0, setdomain_request, NULL, NULL, NULL);
1238 if (err) return err;
1239
1240 hdr = create_hdr(setdomain_request, &len, &ptr, 0, tmp);
1241 if (!hdr) { DNSServiceRefDeallocate(tmp); return kDNSServiceErr_NoMemory; }
1242
1243 put_flags(flags, &ptr);
1244 put_string(domain, &ptr);
1245 err = deliver_request(hdr, tmp); // Will free hdr for us
1246 DNSServiceRefDeallocate(tmp);
1247 return err;
1248 }
1249
1250 static void handle_regservice_response(DNSServiceOp *sdr, CallbackHeader *cbh, char *data, char *end)
1251 {
1252 char name[256], regtype[kDNSServiceMaxDomainName], domain[kDNSServiceMaxDomainName];
1253 get_string(&data, end, name, 256);
1254 get_string(&data, end, regtype, kDNSServiceMaxDomainName);
1255 get_string(&data, end, domain, kDNSServiceMaxDomainName);
1256 if (!data) syslog(LOG_WARNING, "dnssd_clientstub handle_regservice_response: error reading result from daemon");
1257 else ((DNSServiceRegisterReply)sdr->AppCallback)(sdr, cbh->cb_flags, cbh->cb_err, name, regtype, domain, sdr->AppContext);
1258 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1259 }
1260
1261 DNSServiceErrorType DNSSD_API DNSServiceRegister
1262 (
1263 DNSServiceRef *sdRef,
1264 DNSServiceFlags flags,
1265 uint32_t interfaceIndex,
1266 const char *name,
1267 const char *regtype,
1268 const char *domain,
1269 const char *host,
1270 uint16_t PortInNetworkByteOrder,
1271 uint16_t txtLen,
1272 const void *txtRecord,
1273 DNSServiceRegisterReply callBack,
1274 void *context
1275 )
1276 {
1277 char *ptr;
1278 size_t len;
1279 ipc_msg_hdr *hdr;
1280 DNSServiceErrorType err;
1281 union { uint16_t s; u_char b[2]; } port = { PortInNetworkByteOrder };
1282
1283 if (!name) name = "";
1284 if (!regtype) return kDNSServiceErr_BadParam;
1285 if (!domain) domain = "";
1286 if (!host) host = "";
1287 if (!txtRecord) txtRecord = (void*)"";
1288
1289 // No callback must have auto-rename
1290 if (!callBack && (flags & kDNSServiceFlagsNoAutoRename)) return kDNSServiceErr_BadParam;
1291
1292 err = ConnectToServer(sdRef, flags, reg_service_request, callBack ? handle_regservice_response : NULL, callBack, context);
1293 if (err) return err; // On error ConnectToServer leaves *sdRef set to NULL
1294
1295 len = sizeof(DNSServiceFlags);
1296 len += sizeof(uint32_t); // interfaceIndex
1297 len += strlen(name) + strlen(regtype) + strlen(domain) + strlen(host) + 4;
1298 len += 2 * sizeof(uint16_t); // port, txtLen
1299 len += txtLen;
1300
1301 hdr = create_hdr(reg_service_request, &len, &ptr, (*sdRef)->primary ? 1 : 0, *sdRef);
1302 if (!hdr) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; return kDNSServiceErr_NoMemory; }
1303 if (!callBack) hdr->ipc_flags |= IPC_FLAGS_NOREPLY;
1304
1305 put_flags(flags, &ptr);
1306 put_uint32(interfaceIndex, &ptr);
1307 put_string(name, &ptr);
1308 put_string(regtype, &ptr);
1309 put_string(domain, &ptr);
1310 put_string(host, &ptr);
1311 *ptr++ = port.b[0];
1312 *ptr++ = port.b[1];
1313 put_uint16(txtLen, &ptr);
1314 put_rdata(txtLen, txtRecord, &ptr);
1315
1316 err = deliver_request(hdr, *sdRef); // Will free hdr for us
1317 if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
1318 return err;
1319 }
1320
1321 static void handle_enumeration_response(DNSServiceOp *sdr, CallbackHeader *cbh, char *data, char *end)
1322 {
1323 char domain[kDNSServiceMaxDomainName];
1324 get_string(&data, end, domain, kDNSServiceMaxDomainName);
1325 if (!data) syslog(LOG_WARNING, "dnssd_clientstub handle_enumeration_response: error reading result from daemon");
1326 else ((DNSServiceDomainEnumReply)sdr->AppCallback)(sdr, cbh->cb_flags, cbh->cb_interface, cbh->cb_err, domain, sdr->AppContext);
1327 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1328 }
1329
1330 DNSServiceErrorType DNSSD_API DNSServiceEnumerateDomains
1331 (
1332 DNSServiceRef *sdRef,
1333 DNSServiceFlags flags,
1334 uint32_t interfaceIndex,
1335 DNSServiceDomainEnumReply callBack,
1336 void *context
1337 )
1338 {
1339 char *ptr;
1340 size_t len;
1341 ipc_msg_hdr *hdr;
1342 DNSServiceErrorType err;
1343
1344 int f1 = (flags & kDNSServiceFlagsBrowseDomains) != 0;
1345 int f2 = (flags & kDNSServiceFlagsRegistrationDomains) != 0;
1346 if (f1 + f2 != 1) return kDNSServiceErr_BadParam;
1347
1348 err = ConnectToServer(sdRef, flags, enumeration_request, handle_enumeration_response, callBack, context);
1349 if (err) return err; // On error ConnectToServer leaves *sdRef set to NULL
1350
1351 len = sizeof(DNSServiceFlags);
1352 len += sizeof(uint32_t);
1353
1354 hdr = create_hdr(enumeration_request, &len, &ptr, (*sdRef)->primary ? 1 : 0, *sdRef);
1355 if (!hdr) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; return kDNSServiceErr_NoMemory; }
1356
1357 put_flags(flags, &ptr);
1358 put_uint32(interfaceIndex, &ptr);
1359
1360 err = deliver_request(hdr, *sdRef); // Will free hdr for us
1361 if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
1362 return err;
1363 }
1364
1365 static void ConnectionResponse(DNSServiceOp *sdr, CallbackHeader *cbh, char *data, char *end)
1366 {
1367 DNSRecordRef rref = cbh->ipc_hdr.client_context.context;
1368 (void)data; // Unused
1369
1370 //printf("ConnectionResponse got %d\n", cbh->ipc_hdr.op);
1371 if (cbh->ipc_hdr.op != reg_record_reply_op)
1372 {
1373 // When using kDNSServiceFlagsShareConnection, need to search the list of associated DNSServiceOps
1374 // to find the one this response is intended for, and then call through to its ProcessReply handler
1375 while (sdr && (sdr->uid.u32[0] != cbh->ipc_hdr.client_context.u32[0] || sdr->uid.u32[1] != cbh->ipc_hdr.client_context.u32[1]))
1376 sdr = sdr->next;
1377 // NOTE: We may sometimes not find a matching DNSServiceOp, in the case where the client has
1378 // cancelled the subordinate DNSServiceOp, but there are still messages in the pipeline from the daemon
1379 if (sdr && sdr->ProcessReply) sdr->ProcessReply(sdr, cbh, data, end);
1380 // WARNING: Don't touch sdr after this -- client may have called DNSServiceRefDeallocate
1381 return;
1382 }
1383
1384 if (sdr->op == connection_request)
1385 rref->AppCallback(rref->sdr, rref, cbh->cb_flags, cbh->cb_err, rref->AppContext);
1386 else
1387 {
1388 syslog(LOG_WARNING, "dnssd_clientstub handle_regrecord_response: sdr->op != connection_request");
1389 rref->AppCallback(rref->sdr, rref, 0, kDNSServiceErr_Unknown, rref->AppContext);
1390 }
1391 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1392 }
1393
1394 DNSServiceErrorType DNSSD_API DNSServiceCreateConnection(DNSServiceRef *sdRef)
1395 {
1396 char *ptr;
1397 size_t len = 0;
1398 ipc_msg_hdr *hdr;
1399 DNSServiceErrorType err = ConnectToServer(sdRef, 0, connection_request, ConnectionResponse, NULL, NULL);
1400 if (err) return err; // On error ConnectToServer leaves *sdRef set to NULL
1401
1402 hdr = create_hdr(connection_request, &len, &ptr, 0, *sdRef);
1403 if (!hdr) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; return kDNSServiceErr_NoMemory; }
1404
1405 err = deliver_request(hdr, *sdRef); // Will free hdr for us
1406 if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
1407 return err;
1408 }
1409
1410 DNSServiceErrorType DNSSD_API DNSServiceRegisterRecord
1411 (
1412 DNSServiceRef sdRef,
1413 DNSRecordRef *RecordRef,
1414 DNSServiceFlags flags,
1415 uint32_t interfaceIndex,
1416 const char *fullname,
1417 uint16_t rrtype,
1418 uint16_t rrclass,
1419 uint16_t rdlen,
1420 const void *rdata,
1421 uint32_t ttl,
1422 DNSServiceRegisterRecordReply callBack,
1423 void *context
1424 )
1425 {
1426 char *ptr;
1427 size_t len;
1428 ipc_msg_hdr *hdr = NULL;
1429 DNSRecordRef rref = NULL;
1430 int f1 = (flags & kDNSServiceFlagsShared) != 0;
1431 int f2 = (flags & kDNSServiceFlagsUnique) != 0;
1432 if (f1 + f2 != 1) return kDNSServiceErr_BadParam;
1433
1434 if (!sdRef) { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRegisterRecord called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam; }
1435
1436 if (!DNSServiceRefValid(sdRef))
1437 {
1438 syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRegisterRecord called with invalid DNSServiceRef %p %08X %08X", sdRef, sdRef->sockfd, sdRef->validator);
1439 return kDNSServiceErr_BadReference;
1440 }
1441
1442 if (sdRef->op != connection_request)
1443 {
1444 syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRegisterRecord called with non-DNSServiceCreateConnection DNSServiceRef %p %d", sdRef, sdRef->op);
1445 return kDNSServiceErr_BadReference;
1446 }
1447
1448 *RecordRef = NULL;
1449
1450 len = sizeof(DNSServiceFlags);
1451 len += 2 * sizeof(uint32_t); // interfaceIndex, ttl
1452 len += 3 * sizeof(uint16_t); // rrtype, rrclass, rdlen
1453 len += strlen(fullname) + 1;
1454 len += rdlen;
1455
1456 hdr = create_hdr(reg_record_request, &len, &ptr, 1, sdRef);
1457 if (!hdr) return kDNSServiceErr_NoMemory;
1458
1459 put_flags(flags, &ptr);
1460 put_uint32(interfaceIndex, &ptr);
1461 put_string(fullname, &ptr);
1462 put_uint16(rrtype, &ptr);
1463 put_uint16(rrclass, &ptr);
1464 put_uint16(rdlen, &ptr);
1465 put_rdata(rdlen, rdata, &ptr);
1466 put_uint32(ttl, &ptr);
1467
1468 rref = malloc(sizeof(DNSRecord));
1469 if (!rref) { free(hdr); return kDNSServiceErr_NoMemory; }
1470 rref->AppContext = context;
1471 rref->AppCallback = callBack;
1472 rref->record_index = sdRef->max_index++;
1473 rref->sdr = sdRef;
1474 *RecordRef = rref;
1475 hdr->client_context.context = rref;
1476 hdr->reg_index = rref->record_index;
1477
1478 return deliver_request(hdr, sdRef); // Will free hdr for us
1479 }
1480
1481 // sdRef returned by DNSServiceRegister()
1482 DNSServiceErrorType DNSSD_API DNSServiceAddRecord
1483 (
1484 DNSServiceRef sdRef,
1485 DNSRecordRef *RecordRef,
1486 DNSServiceFlags flags,
1487 uint16_t rrtype,
1488 uint16_t rdlen,
1489 const void *rdata,
1490 uint32_t ttl
1491 )
1492 {
1493 ipc_msg_hdr *hdr;
1494 size_t len = 0;
1495 char *ptr;
1496 DNSRecordRef rref;
1497
1498 if (!sdRef) { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceAddRecord called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam; }
1499 if (!RecordRef) { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceAddRecord called with NULL DNSRecordRef pointer"); return kDNSServiceErr_BadParam; }
1500 if (sdRef->op != reg_service_request)
1501 {
1502 syslog(LOG_WARNING, "dnssd_clientstub DNSServiceAddRecord called with non-DNSServiceRegister DNSServiceRef %p %d", sdRef, sdRef->op);
1503 return kDNSServiceErr_BadReference;
1504 }
1505
1506 if (!DNSServiceRefValid(sdRef))
1507 {
1508 syslog(LOG_WARNING, "dnssd_clientstub DNSServiceAddRecord called with invalid DNSServiceRef %p %08X %08X", sdRef, sdRef->sockfd, sdRef->validator);
1509 return kDNSServiceErr_BadReference;
1510 }
1511
1512 *RecordRef = NULL;
1513
1514 len += 2 * sizeof(uint16_t); // rrtype, rdlen
1515 len += rdlen;
1516 len += sizeof(uint32_t);
1517 len += sizeof(DNSServiceFlags);
1518
1519 hdr = create_hdr(add_record_request, &len, &ptr, 1, sdRef);
1520 if (!hdr) return kDNSServiceErr_NoMemory;
1521 put_flags(flags, &ptr);
1522 put_uint16(rrtype, &ptr);
1523 put_uint16(rdlen, &ptr);
1524 put_rdata(rdlen, rdata, &ptr);
1525 put_uint32(ttl, &ptr);
1526
1527 rref = malloc(sizeof(DNSRecord));
1528 if (!rref) { free(hdr); return kDNSServiceErr_NoMemory; }
1529 rref->AppContext = NULL;
1530 rref->AppCallback = NULL;
1531 rref->record_index = sdRef->max_index++;
1532 rref->sdr = sdRef;
1533 *RecordRef = rref;
1534 hdr->client_context.context = rref;
1535 hdr->reg_index = rref->record_index;
1536
1537 return deliver_request(hdr, sdRef); // Will free hdr for us
1538 }
1539
1540 // DNSRecordRef returned by DNSServiceRegisterRecord or DNSServiceAddRecord
1541 DNSServiceErrorType DNSSD_API DNSServiceUpdateRecord
1542 (
1543 DNSServiceRef sdRef,
1544 DNSRecordRef RecordRef,
1545 DNSServiceFlags flags,
1546 uint16_t rdlen,
1547 const void *rdata,
1548 uint32_t ttl
1549 )
1550 {
1551 ipc_msg_hdr *hdr;
1552 size_t len = 0;
1553 char *ptr;
1554
1555 if (!sdRef) { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceUpdateRecord called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam; }
1556
1557 if (!DNSServiceRefValid(sdRef))
1558 {
1559 syslog(LOG_WARNING, "dnssd_clientstub DNSServiceUpdateRecord called with invalid DNSServiceRef %p %08X %08X", sdRef, sdRef->sockfd, sdRef->validator);
1560 return kDNSServiceErr_BadReference;
1561 }
1562
1563 // Note: RecordRef is allowed to be NULL
1564
1565 len += sizeof(uint16_t);
1566 len += rdlen;
1567 len += sizeof(uint32_t);
1568 len += sizeof(DNSServiceFlags);
1569
1570 hdr = create_hdr(update_record_request, &len, &ptr, 1, sdRef);
1571 if (!hdr) return kDNSServiceErr_NoMemory;
1572 hdr->reg_index = RecordRef ? RecordRef->record_index : TXT_RECORD_INDEX;
1573 put_flags(flags, &ptr);
1574 put_uint16(rdlen, &ptr);
1575 put_rdata(rdlen, rdata, &ptr);
1576 put_uint32(ttl, &ptr);
1577 return deliver_request(hdr, sdRef); // Will free hdr for us
1578 }
1579
1580 DNSServiceErrorType DNSSD_API DNSServiceRemoveRecord
1581 (
1582 DNSServiceRef sdRef,
1583 DNSRecordRef RecordRef,
1584 DNSServiceFlags flags
1585 )
1586 {
1587 ipc_msg_hdr *hdr;
1588 size_t len = 0;
1589 char *ptr;
1590 DNSServiceErrorType err;
1591
1592 if (!sdRef) { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRemoveRecord called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam; }
1593 if (!RecordRef) { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRemoveRecord called with NULL DNSRecordRef"); return kDNSServiceErr_BadParam; }
1594 if (!sdRef->max_index) { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRemoveRecord called with bad DNSServiceRef"); return kDNSServiceErr_BadReference; }
1595
1596 if (!DNSServiceRefValid(sdRef))
1597 {
1598 syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRemoveRecord called with invalid DNSServiceRef %p %08X %08X", sdRef, sdRef->sockfd, sdRef->validator);
1599 return kDNSServiceErr_BadReference;
1600 }
1601
1602 len += sizeof(flags);
1603 hdr = create_hdr(remove_record_request, &len, &ptr, 1, sdRef);
1604 if (!hdr) return kDNSServiceErr_NoMemory;
1605 hdr->reg_index = RecordRef->record_index;
1606 put_flags(flags, &ptr);
1607 err = deliver_request(hdr, sdRef); // Will free hdr for us
1608 if (!err) free(RecordRef);
1609 return err;
1610 }
1611
1612 DNSServiceErrorType DNSSD_API DNSServiceReconfirmRecord
1613 (
1614 DNSServiceFlags flags,
1615 uint32_t interfaceIndex,
1616 const char *fullname,
1617 uint16_t rrtype,
1618 uint16_t rrclass,
1619 uint16_t rdlen,
1620 const void *rdata
1621 )
1622 {
1623 char *ptr;
1624 size_t len;
1625 ipc_msg_hdr *hdr;
1626 DNSServiceOp *tmp;
1627
1628 DNSServiceErrorType err = ConnectToServer(&tmp, flags, reconfirm_record_request, NULL, NULL, NULL);
1629 if (err) return err;
1630
1631 len = sizeof(DNSServiceFlags);
1632 len += sizeof(uint32_t);
1633 len += strlen(fullname) + 1;
1634 len += 3 * sizeof(uint16_t);
1635 len += rdlen;
1636 hdr = create_hdr(reconfirm_record_request, &len, &ptr, 0, tmp);
1637 if (!hdr) { DNSServiceRefDeallocate(tmp); return kDNSServiceErr_NoMemory; }
1638
1639 put_flags(flags, &ptr);
1640 put_uint32(interfaceIndex, &ptr);
1641 put_string(fullname, &ptr);
1642 put_uint16(rrtype, &ptr);
1643 put_uint16(rrclass, &ptr);
1644 put_uint16(rdlen, &ptr);
1645 put_rdata(rdlen, rdata, &ptr);
1646
1647 err = deliver_request(hdr, tmp); // Will free hdr for us
1648 DNSServiceRefDeallocate(tmp);
1649 return err;
1650 }
1651
1652 static void handle_port_mapping_response(DNSServiceOp *sdr, CallbackHeader *cbh, char *data, char *end)
1653 {
1654 union { uint32_t l; u_char b[4]; } addr;
1655 uint8_t protocol = 0;
1656 union { uint16_t s; u_char b[2]; } privatePort;
1657 union { uint16_t s; u_char b[2]; } publicPort;
1658 uint32_t ttl = 0;
1659
1660 if (data + 13 > end) data = NULL;
1661 else
1662 {
1663 addr .b[0] = *data++;
1664 addr .b[1] = *data++;
1665 addr .b[2] = *data++;
1666 addr .b[3] = *data++;
1667 protocol = *data++;
1668 privatePort.b[0] = *data++;
1669 privatePort.b[1] = *data++;
1670 publicPort .b[0] = *data++;
1671 publicPort .b[1] = *data++;
1672 ttl = get_uint32(&data, end);
1673 }
1674
1675 if (!data) syslog(LOG_WARNING, "dnssd_clientstub handle_port_mapping_response: error reading result from daemon");
1676 else ((DNSServiceNATPortMappingReply)sdr->AppCallback)(sdr, cbh->cb_flags, cbh->cb_interface, cbh->cb_err, addr.l, protocol, privatePort.s, publicPort.s, ttl, sdr->AppContext);
1677 // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
1678 }
1679
1680 DNSServiceErrorType DNSSD_API DNSServiceNATPortMappingCreate
1681 (
1682 DNSServiceRef *sdRef,
1683 DNSServiceFlags flags,
1684 uint32_t interfaceIndex,
1685 uint32_t protocol, /* TCP and/or UDP */
1686 uint16_t privatePortInNetworkByteOrder,
1687 uint16_t publicPortInNetworkByteOrder,
1688 uint32_t ttl, /* time to live in seconds */
1689 DNSServiceNATPortMappingReply callBack,
1690 void *context /* may be NULL */
1691 )
1692 {
1693 char *ptr;
1694 size_t len;
1695 ipc_msg_hdr *hdr;
1696 union { uint16_t s; u_char b[2]; } privatePort = { privatePortInNetworkByteOrder };
1697 union { uint16_t s; u_char b[2]; } publicPort = { publicPortInNetworkByteOrder };
1698
1699 DNSServiceErrorType err = ConnectToServer(sdRef, flags, port_mapping_request, handle_port_mapping_response, callBack, context);
1700 if (err) return err; // On error ConnectToServer leaves *sdRef set to NULL
1701
1702 len = sizeof(flags);
1703 len += sizeof(interfaceIndex);
1704 len += sizeof(protocol);
1705 len += sizeof(privatePort);
1706 len += sizeof(publicPort);
1707 len += sizeof(ttl);
1708
1709 hdr = create_hdr(port_mapping_request, &len, &ptr, (*sdRef)->primary ? 1 : 0, *sdRef);
1710 if (!hdr) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; return kDNSServiceErr_NoMemory; }
1711
1712 put_flags(flags, &ptr);
1713 put_uint32(interfaceIndex, &ptr);
1714 put_uint32(protocol, &ptr);
1715 *ptr++ = privatePort.b[0];
1716 *ptr++ = privatePort.b[1];
1717 *ptr++ = publicPort .b[0];
1718 *ptr++ = publicPort .b[1];
1719 put_uint32(ttl, &ptr);
1720
1721 err = deliver_request(hdr, *sdRef); // Will free hdr for us
1722 if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
1723 return err;
1724 }