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