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