14b22b933Srs /* -*- Mode: C; tab-width: 4 -*-
24b22b933Srs  *
3*472cd20dSToomas Soome  * Copyright (c) 2003-2020 Apple Inc. All rights reserved.
44b22b933Srs  *
55ffb0c9bSToomas Soome  * Redistribution and use in source and binary forms, with or without
64b22b933Srs  * modification, are permitted provided that the following conditions are met:
74b22b933Srs  *
85ffb0c9bSToomas Soome  * 1.  Redistributions of source code must retain the above copyright notice,
95ffb0c9bSToomas Soome  *     this list of conditions and the following disclaimer.
105ffb0c9bSToomas Soome  * 2.  Redistributions in binary form must reproduce the above copyright notice,
115ffb0c9bSToomas Soome  *     this list of conditions and the following disclaimer in the documentation
125ffb0c9bSToomas Soome  *     and/or other materials provided with the distribution.
13cda73f64SToomas Soome  * 3.  Neither the name of Apple Inc. ("Apple") nor the names of its
145ffb0c9bSToomas Soome  *     contributors may be used to endorse or promote products derived from this
155ffb0c9bSToomas Soome  *     software without specific prior written permission.
164b22b933Srs  *
274b22b933Srs  */
294b22b933Srs #include <errno.h>
304b22b933Srs #include <stdlib.h>
313b436d06SToomas Soome #include <fcntl.h>
325ffb0c9bSToomas Soome 
33cda73f64SToomas Soome #include "dnssd_ipc.h"
34cda73f64SToomas Soome 
355ffb0c9bSToomas Soome #if APPLE_OSX_mDNSResponder
365ffb0c9bSToomas Soome #include <mach-o/dyld.h>
375ffb0c9bSToomas Soome #include <uuid/uuid.h>
385ffb0c9bSToomas Soome #include <TargetConditionals.h>
39*472cd20dSToomas Soome #include "dns_sd_private.h"
40*472cd20dSToomas Soome #include "dnssd_clientstub_apple.h"
41*472cd20dSToomas Soome #include <CoreUtils/CommonServices.h>
42*472cd20dSToomas Soome #if !defined(__i386__)
43*472cd20dSToomas Soome #define CHECK_BUNDLE_VERSION  1
44*472cd20dSToomas Soome #else
45*472cd20dSToomas Soome #define CHECK_BUNDLE_VERSION  0
46*472cd20dSToomas Soome #endif
475ffb0c9bSToomas Soome #endif
494b22b933Srs #if defined(_WIN32)
515ffb0c9bSToomas Soome     #define _SSIZE_T
525ffb0c9bSToomas Soome     #include <CommonServices.h>
535ffb0c9bSToomas Soome     #include <DebugServices.h>
545ffb0c9bSToomas Soome     #include <winsock2.h>
555ffb0c9bSToomas Soome     #include <ws2tcpip.h>
565ffb0c9bSToomas Soome     #include <windows.h>
575ffb0c9bSToomas Soome     #include <stdarg.h>
585ffb0c9bSToomas Soome     #include <stdio.h>
605ffb0c9bSToomas Soome     #define sockaddr_mdns sockaddr_in
615ffb0c9bSToomas Soome     #define AF_MDNS AF_INET
635ffb0c9bSToomas Soome // Disable warning: "'type cast' : from data pointer 'void *' to function pointer"
645ffb0c9bSToomas Soome     #pragma warning(disable:4055)
665ffb0c9bSToomas Soome // Disable warning: "nonstandard extension, function/data pointer conversion in expression"
675ffb0c9bSToomas Soome     #pragma warning(disable:4152)
694b22b933Srs extern BOOL IsSystemServiceDisabled();
715ffb0c9bSToomas Soome     #define sleep(X) Sleep((X) * 1000)
734b22b933Srs static int g_initWinsock = 0;
745ffb0c9bSToomas Soome     #define LOG_WARNING kDebugLevelWarning
755ffb0c9bSToomas Soome     #define LOG_INFO kDebugLevelInfo
syslog(int priority,const char * message,...)765ffb0c9bSToomas Soome static void syslog( int priority, const char * message, ...)
775ffb0c9bSToomas Soome {
785ffb0c9bSToomas Soome     va_list args;
795ffb0c9bSToomas Soome     int len;
805ffb0c9bSToomas Soome     char * buffer;
815ffb0c9bSToomas Soome     DWORD err = WSAGetLastError();
825ffb0c9bSToomas Soome     (void) priority;
835ffb0c9bSToomas Soome     va_start( args, message );
845ffb0c9bSToomas Soome     len = _vscprintf( message, args ) + 1;
855ffb0c9bSToomas Soome     buffer = malloc( len * sizeof(char) );
86cda73f64SToomas Soome     if ( buffer ) { vsnprintf( buffer, len, message, args ); OutputDebugString( buffer ); free( buffer ); }
875ffb0c9bSToomas Soome     WSASetLastError( err );
885ffb0c9bSToomas Soome }
894b22b933Srs #else
91*472cd20dSToomas Soome     #include <fcntl.h>      // For O_RDWR etc.
925ffb0c9bSToomas Soome     #include <sys/time.h>
935ffb0c9bSToomas Soome     #include <sys/socket.h>
945ffb0c9bSToomas Soome     #include <syslog.h>
965ffb0c9bSToomas Soome     #define sockaddr_mdns sockaddr_un
975ffb0c9bSToomas Soome     #define AF_MDNS AF_LOCAL
994b22b933Srs #endif
101*472cd20dSToomas Soome #if CHECK_BUNDLE_VERSION
102*472cd20dSToomas Soome #include "bundle_utilities.h"
103*472cd20dSToomas Soome #include <os/feature_private.h>
104*472cd20dSToomas Soome #endif
105*472cd20dSToomas Soome 
106*472cd20dSToomas Soome #if defined(_WIN32)
1075ffb0c9bSToomas Soome // <rdar://problem/4096913> Specifies how many times we'll try and connect to the server.
1094b22b933Srs #define DNSSD_CLIENT_MAXTRIES 4
110*472cd20dSToomas Soome #endif // _WIN32
1125ffb0c9bSToomas Soome // Uncomment the line below to use the old error return mechanism of creating a temporary named socket (e.g. in /var/tmp)
1135ffb0c9bSToomas Soome //#define USE_NAMED_ERROR_RETURN_SOCKET 1
1155ffb0c9bSToomas Soome // If the UDS client has not received a response from the daemon in 60 secs, it is unlikely to get one
1165ffb0c9bSToomas Soome // Note: Timeout of 3 secs should be sufficient in normal scenarios, but 60 secs is chosen as a safeguard since
1175ffb0c9bSToomas Soome // some clients may come up before mDNSResponder itself after a BOOT and on rare ocassions IOPM/Keychain/D2D calls
1185ffb0c9bSToomas Soome // in mDNSResponder's INIT may take a much longer time to return
1195ffb0c9bSToomas Soome #define DNSSD_CLIENT_TIMEOUT 60
1205ffb0c9bSToomas Soome 
1215ffb0c9bSToomas Soome #ifndef CTL_PATH_PREFIX
1225ffb0c9bSToomas Soome #define CTL_PATH_PREFIX "/var/tmp/dnssd_result_socket."
1235ffb0c9bSToomas Soome #endif
1245ffb0c9bSToomas Soome 
1255ffb0c9bSToomas Soome typedef struct
1265ffb0c9bSToomas Soome {
1275ffb0c9bSToomas Soome     ipc_msg_hdr ipc_hdr;
1285ffb0c9bSToomas Soome     DNSServiceFlags cb_flags;
1295ffb0c9bSToomas Soome     uint32_t cb_interface;
1305ffb0c9bSToomas Soome     DNSServiceErrorType cb_err;
1315ffb0c9bSToomas Soome } CallbackHeader;
1325ffb0c9bSToomas Soome 
1335ffb0c9bSToomas Soome typedef struct _DNSServiceRef_t DNSServiceOp;
1345ffb0c9bSToomas Soome typedef struct _DNSRecordRef_t DNSRecord;
1355ffb0c9bSToomas Soome 
1365ffb0c9bSToomas Soome #if !defined(_WIN32)
1375ffb0c9bSToomas Soome typedef struct
1385ffb0c9bSToomas Soome {
1395ffb0c9bSToomas Soome     void             *AppCallback;      // Client callback function and context
1405ffb0c9bSToomas Soome     void             *AppContext;
1415ffb0c9bSToomas Soome } SleepKAContext;
1425ffb0c9bSToomas Soome #endif
1435ffb0c9bSToomas Soome 
1445ffb0c9bSToomas Soome // client stub callback to process message from server and deliver results to client application
1455ffb0c9bSToomas Soome typedef void (*ProcessReplyFn)(DNSServiceOp *const sdr, const CallbackHeader *const cbh, const char *msg, const char *const end);
1465ffb0c9bSToomas Soome 
1475ffb0c9bSToomas Soome #define ValidatorBits 0x12345678
1485ffb0c9bSToomas Soome #define DNSServiceRefValid(X) (dnssd_SocketValid((X)->sockfd) && (((X)->sockfd ^ (X)->validator) == ValidatorBits))
1495ffb0c9bSToomas Soome 
1505ffb0c9bSToomas Soome // When using kDNSServiceFlagsShareConnection, there is one primary _DNSServiceOp_t, and zero or more subordinates
1515ffb0c9bSToomas Soome // For the primary, the 'next' field points to the first subordinate, and its 'next' field points to the next, and so on.
1525ffb0c9bSToomas Soome // For the primary, the 'primary' field is NULL; for subordinates the 'primary' field points back to the associated primary
1535ffb0c9bSToomas Soome //
1545ffb0c9bSToomas Soome // _DNS_SD_LIBDISPATCH is defined where libdispatch/GCD is available. This does not mean that the application will use the
1555ffb0c9bSToomas Soome // DNSServiceSetDispatchQueue API. Hence any new code guarded with _DNS_SD_LIBDISPATCH should still be backwards compatible.
1565ffb0c9bSToomas Soome struct _DNSServiceRef_t
1575ffb0c9bSToomas Soome {
1585ffb0c9bSToomas Soome     DNSServiceOp     *next;             // For shared connection
1595ffb0c9bSToomas Soome     DNSServiceOp     *primary;          // For shared connection
1605ffb0c9bSToomas Soome     dnssd_sock_t sockfd;                // Connected socket between client and daemon
1615ffb0c9bSToomas Soome     dnssd_sock_t validator;             // Used to detect memory corruption, double disposals, etc.
1625ffb0c9bSToomas Soome     client_context_t uid;               // For shared connection requests, each subordinate DNSServiceRef has its own ID,
1635ffb0c9bSToomas Soome                                         // unique within the scope of the same shared parent DNSServiceRef
1645ffb0c9bSToomas Soome     uint32_t op;                        // request_op_t or reply_op_t
1655ffb0c9bSToomas Soome     uint32_t max_index;                 // Largest assigned record index - 0 if no additional records registered
1665ffb0c9bSToomas Soome     uint32_t logcounter;                // Counter used to control number of syslog messages we write
1675ffb0c9bSToomas Soome     int              *moreptr;          // Set while DNSServiceProcessResult working on this particular DNSServiceRef
1685ffb0c9bSToomas Soome     ProcessReplyFn ProcessReply;        // Function pointer to the code to handle received messages
1695ffb0c9bSToomas Soome     void             *AppCallback;      // Client callback function and context
1705ffb0c9bSToomas Soome     void             *AppContext;
1715ffb0c9bSToomas Soome     DNSRecord        *rec;
1725ffb0c9bSToomas Soome #if _DNS_SD_LIBDISPATCH
1735ffb0c9bSToomas Soome     dispatch_source_t disp_source;
1745ffb0c9bSToomas Soome     dispatch_queue_t disp_queue;
1755ffb0c9bSToomas Soome #endif
1765ffb0c9bSToomas Soome     void             *kacontext;
1775ffb0c9bSToomas Soome };
1785ffb0c9bSToomas Soome 
1795ffb0c9bSToomas Soome struct _DNSRecordRef_t
1805ffb0c9bSToomas Soome {
1815ffb0c9bSToomas Soome     DNSRecord       *recnext;
1825ffb0c9bSToomas Soome     void *AppContext;
1835ffb0c9bSToomas Soome     DNSServiceRegisterRecordReply AppCallback;
1844b22b933Srs     DNSRecordRef recref;
1854b22b933Srs     uint32_t record_index;  // index is unique to the ServiceDiscoveryRef
1865ffb0c9bSToomas Soome     client_context_t uid;  // For demultiplexing multiple DNSServiceRegisterRecord calls
1875ffb0c9bSToomas Soome     DNSServiceOp *sdr;
1885ffb0c9bSToomas Soome };
190*472cd20dSToomas Soome #if CHECK_BUNDLE_VERSION
_should_return_noauth_error(void)191*472cd20dSToomas Soome static bool _should_return_noauth_error(void)
192*472cd20dSToomas Soome {
193*472cd20dSToomas Soome     static dispatch_once_t  s_once      = 0;
194*472cd20dSToomas Soome     static bool        s_should    = false;
195*472cd20dSToomas Soome     dispatch_once(&s_once,
196*472cd20dSToomas Soome     ^{
197*472cd20dSToomas Soome         s_should = bundle_sdk_is_ios14_or_later();
198*472cd20dSToomas Soome     });
199*472cd20dSToomas Soome     return s_should;
200*472cd20dSToomas Soome }
201*472cd20dSToomas Soome #endif
202*472cd20dSToomas Soome 
203c65ebfc7SToomas Soome #if !defined(USE_TCP_LOOPBACK)
SetUDSPath(struct sockaddr_un * saddr,const char * path)204c65ebfc7SToomas Soome static void SetUDSPath(struct sockaddr_un *saddr, const char *path)
205c65ebfc7SToomas Soome {
206c65ebfc7SToomas Soome     size_t pathLen;
207c65ebfc7SToomas Soome 
208c65ebfc7SToomas Soome     pathLen = strlen(path);
209c65ebfc7SToomas Soome     if (pathLen < sizeof(saddr->sun_path))
210c65ebfc7SToomas Soome         memcpy(saddr->sun_path, path, pathLen + 1);
211c65ebfc7SToomas Soome     else
212c65ebfc7SToomas Soome         saddr->sun_path[0] = '\0';
213c65ebfc7SToomas Soome }
214c65ebfc7SToomas Soome #endif
215c65ebfc7SToomas Soome 
216*472cd20dSToomas Soome enum { write_all_success = 0, write_all_fail = -1, write_all_defunct = -2 };
217*472cd20dSToomas Soome 
2185ffb0c9bSToomas Soome // Write len bytes. Return 0 on success, -1 on error
write_all(dnssd_sock_t sd,char * buf,size_t len)2195ffb0c9bSToomas Soome static int write_all(dnssd_sock_t sd, char *buf, size_t len)
2205ffb0c9bSToomas Soome {
2214b22b933Srs     // Don't use "MSG_WAITALL"; it returns "Invalid argument" on some Linux versions; use an explicit while() loop instead.
222*472cd20dSToomas Soome     //if (send(sd, buf, len, MSG_WAITALL) != len) return write_all_fail;
2234b22b933Srs     while (len)
2245ffb0c9bSToomas Soome     {
2255ffb0c9bSToomas Soome         ssize_t num_written = send(sd, buf, (long)len, 0);
2265ffb0c9bSToomas Soome         if (num_written < 0 || (size_t)num_written > len)
2275ffb0c9bSToomas Soome         {
228c65ebfc7SToomas Soome             // Check whether socket has gone defunct,
229c65ebfc7SToomas Soome             // otherwise, an error here indicates some OS bug
2305ffb0c9bSToomas Soome             // or that the mDNSResponder daemon crashed (which should never happen).
231c65ebfc7SToomas Soome #if !defined(__ppc__) && defined(SO_ISDEFUNCT)
232c65ebfc7SToomas Soome             int defunct = 0;
2335ffb0c9bSToomas Soome             socklen_t dlen = sizeof (defunct);
2345ffb0c9bSToomas Soome             if (getsockopt(sd, SOL_SOCKET, SO_ISDEFUNCT, &defunct, &dlen) < 0)
2355ffb0c9bSToomas Soome                 syslog(LOG_WARNING, "dnssd_clientstub write_all: SO_ISDEFUNCT failed %d %s", dnssd_errno, dnssd_strerror(dnssd_errno));
2365ffb0c9bSToomas Soome             if (!defunct)
2375ffb0c9bSToomas Soome                 syslog(LOG_WARNING, "dnssd_clientstub write_all(%d) failed %ld/%ld %d %s", sd,
2385ffb0c9bSToomas Soome                        (long)num_written, (long)len,
2395ffb0c9bSToomas Soome                        (num_written < 0) ? dnssd_errno                 : 0,
2405ffb0c9bSToomas Soome                        (num_written < 0) ? dnssd_strerror(dnssd_errno) : "");
2415ffb0c9bSToomas Soome             else
2425ffb0c9bSToomas Soome                 syslog(LOG_INFO, "dnssd_clientstub write_all(%d) DEFUNCT", sd);
243*472cd20dSToomas Soome             return defunct ? write_all_defunct : write_all_fail;
244c65ebfc7SToomas Soome #else
2455ffb0c9bSToomas Soome             syslog(LOG_WARNING, "dnssd_clientstub write_all(%d) failed %ld/%ld %d %s", sd,
2465ffb0c9bSToomas Soome                    (long)num_written, (long)len,
2475ffb0c9bSToomas Soome                    (num_written < 0) ? dnssd_errno                 : 0,
2485ffb0c9bSToomas Soome                    (num_written < 0) ? dnssd_strerror(dnssd_errno) : "");
249*472cd20dSToomas Soome             return write_all_fail;
250c65ebfc7SToomas Soome #endif
2515ffb0c9bSToomas Soome         }
2525ffb0c9bSToomas Soome         buf += num_written;
2535ffb0c9bSToomas Soome         len -= num_written;
2544b22b933Srs     }
255*472cd20dSToomas Soome     return write_all_success;
2565ffb0c9bSToomas Soome }
2575ffb0c9bSToomas Soome 
258*472cd20dSToomas Soome enum { read_all_success = 0, read_all_fail = -1, read_all_wouldblock = -2, read_all_defunct = -3 };
2605ffb0c9bSToomas Soome // Read len bytes. Return 0 on success, read_all_fail on error, or read_all_wouldblock for
read_all(dnssd_sock_t sd,char * buf,int len)2614b22b933Srs static int read_all(dnssd_sock_t sd, char *buf, int len)
2625ffb0c9bSToomas Soome {
2634b22b933Srs     // Don't use "MSG_WAITALL"; it returns "Invalid argument" on some Linux versions; use an explicit while() loop instead.
2645ffb0c9bSToomas Soome     //if (recv(sd, buf, len, MSG_WAITALL) != len) return -1;
2655ffb0c9bSToomas Soome 
2664b22b933Srs     while (len)
2675ffb0c9bSToomas Soome     {
2685ffb0c9bSToomas Soome         ssize_t num_read = recv(sd, buf, len, 0);
2695ffb0c9bSToomas Soome         // It is valid to get an interrupted system call error e.g., somebody attaching
2705ffb0c9bSToomas Soome         // in a debugger, retry without failing
271c65ebfc7SToomas Soome         if ((num_read < 0) && (errno == EINTR))
272c65ebfc7SToomas Soome         {
273c65ebfc7SToomas Soome             syslog(LOG_INFO, "dnssd_clientstub read_all: EINTR continue");
274c65ebfc7SToomas Soome             continue;
2755ffb0c9bSToomas Soome         }
2765ffb0c9bSToomas Soome         if ((num_read == 0) || (num_read < 0) || (num_read > len))
2775ffb0c9bSToomas Soome         {
2785ffb0c9bSToomas Soome             int printWarn = 0;
2795ffb0c9bSToomas Soome             int defunct = 0;
280c65ebfc7SToomas Soome 
281c65ebfc7SToomas Soome             // Check whether socket has gone defunct,
282c65ebfc7SToomas Soome             // otherwise, an error here indicates some OS bug
2835ffb0c9bSToomas Soome             // or that the mDNSResponder daemon crashed (which should never happen).
2845ffb0c9bSToomas Soome #if defined(WIN32)
2855ffb0c9bSToomas Soome             // <rdar://problem/7481776> Suppress logs for "A non-blocking socket operation
2865ffb0c9bSToomas Soome             //                          could not be completed immediately"
2875ffb0c9bSToomas Soome             if (WSAGetLastError() != WSAEWOULDBLOCK)
2885ffb0c9bSToomas Soome                 printWarn = 1;
2895ffb0c9bSToomas Soome #endif
2905ffb0c9bSToomas Soome #if !defined(__ppc__) && defined(SO_ISDEFUNCT)
2915ffb0c9bSToomas Soome             {
2925ffb0c9bSToomas Soome                 socklen_t dlen = sizeof (defunct);
2935ffb0c9bSToomas Soome                 if (getsockopt(sd, SOL_SOCKET, SO_ISDEFUNCT, &defunct, &dlen) < 0)
2945ffb0c9bSToomas Soome                     syslog(LOG_WARNING, "dnssd_clientstub read_all: SO_ISDEFUNCT failed %d %s", dnssd_errno, dnssd_strerror(dnssd_errno));
2955ffb0c9bSToomas Soome             }
2965ffb0c9bSToomas Soome             if (!defunct)
2975ffb0c9bSToomas Soome                 printWarn = 1;
2985ffb0c9bSToomas Soome #endif
2995ffb0c9bSToomas Soome             if (printWarn)
3005ffb0c9bSToomas Soome                 syslog(LOG_WARNING, "dnssd_clientstub read_all(%d) failed %ld/%ld %d %s", sd,
3015ffb0c9bSToomas Soome                        (long)num_read, (long)len,
3025ffb0c9bSToomas Soome                        (num_read < 0) ? dnssd_errno                 : 0,
3035ffb0c9bSToomas Soome                        (num_read < 0) ? dnssd_strerror(dnssd_errno) : "");
3045ffb0c9bSToomas Soome             else if (defunct)
3055ffb0c9bSToomas Soome                 syslog(LOG_INFO, "dnssd_clientstub read_all(%d) DEFUNCT", sd);
306*472cd20dSToomas Soome             return (num_read < 0 && dnssd_errno == dnssd_EWOULDBLOCK) ? read_all_wouldblock : (defunct ? read_all_defunct : read_all_fail);
3075ffb0c9bSToomas Soome         }
3085ffb0c9bSToomas Soome         buf += num_read;
3095ffb0c9bSToomas Soome         len -= num_read;
3104b22b933Srs     }
3115ffb0c9bSToomas Soome     return read_all_success;
3125ffb0c9bSToomas Soome }
3135ffb0c9bSToomas Soome 
3145ffb0c9bSToomas Soome // Returns 1 if more bytes remain to be read on socket descriptor sd, 0 otherwise
more_bytes(dnssd_sock_t sd)3155ffb0c9bSToomas Soome static int more_bytes(dnssd_sock_t sd)
3165ffb0c9bSToomas Soome {
3175ffb0c9bSToomas Soome     struct timeval tv = { 0, 0 };
3185ffb0c9bSToomas Soome     fd_set readfds;
3195ffb0c9bSToomas Soome     fd_set *fs;
3205ffb0c9bSToomas Soome     int ret;
3215ffb0c9bSToomas Soome 
322c65ebfc7SToomas Soome #if defined(_WIN32)
323c65ebfc7SToomas Soome     fs = &readfds;
324c65ebfc7SToomas Soome     FD_ZERO(fs);
325c65ebfc7SToomas Soome     FD_SET(sd, fs);
326c65ebfc7SToomas Soome     ret = select((int)sd+1, fs, (fd_set*)NULL, (fd_set*)NULL, &tv);
327c65ebfc7SToomas Soome #else
328*472cd20dSToomas Soome     // This whole thing would probably be better done using kevent() instead of select()
3295ffb0c9bSToomas Soome     if (sd < FD_SETSIZE)
3305ffb0c9bSToomas Soome     {
3315ffb0c9bSToomas Soome         fs = &readfds;
3325ffb0c9bSToomas Soome         FD_ZERO(fs);
3335ffb0c9bSToomas Soome     }
3345ffb0c9bSToomas Soome     else
3355ffb0c9bSToomas Soome     {
3365ffb0c9bSToomas Soome         // Compute the number of integers needed for storing "sd". Internally fd_set is stored
3375ffb0c9bSToomas Soome         // as an array of ints with one bit for each fd and hence we need to compute
3385ffb0c9bSToomas Soome         // the number of ints needed rather than the number of bytes. If "sd" is 32, we need
3395ffb0c9bSToomas Soome         // two ints and not just one.
3405ffb0c9bSToomas Soome         int nfdbits = sizeof (int) * 8;
3415ffb0c9bSToomas Soome         int nints = (sd/nfdbits) + 1;
342cda73f64SToomas Soome         fs = (fd_set *)calloc(nints, (size_t)sizeof(int));
343c65ebfc7SToomas Soome         if (fs == NULL)
344c65ebfc7SToomas Soome         {
345c65ebfc7SToomas Soome             syslog(LOG_WARNING, "dnssd_clientstub more_bytes: malloc failed");
346c65ebfc7SToomas Soome             return 0;
3475ffb0c9bSToomas Soome         }
3485ffb0c9bSToomas Soome     }
3495ffb0c9bSToomas Soome     FD_SET(sd, fs);
3505ffb0c9bSToomas Soome     ret = select((int)sd+1, fs, (fd_set*)NULL, (fd_set*)NULL, &tv);
351c65ebfc7SToomas Soome     if (fs != &readfds)
3525ffb0c9bSToomas Soome         free(fs);
353c65ebfc7SToomas Soome #endif
3545ffb0c9bSToomas Soome     return (ret > 0);
3555ffb0c9bSToomas Soome }
3565ffb0c9bSToomas Soome 
3575ffb0c9bSToomas Soome // set_waitlimit() implements a timeout using select. It is called from deliver_request() before recv() OR accept()
3585ffb0c9bSToomas Soome // to ensure the UDS clients are not blocked in these system calls indefinitely.
3595ffb0c9bSToomas Soome // Note: Ideally one should never be blocked here, because it indicates either mDNSResponder daemon is not yet up/hung/
360c65ebfc7SToomas Soome // superbusy/crashed or some other OS bug. For eg: On Windows which suffers from 3rd party software
361c65ebfc7SToomas Soome // (primarily 3rd party firewall software) interfering with proper functioning of the TCP protocol stack it is possible
3625ffb0c9bSToomas Soome // the next operation on this socket(recv/accept) is blocked since we depend on TCP to communicate with the system service.
set_waitlimit(dnssd_sock_t sock,int timeout)3635ffb0c9bSToomas Soome static int set_waitlimit(dnssd_sock_t sock, int timeout)
3645ffb0c9bSToomas Soome {
3655ffb0c9bSToomas Soome     int gDaemonErr = kDNSServiceErr_NoError;
3665ffb0c9bSToomas Soome 
367*472cd20dSToomas Soome     // The comment below is wrong. The select() routine does not cause stack corruption.
368*472cd20dSToomas Soome     // The use of FD_SET out of range for the bitmap is what causes stack corruption.
369*472cd20dSToomas Soome     // For how to do this correctly, see the example using calloc() in more_bytes() above.
370*472cd20dSToomas Soome     // Even better, both should be changed to use kevent() instead of select().
3715ffb0c9bSToomas Soome     // To prevent stack corruption since select does not work with timeout if fds > FD_SETSIZE(1024)
3725ffb0c9bSToomas Soome     if (!gDaemonErr && sock < FD_SETSIZE)
3735ffb0c9bSToomas Soome     {
3745ffb0c9bSToomas Soome         struct timeval tv;
3755ffb0c9bSToomas Soome         fd_set set;
3765ffb0c9bSToomas Soome 
3775ffb0c9bSToomas Soome         FD_ZERO(&set);
3785ffb0c9bSToomas Soome         FD_SET(sock, &set);
3795ffb0c9bSToomas Soome         tv.tv_sec = timeout;
3805ffb0c9bSToomas Soome         tv.tv_usec = 0;
3815ffb0c9bSToomas Soome         if (!select((int)(sock + 1), &set, NULL, NULL, &tv))
3825ffb0c9bSToomas Soome         {
3835ffb0c9bSToomas Soome             // Ideally one should never hit this case: See comments before set_waitlimit()
3845ffb0c9bSToomas Soome             syslog(LOG_WARNING, "dnssd_clientstub set_waitlimit:_daemon timed out (%d secs) without any response: Socket %d", timeout, sock);
3855ffb0c9bSToomas Soome             gDaemonErr = kDNSServiceErr_Timeout;
3865ffb0c9bSToomas Soome         }
3875ffb0c9bSToomas Soome     }
3885ffb0c9bSToomas Soome     return gDaemonErr;
3895ffb0c9bSToomas Soome }
3914b22b933Srs /* create_hdr
3924b22b933Srs  *
3935ffb0c9bSToomas Soome  * allocate and initialize an ipc message header. Value of len should initially be the
3945ffb0c9bSToomas Soome  * length of the data, and is set to the value of the data plus the header. data_start
3955ffb0c9bSToomas Soome  * is set to point to the beginning of the data section. SeparateReturnSocket should be
3965ffb0c9bSToomas Soome  * non-zero for calls that can't receive an immediate error return value on their primary
3975ffb0c9bSToomas Soome  * socket, and therefore require a separate return path for the error code result.
3984b22b933Srs  * if zero, the path to a control socket is appended at the beginning of the message buffer.
3994b22b933Srs  * data_start is set past this string.
4004b22b933Srs  */
create_hdr(uint32_t op,size_t * len,char ** data_start,int SeparateReturnSocket,DNSServiceOp * ref)4015ffb0c9bSToomas Soome static ipc_msg_hdr *create_hdr(uint32_t op, size_t *len, char **data_start, int SeparateReturnSocket, DNSServiceOp *ref)
4025ffb0c9bSToomas Soome {
4034b22b933Srs     char *msg = NULL;
4044b22b933Srs     ipc_msg_hdr *hdr;
4054b22b933Srs     int datalen;
4064b22b933Srs #if !defined(USE_TCP_LOOPBACK)
4075ffb0c9bSToomas Soome     char ctrl_path[64] = "";    // "/var/tmp/dnssd_result_socket.xxxxxxxxxx-xxx-xxxxxx"
4084b22b933Srs #endif
4105ffb0c9bSToomas Soome     if (SeparateReturnSocket)
4115ffb0c9bSToomas Soome     {
4124b22b933Srs #if defined(USE_TCP_LOOPBACK)
4135ffb0c9bSToomas Soome         *len += 2;  // Allocate space for two-byte port number
4145ffb0c9bSToomas Soome #elif defined(USE_NAMED_ERROR_RETURN_SOCKET)
4155ffb0c9bSToomas Soome         struct timeval tv;
4165ffb0c9bSToomas Soome         if (gettimeofday(&tv, NULL) < 0)
4175ffb0c9bSToomas Soome         { syslog(LOG_WARNING, "dnssd_clientstub create_hdr: gettimeofday failed %d %s", dnssd_errno, dnssd_strerror(dnssd_errno)); return NULL; }
418cda73f64SToomas Soome         snprintf(ctrl_path, sizeof(ctrl_path), "%s%d-%.3lx-%.6lu", CTL_PATH_PREFIX, (int)getpid(),
4195ffb0c9bSToomas Soome                 (unsigned long)(tv.tv_sec & 0xFFF), (unsigned long)(tv.tv_usec));
4204b22b933Srs         *len += strlen(ctrl_path) + 1;
4215ffb0c9bSToomas Soome #else
4225ffb0c9bSToomas Soome         *len += 1;      // Allocate space for single zero byte (empty C string)
4234b22b933Srs #endif
4245ffb0c9bSToomas Soome     }
4264b22b933Srs     datalen = (int) *len;
4274b22b933Srs     *len += sizeof(ipc_msg_hdr);
4295ffb0c9bSToomas Soome     // Write message to buffer
4304b22b933Srs     msg = malloc(*len);
4315ffb0c9bSToomas Soome     if (!msg) { syslog(LOG_WARNING, "dnssd_clientstub create_hdr: malloc failed"); return NULL; }
4325ffb0c9bSToomas Soome 
4335ffb0c9bSToomas Soome     memset(msg, 0, *len);
4345ffb0c9bSToomas Soome     hdr = (ipc_msg_hdr *)msg;
4355ffb0c9bSToomas Soome     hdr->version                = VERSION;
4365ffb0c9bSToomas Soome     hdr->datalen                = datalen;
4375ffb0c9bSToomas Soome     hdr->ipc_flags              = 0;
4385ffb0c9bSToomas Soome     hdr->op                     = op;
4395ffb0c9bSToomas Soome     hdr->client_context         = ref->uid;
4405ffb0c9bSToomas Soome     hdr->reg_index              = 0;
4414b22b933Srs     *data_start = msg + sizeof(ipc_msg_hdr);
4424b22b933Srs #if defined(USE_TCP_LOOPBACK)
4435ffb0c9bSToomas Soome     // Put dummy data in for the port, since we don't know what it is yet.
4445ffb0c9bSToomas Soome     // The data will get filled in before we send the message. This happens in deliver_request().
4455ffb0c9bSToomas Soome     if (SeparateReturnSocket) put_uint16(0, data_start);
4464b22b933Srs #else
4475ffb0c9bSToomas Soome     if (SeparateReturnSocket) put_string(ctrl_path, data_start);
4484b22b933Srs #endif
4494b22b933Srs     return hdr;
4505ffb0c9bSToomas Soome }
FreeDNSRecords(DNSServiceOp * sdRef)4525ffb0c9bSToomas Soome static void FreeDNSRecords(DNSServiceOp *sdRef)
4535ffb0c9bSToomas Soome {
4545ffb0c9bSToomas Soome     DNSRecord *rec = sdRef->rec;
4555ffb0c9bSToomas Soome     while (rec)
4564b22b933Srs     {
4575ffb0c9bSToomas Soome         DNSRecord *next = rec->recnext;
4585ffb0c9bSToomas Soome         free(rec);
4595ffb0c9bSToomas Soome         rec = next;
4605ffb0c9bSToomas Soome     }
4615ffb0c9bSToomas Soome }
FreeDNSServiceOp(DNSServiceOp * x)4635ffb0c9bSToomas Soome static void FreeDNSServiceOp(DNSServiceOp *x)
4645ffb0c9bSToomas Soome {
4655ffb0c9bSToomas Soome     // We don't use our DNSServiceRefValid macro here because if we're cleaning up after a socket() call failed
4665ffb0c9bSToomas Soome     // then sockfd could legitimately contain a failing value (e.g. dnssd_InvalidSocket)
4675ffb0c9bSToomas Soome     if ((x->sockfd ^ x->validator) != ValidatorBits)
468cda73f64SToomas Soome     {
469cda73f64SToomas Soome     }
4705ffb0c9bSToomas Soome     else
4715ffb0c9bSToomas Soome     {
4725ffb0c9bSToomas Soome         x->next         = NULL;
4735ffb0c9bSToomas Soome         x->primary      = NULL;
4745ffb0c9bSToomas Soome         x->sockfd       = dnssd_InvalidSocket;
4755ffb0c9bSToomas Soome         x->validator    = 0xDDDDDDDD;
4765ffb0c9bSToomas Soome         x->op           = request_op_none;
4775ffb0c9bSToomas Soome         x->max_index    = 0;
4785ffb0c9bSToomas Soome         x->logcounter   = 0;
4795ffb0c9bSToomas Soome         x->moreptr      = NULL;
4805ffb0c9bSToomas Soome         x->ProcessReply = NULL;
4815ffb0c9bSToomas Soome         x->AppCallback  = NULL;
4825ffb0c9bSToomas Soome         x->AppContext   = NULL;
4835ffb0c9bSToomas Soome #if _DNS_SD_LIBDISPATCH
4845ffb0c9bSToomas Soome         if (x->disp_source) dispatch_release(x->disp_source);
4855ffb0c9bSToomas Soome         x->disp_source  = NULL;
4865ffb0c9bSToomas Soome         x->disp_queue   = NULL;
4875ffb0c9bSToomas Soome #endif
4885ffb0c9bSToomas Soome         // DNSRecords may have been added to subordinate sdRef e.g., DNSServiceRegister/DNSServiceAddRecord
489c65ebfc7SToomas Soome         // or on the main sdRef e.g., DNSServiceCreateConnection/DNSServiceRegisterRecord.
490c65ebfc7SToomas Soome         // DNSRecords may have been freed if the application called DNSRemoveRecord.
4915ffb0c9bSToomas Soome         FreeDNSRecords(x);
4925ffb0c9bSToomas Soome         if (x->kacontext)
4935ffb0c9bSToomas Soome         {
4945ffb0c9bSToomas Soome             free(x->kacontext);
4955ffb0c9bSToomas Soome             x->kacontext = NULL;
4965ffb0c9bSToomas Soome         }
4975ffb0c9bSToomas Soome         free(x);
4985ffb0c9bSToomas Soome     }
4995ffb0c9bSToomas Soome }
5015ffb0c9bSToomas Soome // Return a connected service ref (deallocate with DNSServiceRefDeallocate)
ConnectToServer(DNSServiceRef * ref,DNSServiceFlags flags,uint32_t op,ProcessReplyFn ProcessReply,void * AppCallback,void * AppContext)5025ffb0c9bSToomas Soome static DNSServiceErrorType ConnectToServer(DNSServiceRef *ref, DNSServiceFlags flags, uint32_t op, ProcessReplyFn ProcessReply, void *AppCallback, void *AppContext)
5035ffb0c9bSToomas Soome {
504*472cd20dSToomas Soome     #if defined(_WIN32)
5055ffb0c9bSToomas Soome     int NumTries = 0;
506*472cd20dSToomas Soome     #endif // _WIN32
5085ffb0c9bSToomas Soome     dnssd_sockaddr_t saddr;
5095ffb0c9bSToomas Soome     DNSServiceOp *sdr;
511c65ebfc7SToomas Soome     if (!ref)
512c65ebfc7SToomas Soome     {
513c65ebfc7SToomas Soome         syslog(LOG_WARNING, "dnssd_clientstub DNSService operation with NULL DNSServiceRef");
514c65ebfc7SToomas Soome         return kDNSServiceErr_BadParam;
5155ffb0c9bSToomas Soome     }
5175ffb0c9bSToomas Soome     if (flags & kDNSServiceFlagsShareConnection)
5185ffb0c9bSToomas Soome     {
5195ffb0c9bSToomas Soome         if (!*ref)
5205ffb0c9bSToomas Soome         {
5215ffb0c9bSToomas Soome             syslog(LOG_WARNING, "dnssd_clientstub kDNSServiceFlagsShareConnection used with NULL DNSServiceRef");
5225ffb0c9bSToomas Soome             return kDNSServiceErr_BadParam;
5235ffb0c9bSToomas Soome         }
5245ffb0c9bSToomas Soome         if (!DNSServiceRefValid(*ref) || ((*ref)->op != connection_request && (*ref)->op != connection_delegate_request) || (*ref)->primary)
5255ffb0c9bSToomas Soome         {
5265ffb0c9bSToomas Soome             syslog(LOG_WARNING, "dnssd_clientstub kDNSServiceFlagsShareConnection used with invalid DNSServiceRef %p %08X %08X op %d",
5275ffb0c9bSToomas Soome                    (*ref), (*ref)->sockfd, (*ref)->validator, (*ref)->op);
5285ffb0c9bSToomas Soome             *ref = NULL;
5295ffb0c9bSToomas Soome             return kDNSServiceErr_BadReference;
5305ffb0c9bSToomas Soome         }
5315ffb0c9bSToomas Soome     }
5335ffb0c9bSToomas Soome     #if defined(_WIN32)
5345ffb0c9bSToomas Soome     if (!g_initWinsock)
5355ffb0c9bSToomas Soome     {
5365ffb0c9bSToomas Soome         WSADATA wsaData;
5375ffb0c9bSToomas Soome         g_initWinsock = 1;
5385ffb0c9bSToomas Soome         if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) { *ref = NULL; return kDNSServiceErr_ServiceNotRunning; }
5395ffb0c9bSToomas Soome     }
5405ffb0c9bSToomas Soome     // <rdar://problem/4096913> If the system service is disabled, we only want to try to connect once
541c65ebfc7SToomas Soome     if (IsSystemServiceDisabled())
5425ffb0c9bSToomas Soome         NumTries = DNSSD_CLIENT_MAXTRIES;
5435ffb0c9bSToomas Soome     #endif
5445ffb0c9bSToomas Soome 
5455ffb0c9bSToomas Soome     sdr = malloc(sizeof(DNSServiceOp));
546c65ebfc7SToomas Soome     if (!sdr)
547c65ebfc7SToomas Soome     {
548c65ebfc7SToomas Soome         syslog(LOG_WARNING, "dnssd_clientstub ConnectToServer: malloc failed");
549c65ebfc7SToomas Soome         *ref = NULL;
550c65ebfc7SToomas Soome         return kDNSServiceErr_NoMemory;
5515ffb0c9bSToomas Soome     }
5525ffb0c9bSToomas Soome     sdr->next          = NULL;
5535ffb0c9bSToomas Soome     sdr->primary       = NULL;
5545ffb0c9bSToomas Soome     sdr->sockfd        = dnssd_InvalidSocket;
5555ffb0c9bSToomas Soome     sdr->validator     = sdr->sockfd ^ ValidatorBits;
5565ffb0c9bSToomas Soome     sdr->op            = op;
5575ffb0c9bSToomas Soome     sdr->max_index     = 0;
5585ffb0c9bSToomas Soome     sdr->logcounter    = 0;
5595ffb0c9bSToomas Soome     sdr->moreptr       = NULL;
5605ffb0c9bSToomas Soome     sdr->uid.u32[0]    = 0;
5615ffb0c9bSToomas Soome     sdr->uid.u32[1]    = 0;
5625ffb0c9bSToomas Soome     sdr->ProcessReply  = ProcessReply;
5635ffb0c9bSToomas Soome     sdr->AppCallback   = AppCallback;
5645ffb0c9bSToomas Soome     sdr->AppContext    = AppContext;
5655ffb0c9bSToomas Soome     sdr->rec           = NULL;
5665ffb0c9bSToomas Soome #if _DNS_SD_LIBDISPATCH
5675ffb0c9bSToomas Soome     sdr->disp_source   = NULL;
5685ffb0c9bSToomas Soome     sdr->disp_queue    = NULL;
5694b22b933Srs #endif
5705ffb0c9bSToomas Soome     sdr->kacontext     = NULL;
571*472cd20dSToomas Soome 
5725ffb0c9bSToomas Soome     if (flags & kDNSServiceFlagsShareConnection)
5734b22b933Srs     {
5745ffb0c9bSToomas Soome         DNSServiceOp **p = &(*ref)->next;       // Append ourselves to end of primary's list
575c65ebfc7SToomas Soome         while (*p)
5765ffb0c9bSToomas Soome             p = &(*p)->next;
5775ffb0c9bSToomas Soome         *p = sdr;
5785ffb0c9bSToomas Soome         // Preincrement counter before we use it -- it helps with debugging if we know the all-zeroes ID should never appear
579c65ebfc7SToomas Soome         if (++(*ref)->uid.u32[0] == 0)
5805ffb0c9bSToomas Soome             ++(*ref)->uid.u32[1];               // In parent DNSServiceOp increment UID counter
5815ffb0c9bSToomas Soome         sdr->primary    = *ref;                 // Set our primary pointer
5825ffb0c9bSToomas Soome         sdr->sockfd     = (*ref)->sockfd;       // Inherit primary's socket
5835ffb0c9bSToomas Soome         sdr->validator  = (*ref)->validator;
5845ffb0c9bSToomas Soome         sdr->uid        = (*ref)->uid;
5855ffb0c9bSToomas Soome         //printf("ConnectToServer sharing socket %d\n", sdr->sockfd);
5865ffb0c9bSToomas Soome     }
5875ffb0c9bSToomas Soome     else
5885ffb0c9bSToomas Soome     {
5895ffb0c9bSToomas Soome         #ifdef SO_NOSIGPIPE
5905ffb0c9bSToomas Soome         const unsigned long optval = 1;
5915ffb0c9bSToomas Soome         #endif
5925ffb0c9bSToomas Soome         #ifndef USE_TCP_LOOPBACK
5935ffb0c9bSToomas Soome         char* uds_serverpath = getenv(MDNS_UDS_SERVERPATH_ENVVAR);
5945ffb0c9bSToomas Soome         if (uds_serverpath == NULL)
5955ffb0c9bSToomas Soome             uds_serverpath = MDNS_UDS_SERVERPATH;
596cda73f64SToomas Soome         else if (strlen(uds_serverpath) >= MAX_CTLPATH)
597cda73f64SToomas Soome         {
598cda73f64SToomas Soome             uds_serverpath = MDNS_UDS_SERVERPATH;
599cda73f64SToomas Soome             syslog(LOG_WARNING, "dnssd_clientstub ConnectToServer: using default path since env len is invalid");
600cda73f64SToomas Soome         }
6015ffb0c9bSToomas Soome         #endif
6025ffb0c9bSToomas Soome         *ref = NULL;
6035ffb0c9bSToomas Soome         sdr->sockfd    = socket(AF_DNSSD, SOCK_STREAM, 0);
6045ffb0c9bSToomas Soome         sdr->validator = sdr->sockfd ^ ValidatorBits;
6055ffb0c9bSToomas Soome         if (!dnssd_SocketValid(sdr->sockfd))
6065ffb0c9bSToomas Soome         {
6075ffb0c9bSToomas Soome             syslog(LOG_WARNING, "dnssd_clientstub ConnectToServer: socket failed %d %s", dnssd_errno, dnssd_strerror(dnssd_errno));
6085ffb0c9bSToomas Soome             FreeDNSServiceOp(sdr);
6095ffb0c9bSToomas Soome             return kDNSServiceErr_NoMemory;
6105ffb0c9bSToomas Soome         }
611*472cd20dSToomas Soome #if !defined(_WIN32)
612*472cd20dSToomas Soome         int fcntl_flags = fcntl(sdr->sockfd, F_GETFD);
613*472cd20dSToomas Soome         if (fcntl_flags != -1)
614*472cd20dSToomas Soome         {
615*472cd20dSToomas Soome             fcntl_flags |= FD_CLOEXEC;
616*472cd20dSToomas Soome             int ret = fcntl(sdr->sockfd, F_SETFD, fcntl_flags);
617*472cd20dSToomas Soome             if (ret == -1)
618*472cd20dSToomas Soome                 syslog(LOG_WARNING, "dnssd_clientstub ConnectToServer: Failed to set FD_CLOEXEC on socket %d %s",
619*472cd20dSToomas Soome                        dnssd_errno, dnssd_strerror(dnssd_errno));
620*472cd20dSToomas Soome         }
621*472cd20dSToomas Soome         else
622*472cd20dSToomas Soome         {
623*472cd20dSToomas Soome             syslog(LOG_WARNING, "dnssd_clientstub ConnectToServer: Failed to get the file descriptor flags of socket %d %s",
624*472cd20dSToomas Soome                    dnssd_errno, dnssd_strerror(dnssd_errno));
625*472cd20dSToomas Soome         }
626*472cd20dSToomas Soome #endif // !defined(_WIN32)
6275ffb0c9bSToomas Soome         #ifdef SO_NOSIGPIPE
6285ffb0c9bSToomas Soome         // Some environments (e.g. OS X) support turning off SIGPIPE for a socket
6295ffb0c9bSToomas Soome         if (setsockopt(sdr->sockfd, SOL_SOCKET, SO_NOSIGPIPE, &optval, sizeof(optval)) < 0)
6305ffb0c9bSToomas Soome             syslog(LOG_WARNING, "dnssd_clientstub ConnectToServer: SO_NOSIGPIPE failed %d %s", dnssd_errno, dnssd_strerror(dnssd_errno));
6315ffb0c9bSToomas Soome         #endif
6325ffb0c9bSToomas Soome         #if defined(USE_TCP_LOOPBACK)
6335ffb0c9bSToomas Soome         saddr.sin_family      = AF_INET;
6345ffb0c9bSToomas Soome         saddr.sin_addr.s_addr = inet_addr(MDNS_TCP_SERVERADDR);
6355ffb0c9bSToomas Soome         saddr.sin_port        = htons(MDNS_TCP_SERVERPORT);
6365ffb0c9bSToomas Soome         #else
6375ffb0c9bSToomas Soome         saddr.sun_family      = AF_LOCAL;
638c65ebfc7SToomas Soome         SetUDSPath(&saddr, uds_serverpath);
6395ffb0c9bSToomas Soome         #if !defined(__ppc__) && defined(SO_DEFUNCTOK)
6405ffb0c9bSToomas Soome         {
6415ffb0c9bSToomas Soome             int defunct = 1;
6425ffb0c9bSToomas Soome             if (setsockopt(sdr->sockfd, SOL_SOCKET, SO_DEFUNCTOK, &defunct, sizeof(defunct)) < 0)
6435ffb0c9bSToomas Soome                 syslog(LOG_WARNING, "dnssd_clientstub ConnectToServer: SO_DEFUNCTOK failed %d %s", dnssd_errno, dnssd_strerror(dnssd_errno));
6445ffb0c9bSToomas Soome         }
6455ffb0c9bSToomas Soome         #endif
6465ffb0c9bSToomas Soome         #endif
647c65ebfc7SToomas Soome 
648*472cd20dSToomas Soome         #if defined(_WIN32)
6495ffb0c9bSToomas Soome         while (1)
6505ffb0c9bSToomas Soome         {
6515ffb0c9bSToomas Soome             int err = connect(sdr->sockfd, (struct sockaddr *) &saddr, sizeof(saddr));
6525ffb0c9bSToomas Soome             if (!err)
6535ffb0c9bSToomas Soome                 break; // If we succeeded, return sdr
654*472cd20dSToomas Soome 
6555ffb0c9bSToomas Soome             // If we failed, then it may be because the daemon is still launching.
6565ffb0c9bSToomas Soome             // This can happen for processes that launch early in the boot process, while the
6575ffb0c9bSToomas Soome             // daemon is still coming up. Rather than fail here, we wait 1 sec and try again.
6585ffb0c9bSToomas Soome             // If, after DNSSD_CLIENT_MAXTRIES, we still can't connect to the daemon,
6595ffb0c9bSToomas Soome             // then we give up and return a failure code.
6605ffb0c9bSToomas Soome             if (++NumTries < DNSSD_CLIENT_MAXTRIES)
6615ffb0c9bSToomas Soome             {
662c65ebfc7SToomas Soome                 syslog(LOG_WARNING, "dnssd_clientstub ConnectToServer: connect()-> No of tries: %d", NumTries);
6635ffb0c9bSToomas Soome                 sleep(1); // Sleep a bit, then try again
6645ffb0c9bSToomas Soome             }
665c65ebfc7SToomas Soome             else
6665ffb0c9bSToomas Soome             {
667cda73f64SToomas Soome                 #if !defined(USE_TCP_LOOPBACK)
668c65ebfc7SToomas Soome                 syslog(LOG_WARNING, "dnssd_clientstub ConnectToServer: connect() failed path:%s Socket:%d Err:%d Errno:%d %s",
6695ffb0c9bSToomas Soome                        uds_serverpath, sdr->sockfd, err, dnssd_errno, dnssd_strerror(dnssd_errno));
670cda73f64SToomas Soome                 #endif
671c65ebfc7SToomas Soome                 dnssd_close(sdr->sockfd);
672c65ebfc7SToomas Soome                 FreeDNSServiceOp(sdr);
673c65ebfc7SToomas Soome                 return kDNSServiceErr_ServiceNotRunning;
6745ffb0c9bSToomas Soome             }
6755ffb0c9bSToomas Soome         }
676*472cd20dSToomas Soome         #else
677*472cd20dSToomas Soome         int err = connect(sdr->sockfd, (struct sockaddr *) &saddr, sizeof(saddr));
678*472cd20dSToomas Soome         if (err)
679*472cd20dSToomas Soome         {
680*472cd20dSToomas Soome             #if !defined(USE_TCP_LOOPBACK)
681*472cd20dSToomas Soome             syslog(LOG_WARNING, "dnssd_clientstub ConnectToServer: connect() failed path:%s Socket:%d Err:%d Errno:%d %s",
682*472cd20dSToomas Soome                    uds_serverpath, sdr->sockfd, err, dnssd_errno, dnssd_strerror(dnssd_errno));
683*472cd20dSToomas Soome             #endif
684*472cd20dSToomas Soome             dnssd_close(sdr->sockfd);
685*472cd20dSToomas Soome             FreeDNSServiceOp(sdr);
686*472cd20dSToomas Soome             return kDNSServiceErr_ServiceNotRunning;
687*472cd20dSToomas Soome         }
688*472cd20dSToomas Soome         #endif
6895ffb0c9bSToomas Soome     }
6905ffb0c9bSToomas Soome 
6915ffb0c9bSToomas Soome     *ref = sdr;
6925ffb0c9bSToomas Soome     return kDNSServiceErr_NoError;
6935ffb0c9bSToomas Soome }
6945ffb0c9bSToomas Soome 
6955ffb0c9bSToomas Soome #define deliver_request_bailout(MSG) \
6963b436d06SToomas Soome     syslog(LOG_WARNING, "dnssd_clientstub deliver_request: %s failed %d (%s)", (MSG), dnssd_errno, dnssd_strerror(dnssd_errno)); goto cleanup
6975ffb0c9bSToomas Soome 
deliver_request(ipc_msg_hdr * hdr,DNSServiceOp * sdr)6985ffb0c9bSToomas Soome static DNSServiceErrorType deliver_request(ipc_msg_hdr *hdr, DNSServiceOp *sdr)
6995ffb0c9bSToomas Soome {
700c65ebfc7SToomas Soome     uint32_t datalen;
701c65ebfc7SToomas Soome     dnssd_sock_t listenfd = dnssd_InvalidSocket, errsd = dnssd_InvalidSocket;
702c65ebfc7SToomas Soome     DNSServiceErrorType err = kDNSServiceErr_Unknown;   // Default for the "goto cleanup" cases
703c65ebfc7SToomas Soome     int MakeSeparateReturnSocket;
704*472cd20dSToomas Soome     int ioresult;
705c65ebfc7SToomas Soome     #if defined(USE_TCP_LOOPBACK) || defined(USE_NAMED_ERROR_RETURN_SOCKET)
706c65ebfc7SToomas Soome     char *data;
707c65ebfc7SToomas Soome     #endif
708c65ebfc7SToomas Soome 
709cda73f64SToomas Soome     if (!hdr)
710cda73f64SToomas Soome     {
711cda73f64SToomas Soome         syslog(LOG_WARNING, "dnssd_clientstub deliver_request: !hdr");
712cda73f64SToomas Soome         return kDNSServiceErr_Unknown;
713cda73f64SToomas Soome     }
714cda73f64SToomas Soome 
715c65ebfc7SToomas Soome     datalen = hdr->datalen;    // We take a copy here because we're going to convert hdr->datalen to network byte order
7165ffb0c9bSToomas Soome     #if defined(USE_TCP_LOOPBACK) || defined(USE_NAMED_ERROR_RETURN_SOCKET)
717c65ebfc7SToomas Soome     data = (char *)hdr + sizeof(ipc_msg_hdr);
7185ffb0c9bSToomas Soome     #endif
7195ffb0c9bSToomas Soome 
7205ffb0c9bSToomas Soome     // Note: need to check hdr->op, not sdr->op.
7215ffb0c9bSToomas Soome     // hdr->op contains the code for the specific operation we're currently doing, whereas sdr->op
7225ffb0c9bSToomas Soome     // contains the original parent DNSServiceOp (e.g. for an add_record_request, hdr->op will be
7235ffb0c9bSToomas Soome     // add_record_request but the parent sdr->op will be connection_request or reg_service_request)
724c65ebfc7SToomas Soome     MakeSeparateReturnSocket = (sdr->primary ||
725cda73f64SToomas Soome         hdr->op == reg_record_request || hdr->op == add_record_request || hdr->op == update_record_request || hdr->op == remove_record_request);
7265ffb0c9bSToomas Soome 
7275ffb0c9bSToomas Soome     if (!DNSServiceRefValid(sdr))
7285ffb0c9bSToomas Soome     {
7295ffb0c9bSToomas Soome         if (hdr)
7305ffb0c9bSToomas Soome             free(hdr);
7315ffb0c9bSToomas Soome         syslog(LOG_WARNING, "dnssd_clientstub deliver_request: invalid DNSServiceRef %p %08X %08X", sdr, sdr->sockfd, sdr->validator);
7325ffb0c9bSToomas Soome         return kDNSServiceErr_BadReference;
7335ffb0c9bSToomas Soome     }
7355ffb0c9bSToomas Soome     if (MakeSeparateReturnSocket)
7365ffb0c9bSToomas Soome     {
7375ffb0c9bSToomas Soome         #if defined(USE_TCP_LOOPBACK)
7385ffb0c9bSToomas Soome         {
7395ffb0c9bSToomas Soome             union { uint16_t s; u_char b[2]; } port;
7405ffb0c9bSToomas Soome             dnssd_sockaddr_t caddr;
7415ffb0c9bSToomas Soome             dnssd_socklen_t len = (dnssd_socklen_t) sizeof(caddr);
7425ffb0c9bSToomas Soome             listenfd = socket(AF_DNSSD, SOCK_STREAM, 0);
7433b436d06SToomas Soome             if (!dnssd_SocketValid(listenfd)) {
7443b436d06SToomas Soome 		deliver_request_bailout("TCP socket");
7453b436d06SToomas Soome 	    }
7465ffb0c9bSToomas Soome 
7475ffb0c9bSToomas Soome             caddr.sin_family      = AF_INET;
7485ffb0c9bSToomas Soome             caddr.sin_port        = 0;
7495ffb0c9bSToomas Soome             caddr.sin_addr.s_addr = inet_addr(MDNS_TCP_SERVERADDR);
7503b436d06SToomas Soome             if (bind(listenfd, (struct sockaddr*) &caddr, sizeof(caddr)) < 0) {
7513b436d06SToomas Soome 		deliver_request_bailout("TCP bind");
7523b436d06SToomas Soome 	    }
7533b436d06SToomas Soome             if (getsockname(listenfd, (struct sockaddr*) &caddr, &len) < 0) {
7543b436d06SToomas Soome 		deliver_request_bailout("TCP getsockname");
7553b436d06SToomas Soome 	    }
7563b436d06SToomas Soome             if (listen(listenfd, 1) < 0) {
7573b436d06SToomas Soome 		deliver_request_bailout("TCP listen");
7583b436d06SToomas Soome 	    }
7595ffb0c9bSToomas Soome             port.s = caddr.sin_port;
7605ffb0c9bSToomas Soome             data[0] = port.b[0];  // don't switch the byte order, as the
7615ffb0c9bSToomas Soome             data[1] = port.b[1];  // daemon expects it in network byte order
7625ffb0c9bSToomas Soome         }
7635ffb0c9bSToomas Soome         #elif defined(USE_NAMED_ERROR_RETURN_SOCKET)
7645ffb0c9bSToomas Soome         {
7655ffb0c9bSToomas Soome             mode_t mask;
7665ffb0c9bSToomas Soome             int bindresult;
7675ffb0c9bSToomas Soome             dnssd_sockaddr_t caddr;
7685ffb0c9bSToomas Soome             listenfd = socket(AF_DNSSD, SOCK_STREAM, 0);
7693b436d06SToomas Soome             if (!dnssd_SocketValid(listenfd)) {
7703b436d06SToomas Soome 		deliver_request_bailout("USE_NAMED_ERROR_RETURN_SOCKET socket");
7713b436d06SToomas Soome 	    }
7725ffb0c9bSToomas Soome 
7735ffb0c9bSToomas Soome             caddr.sun_family = AF_LOCAL;
7745ffb0c9bSToomas Soome             // According to Stevens (section 3.2), there is no portable way to
7755ffb0c9bSToomas Soome             // determine whether sa_len is defined on a particular platform.
7765ffb0c9bSToomas Soome             #ifndef NOT_HAVE_SA_LEN
7775ffb0c9bSToomas Soome             caddr.sun_len = sizeof(struct sockaddr_un);
7785ffb0c9bSToomas Soome             #endif
779c65ebfc7SToomas Soome             SetUDSPath(&caddr, data);
7805ffb0c9bSToomas Soome             mask = umask(0);
7815ffb0c9bSToomas Soome             bindresult = bind(listenfd, (struct sockaddr *)&caddr, sizeof(caddr));
7825ffb0c9bSToomas Soome             umask(mask);
7833b436d06SToomas Soome             if (bindresult < 0) {
7843b436d06SToomas Soome 		deliver_request_bailout("USE_NAMED_ERROR_RETURN_SOCKET bind");
7853b436d06SToomas Soome 	    }
7863b436d06SToomas Soome             if (listen(listenfd, 1) < 0) {
7873b436d06SToomas Soome 		deliver_request_bailout("USE_NAMED_ERROR_RETURN_SOCKET listen");
7883b436d06SToomas Soome 	    }
7895ffb0c9bSToomas Soome         }
7905ffb0c9bSToomas Soome         #else
7915ffb0c9bSToomas Soome         {
7925ffb0c9bSToomas Soome             dnssd_sock_t sp[2];
7933b436d06SToomas Soome             if (socketpair(AF_DNSSD, SOCK_STREAM, 0, sp) < 0) {
7943b436d06SToomas Soome 		deliver_request_bailout("socketpair");
7953b436d06SToomas Soome 	    }
7965ffb0c9bSToomas Soome             else
7975ffb0c9bSToomas Soome             {
7985ffb0c9bSToomas Soome                 errsd    = sp[0];   // We'll read our four-byte error code from sp[0]
7995ffb0c9bSToomas Soome                 listenfd = sp[1];   // We'll send sp[1] to the daemon
8005ffb0c9bSToomas Soome                 #if !defined(__ppc__) && defined(SO_DEFUNCTOK)
8015ffb0c9bSToomas Soome                 {
8025ffb0c9bSToomas Soome                     int defunct = 1;
8035ffb0c9bSToomas Soome                     if (setsockopt(errsd, SOL_SOCKET, SO_DEFUNCTOK, &defunct, sizeof(defunct)) < 0)
804*472cd20dSToomas Soome                         syslog(LOG_WARNING, "dnssd_clientstub deliver_request: SO_DEFUNCTOK failed %d %s", dnssd_errno, dnssd_strerror(dnssd_errno));
8055ffb0c9bSToomas Soome                 }
8065ffb0c9bSToomas Soome                 #endif
8075ffb0c9bSToomas Soome             }
8085ffb0c9bSToomas Soome         }
8095ffb0c9bSToomas Soome         #endif
8105ffb0c9bSToomas Soome     }
8125ffb0c9bSToomas Soome #if !defined(USE_TCP_LOOPBACK) && !defined(USE_NAMED_ERROR_RETURN_SOCKET)
8135ffb0c9bSToomas Soome     // If we're going to make a separate error return socket, and pass it to the daemon
8145ffb0c9bSToomas Soome     // using sendmsg, then we'll hold back one data byte to go with it.
8155ffb0c9bSToomas Soome     // On some versions of Unix (including Leopard) sending a control message without
8165ffb0c9bSToomas Soome     // any associated data does not work reliably -- e.g. one particular issue we ran
8175ffb0c9bSToomas Soome     // into is that if the receiving program is in a kqueue loop waiting to be notified
8185ffb0c9bSToomas Soome     // of the received message, it doesn't get woken up when the control message arrives.
819c65ebfc7SToomas Soome     if (MakeSeparateReturnSocket || sdr->op == send_bpf)
8205ffb0c9bSToomas Soome         datalen--;     // Okay to use sdr->op when checking for op == send_bpf
8215ffb0c9bSToomas Soome #endif
8225ffb0c9bSToomas Soome 
8235ffb0c9bSToomas Soome     // At this point, our listening socket is set up and waiting, if necessary, for the daemon to connect back to
8245ffb0c9bSToomas Soome     ConvertHeaderBytes(hdr);
8255ffb0c9bSToomas Soome     //syslog(LOG_WARNING, "dnssd_clientstub deliver_request writing %lu bytes", (unsigned long)(datalen + sizeof(ipc_msg_hdr)));
8265ffb0c9bSToomas Soome     //if (MakeSeparateReturnSocket) syslog(LOG_WARNING, "dnssd_clientstub deliver_request name is %s", data);
8275ffb0c9bSToomas Soome #if TEST_SENDING_ONE_BYTE_AT_A_TIME
8285ffb0c9bSToomas Soome     unsigned int i;
8295ffb0c9bSToomas Soome     for (i=0; i<datalen + sizeof(ipc_msg_hdr); i++)
8305ffb0c9bSToomas Soome     {
8315ffb0c9bSToomas Soome         syslog(LOG_WARNING, "dnssd_clientstub deliver_request writing %d", i);
832*472cd20dSToomas Soome         ioresult = write_all(sdr->sockfd, ((char *)hdr)+i, 1);
833*472cd20dSToomas Soome         if (ioresult < write_all_success)
834*472cd20dSToomas Soome         {
835*472cd20dSToomas Soome             syslog(LOG_WARNING, "dnssd_clientstub deliver_request write_all (byte %u) failed", i);
836*472cd20dSToomas Soome             err = (ioresult == write_all_defunct) ? kDNSServiceErr_DefunctConnection : kDNSServiceErr_ServiceNotRunning;
837*472cd20dSToomas Soome             goto cleanup;
838*472cd20dSToomas Soome         }
8395ffb0c9bSToomas Soome         usleep(10000);
8405ffb0c9bSToomas Soome     }
8414b22b933Srs #else
842*472cd20dSToomas Soome     ioresult = write_all(sdr->sockfd, (char *)hdr, datalen + sizeof(ipc_msg_hdr));
843*472cd20dSToomas Soome     if (ioresult < write_all_success)
8445ffb0c9bSToomas Soome     {
8455ffb0c9bSToomas Soome         // write_all already prints an error message if there is an error writing to
8465ffb0c9bSToomas Soome         // the socket except for DEFUNCT. Logging here is unnecessary and also wrong
8475ffb0c9bSToomas Soome         // in the case of DEFUNCT sockets
8485ffb0c9bSToomas Soome         syslog(LOG_INFO, "dnssd_clientstub deliver_request ERROR: write_all(%d, %lu bytes) failed",
8495ffb0c9bSToomas Soome                sdr->sockfd, (unsigned long)(datalen + sizeof(ipc_msg_hdr)));
850*472cd20dSToomas Soome         err = (ioresult == write_all_defunct) ? kDNSServiceErr_DefunctConnection : kDNSServiceErr_ServiceNotRunning;
8515ffb0c9bSToomas Soome         goto cleanup;
8525ffb0c9bSToomas Soome     }
8534b22b933Srs #endif
8545ffb0c9bSToomas Soome 
855c65ebfc7SToomas Soome     if (!MakeSeparateReturnSocket)
8565ffb0c9bSToomas Soome         errsd = sdr->sockfd;
8575ffb0c9bSToomas Soome     if (MakeSeparateReturnSocket || sdr->op == send_bpf)    // Okay to use sdr->op when checking for op == send_bpf
8585ffb0c9bSToomas Soome     {
8595ffb0c9bSToomas Soome #if defined(USE_TCP_LOOPBACK) || defined(USE_NAMED_ERROR_RETURN_SOCKET)
8605ffb0c9bSToomas Soome         // At this point we may wait in accept for a few milliseconds waiting for the daemon to connect back to us,
8615ffb0c9bSToomas Soome         // but that's okay -- the daemon should not take more than a few milliseconds to respond.
8625ffb0c9bSToomas Soome         // set_waitlimit() ensures we do not block indefinitely just in case something is wrong
8635ffb0c9bSToomas Soome         dnssd_sockaddr_t daddr;
8645ffb0c9bSToomas Soome         dnssd_socklen_t len = sizeof(daddr);
865c65ebfc7SToomas Soome         if ((err = set_waitlimit(listenfd, DNSSD_CLIENT_TIMEOUT)) != kDNSServiceErr_NoError)
8665ffb0c9bSToomas Soome             goto cleanup;
8675ffb0c9bSToomas Soome         errsd = accept(listenfd, (struct sockaddr *)&daddr, &len);
8683b436d06SToomas Soome         if (!dnssd_SocketValid(errsd)) {
8695ffb0c9bSToomas Soome             deliver_request_bailout("accept");
8703b436d06SToomas Soome 	}
8715ffb0c9bSToomas Soome #else
8725ffb0c9bSToomas Soome 
8735ffb0c9bSToomas Soome         struct iovec vec = { ((char *)hdr) + sizeof(ipc_msg_hdr) + datalen, 1 }; // Send the last byte along with the SCM_RIGHTS
8745ffb0c9bSToomas Soome         struct msghdr msg;
8755ffb0c9bSToomas Soome         struct cmsghdr *cmsg;
8765ffb0c9bSToomas Soome         char cbuf[CMSG_SPACE(4 * sizeof(dnssd_sock_t))];
8775ffb0c9bSToomas Soome 
8785ffb0c9bSToomas Soome         msg.msg_name       = 0;
8795ffb0c9bSToomas Soome         msg.msg_namelen    = 0;
8805ffb0c9bSToomas Soome         msg.msg_iov        = &vec;
8815ffb0c9bSToomas Soome         msg.msg_iovlen     = 1;
8825ffb0c9bSToomas Soome         msg.msg_flags      = 0;
8835ffb0c9bSToomas Soome         if (MakeSeparateReturnSocket || sdr->op == send_bpf)    // Okay to use sdr->op when checking for op == send_bpf
8845ffb0c9bSToomas Soome         {
8855ffb0c9bSToomas Soome             if (sdr->op == send_bpf)
8865ffb0c9bSToomas Soome             {
8875ffb0c9bSToomas Soome                 int i;
8885ffb0c9bSToomas Soome                 char p[12];     // Room for "/dev/bpf999" with terminating null
8895ffb0c9bSToomas Soome                 for (i=0; i<100; i++)
8905ffb0c9bSToomas Soome                 {
8915ffb0c9bSToomas Soome                     snprintf(p, sizeof(p), "/dev/bpf%d", i);
8925ffb0c9bSToomas Soome                     listenfd = open(p, O_RDWR, 0);
893*472cd20dSToomas Soome                     //if (dnssd_SocketValid(listenfd)) syslog(LOG_WARNING, "dnssd_clientstub deliver_request Sending fd %d for %s", listenfd, p);
8945ffb0c9bSToomas Soome                     if (!dnssd_SocketValid(listenfd) && dnssd_errno != EBUSY)
895*472cd20dSToomas Soome                         syslog(LOG_WARNING, "dnssd_clientstub deliver_request Error opening %s %d (%s)", p, dnssd_errno, dnssd_strerror(dnssd_errno));
8965ffb0c9bSToomas Soome                     if (dnssd_SocketValid(listenfd) || dnssd_errno != EBUSY) break;
8975ffb0c9bSToomas Soome                 }
8985ffb0c9bSToomas Soome             }
8995ffb0c9bSToomas Soome             msg.msg_control    = cbuf;
9005ffb0c9bSToomas Soome             msg.msg_controllen = CMSG_LEN(sizeof(dnssd_sock_t));
9015ffb0c9bSToomas Soome 
9025ffb0c9bSToomas Soome             cmsg = CMSG_FIRSTHDR(&msg);
9035ffb0c9bSToomas Soome             cmsg->cmsg_len     = CMSG_LEN(sizeof(dnssd_sock_t));
9045ffb0c9bSToomas Soome             cmsg->cmsg_level   = SOL_SOCKET;
9055ffb0c9bSToomas Soome             cmsg->cmsg_type    = SCM_RIGHTS;
9065ffb0c9bSToomas Soome             *((dnssd_sock_t *)CMSG_DATA(cmsg)) = listenfd;
9075ffb0c9bSToomas Soome         }
9085ffb0c9bSToomas Soome 
9095ffb0c9bSToomas Soome #if TEST_KQUEUE_CONTROL_MESSAGE_BUG
9105ffb0c9bSToomas Soome         sleep(1);
9114b22b933Srs #endif
9135ffb0c9bSToomas Soome #if DEBUG_64BIT_SCM_RIGHTS
914*472cd20dSToomas Soome         syslog(LOG_WARNING, "dnssd_clientstub deliver_request sendmsg read sd=%d write sd=%d %ld %ld %ld/%ld/%ld/%ld",
9155ffb0c9bSToomas Soome                errsd, listenfd, sizeof(dnssd_sock_t), sizeof(void*),
9165ffb0c9bSToomas Soome                sizeof(struct cmsghdr) + sizeof(dnssd_sock_t),
9175ffb0c9bSToomas Soome                CMSG_LEN(sizeof(dnssd_sock_t)), (long)CMSG_SPACE(sizeof(dnssd_sock_t)),
9185ffb0c9bSToomas Soome                (long)((char*)CMSG_DATA(cmsg) + 4 - cbuf));
9195ffb0c9bSToomas Soome #endif // DEBUG_64BIT_SCM_RIGHTS
9215ffb0c9bSToomas Soome         if (sendmsg(sdr->sockfd, &msg, 0) < 0)
9224b22b933Srs         {
9235ffb0c9bSToomas Soome             syslog(LOG_WARNING, "dnssd_clientstub deliver_request ERROR: sendmsg failed read sd=%d write sd=%d errno %d (%s)",
9245ffb0c9bSToomas Soome                    errsd, listenfd, dnssd_errno, dnssd_strerror(dnssd_errno));
9255ffb0c9bSToomas Soome             err = kDNSServiceErr_Incompatible;
9265ffb0c9bSToomas Soome             goto cleanup;
9274b22b933Srs         }
9295ffb0c9bSToomas Soome #if DEBUG_64BIT_SCM_RIGHTS
930*472cd20dSToomas Soome         syslog(LOG_WARNING, "dnssd_clientstub deliver_request sendmsg read sd=%d write sd=%d okay", errsd, listenfd);
9315ffb0c9bSToomas Soome #endif // DEBUG_64BIT_SCM_RIGHTS
9335ffb0c9bSToomas Soome #endif
9345ffb0c9bSToomas Soome         // Close our end of the socketpair *before* calling read_all() to get the four-byte error code.
9355ffb0c9bSToomas Soome         // Otherwise, if the daemon closes our socket (or crashes), we will have to wait for a timeout
9365ffb0c9bSToomas Soome         // in read_all() because the socket is not closed (we still have an open reference to it)
9375ffb0c9bSToomas Soome         // Note: listenfd is overwritten in the case of send_bpf above and that will be closed here
9385ffb0c9bSToomas Soome         // for send_bpf operation.
9395ffb0c9bSToomas Soome         dnssd_close(listenfd);
9405ffb0c9bSToomas Soome         listenfd = dnssd_InvalidSocket; // Make sure we don't close it a second time in the cleanup handling below
9415ffb0c9bSToomas Soome     }
9425ffb0c9bSToomas Soome 
9435ffb0c9bSToomas Soome     // At this point we may wait in read_all for a few milliseconds waiting for the daemon to send us the error code,
9445ffb0c9bSToomas Soome     // but that's okay -- the daemon should not take more than a few milliseconds to respond.
9455ffb0c9bSToomas Soome     // set_waitlimit() ensures we do not block indefinitely just in case something is wrong
9465ffb0c9bSToomas Soome     if (sdr->op == send_bpf)    // Okay to use sdr->op when checking for op == send_bpf
9475ffb0c9bSToomas Soome         err = kDNSServiceErr_NoError;
9485ffb0c9bSToomas Soome     else if ((err = set_waitlimit(errsd, DNSSD_CLIENT_TIMEOUT)) == kDNSServiceErr_NoError)
9495ffb0c9bSToomas Soome     {
950*472cd20dSToomas Soome         ioresult = read_all(errsd, (char*)&err, (int)sizeof(err));
951*472cd20dSToomas Soome         if (ioresult < read_all_success)
952*472cd20dSToomas Soome             err = (ioresult == read_all_defunct) ? kDNSServiceErr_DefunctConnection : kDNSServiceErr_ServiceNotRunning; // On failure read_all will have written a message to syslog for us
9535ffb0c9bSToomas Soome         else
9545ffb0c9bSToomas Soome             err = ntohl(err);
9555ffb0c9bSToomas Soome     }
9565ffb0c9bSToomas Soome     //syslog(LOG_WARNING, "dnssd_clientstub deliver_request: retrieved error code %d", err);
9584b22b933Srs cleanup:
9595ffb0c9bSToomas Soome     if (MakeSeparateReturnSocket)
9605ffb0c9bSToomas Soome     {
9615ffb0c9bSToomas Soome         if (dnssd_SocketValid(listenfd)) dnssd_close(listenfd);
9625ffb0c9bSToomas Soome         if (dnssd_SocketValid(errsd)) dnssd_close(errsd);
9635ffb0c9bSToomas Soome #if defined(USE_NAMED_ERROR_RETURN_SOCKET)
9645ffb0c9bSToomas Soome         // syslog(LOG_WARNING, "dnssd_clientstub deliver_request: removing UDS: %s", data);
9655ffb0c9bSToomas Soome         if (unlink(data) != 0)
9665ffb0c9bSToomas Soome             syslog(LOG_WARNING, "dnssd_clientstub WARNING: unlink(\"%s\") failed errno %d (%s)", data, dnssd_errno, dnssd_strerror(dnssd_errno));
9675ffb0c9bSToomas Soome         // else syslog(LOG_WARNING, "dnssd_clientstub deliver_request: removed UDS: %s", data);
9684b22b933Srs #endif
9694b22b933Srs     }
9715ffb0c9bSToomas Soome     free(hdr);
9725ffb0c9bSToomas Soome     return err;
9735ffb0c9bSToomas Soome }
9745ffb0c9bSToomas Soome 
DNSServiceRefSockFD(DNSServiceRef sdRef)975c65ebfc7SToomas Soome dnssd_sock_t DNSSD_API DNSServiceRefSockFD(DNSServiceRef sdRef)
9765ffb0c9bSToomas Soome {
9775ffb0c9bSToomas Soome     if (!sdRef) { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRefSockFD called with NULL DNSServiceRef"); return dnssd_InvalidSocket; }
9785ffb0c9bSToomas Soome 
9795ffb0c9bSToomas Soome     if (!DNSServiceRefValid(sdRef))
9804b22b933Srs     {
9815ffb0c9bSToomas Soome         syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRefSockFD called with invalid DNSServiceRef %p %08X %08X",
9825ffb0c9bSToomas Soome                sdRef, sdRef->sockfd, sdRef->validator);
9835ffb0c9bSToomas Soome         return dnssd_InvalidSocket;
9845ffb0c9bSToomas Soome     }
9855ffb0c9bSToomas Soome 
9865ffb0c9bSToomas Soome     if (sdRef->primary)
9875ffb0c9bSToomas Soome     {
9885ffb0c9bSToomas Soome         syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRefSockFD undefined for kDNSServiceFlagsShareConnection subordinate DNSServiceRef %p", sdRef);
9895ffb0c9bSToomas Soome         return dnssd_InvalidSocket;
9905ffb0c9bSToomas Soome     }
9915ffb0c9bSToomas Soome 
992c65ebfc7SToomas Soome     return sdRef->sockfd;
9935ffb0c9bSToomas Soome }
9945ffb0c9bSToomas Soome 
9955ffb0c9bSToomas Soome #if _DNS_SD_LIBDISPATCH
CallbackWithError(DNSServiceRef sdRef,DNSServiceErrorType error)9965ffb0c9bSToomas Soome static void CallbackWithError(DNSServiceRef sdRef, DNSServiceErrorType error)
9975ffb0c9bSToomas Soome {
9985ffb0c9bSToomas Soome     DNSServiceOp *sdr = sdRef;
9995ffb0c9bSToomas Soome     DNSServiceOp *sdrNext;
10005ffb0c9bSToomas Soome     DNSRecord *rec;
10015ffb0c9bSToomas Soome     DNSRecord *recnext;
10025ffb0c9bSToomas Soome     int morebytes;
10035ffb0c9bSToomas Soome 
10045ffb0c9bSToomas Soome     while (sdr)
10055ffb0c9bSToomas Soome     {
10065ffb0c9bSToomas Soome         // We can't touch the sdr after the callback as it can be deallocated in the callback
10075ffb0c9bSToomas Soome         sdrNext = sdr->next;
10085ffb0c9bSToomas Soome         morebytes = 1;
10095ffb0c9bSToomas Soome         sdr->moreptr = &morebytes;
10105ffb0c9bSToomas Soome         switch (sdr->op)
10115ffb0c9bSToomas Soome         {
10125ffb0c9bSToomas Soome         case resolve_request:
10135ffb0c9bSToomas Soome             if (sdr->AppCallback) ((DNSServiceResolveReply)    sdr->AppCallback)(sdr, 0, 0, error, NULL, 0, 0, 0, NULL,    sdr->AppContext);
10145ffb0c9bSToomas Soome             break;
10155ffb0c9bSToomas Soome         case query_request:
10165ffb0c9bSToomas Soome             if (sdr->AppCallback) ((DNSServiceQueryRecordReply)sdr->AppCallback)(sdr, 0, 0, error, NULL, 0, 0, 0, NULL, 0, sdr->AppContext);
10175ffb0c9bSToomas Soome             break;
10185ffb0c9bSToomas Soome         case addrinfo_request:
10195ffb0c9bSToomas Soome             if (sdr->AppCallback) ((DNSServiceGetAddrInfoReply)sdr->AppCallback)(sdr, 0, 0, error, NULL, NULL, 0,          sdr->AppContext);
10205ffb0c9bSToomas Soome             break;
10215ffb0c9bSToomas Soome         case browse_request:
10225ffb0c9bSToomas Soome             if (sdr->AppCallback) ((DNSServiceBrowseReply)     sdr->AppCallback)(sdr, 0, 0, error, NULL, 0, NULL,          sdr->AppContext);
10235ffb0c9bSToomas Soome             break;
10245ffb0c9bSToomas Soome         case reg_service_request:
10255ffb0c9bSToomas Soome             if (sdr->AppCallback) ((DNSServiceRegisterReply)   sdr->AppCallback)(sdr, 0,    error, NULL, 0, NULL,          sdr->AppContext);
10265ffb0c9bSToomas Soome             break;
10275ffb0c9bSToomas Soome         case enumeration_request:
10285ffb0c9bSToomas Soome             if (sdr->AppCallback) ((DNSServiceDomainEnumReply) sdr->AppCallback)(sdr, 0, 0, error, NULL,                   sdr->AppContext);
10295ffb0c9bSToomas Soome             break;
10305ffb0c9bSToomas Soome         case connection_request:
10315ffb0c9bSToomas Soome         case connection_delegate_request:
10325ffb0c9bSToomas Soome             // This means Register Record, walk the list of DNSRecords to do the callback
10335ffb0c9bSToomas Soome             rec = sdr->rec;
10345ffb0c9bSToomas Soome             while (rec)
10355ffb0c9bSToomas Soome             {
10365ffb0c9bSToomas Soome                 recnext = rec->recnext;
10375ffb0c9bSToomas Soome                 if (rec->AppCallback) ((DNSServiceRegisterRecordReply)rec->AppCallback)(sdr, 0, 0, error, rec->AppContext);
10385ffb0c9bSToomas Soome                 // The Callback can call DNSServiceRefDeallocate which in turn frees sdr and all the records.
10395ffb0c9bSToomas Soome                 // Detect that and return early
1040*472cd20dSToomas Soome                 if (!morebytes) { syslog(LOG_WARNING, "dnssd_clientstub:Record: CallbackwithError morebytes zero"); return; }
10415ffb0c9bSToomas Soome                 rec = recnext;
10425ffb0c9bSToomas Soome             }
10435ffb0c9bSToomas Soome             break;
10445ffb0c9bSToomas Soome         case port_mapping_request:
10455ffb0c9bSToomas Soome             if (sdr->AppCallback) ((DNSServiceNATPortMappingReply)sdr->AppCallback)(sdr, 0, 0, error, 0, 0, 0, 0, 0, sdr->AppContext);
10465ffb0c9bSToomas Soome             break;
10475ffb0c9bSToomas Soome         default:
10485ffb0c9bSToomas Soome             syslog(LOG_WARNING, "dnssd_clientstub CallbackWithError called with bad op %d", sdr->op);
10495ffb0c9bSToomas Soome         }
10505ffb0c9bSToomas Soome         // If DNSServiceRefDeallocate was called in the callback, morebytes will be zero. As the sdRef
10515ffb0c9bSToomas Soome         // (and its subordinates) have been freed, we should not proceed further. Note that when we
10525ffb0c9bSToomas Soome         // call the callback with a subordinate sdRef the application can call DNSServiceRefDeallocate
10535ffb0c9bSToomas Soome         // on the main sdRef and DNSServiceRefDeallocate handles this case by walking all the sdRefs and
10545ffb0c9bSToomas Soome         // clears the moreptr so that we can terminate here.
10555ffb0c9bSToomas Soome         //
10565ffb0c9bSToomas Soome         // If DNSServiceRefDeallocate was not called in the callback, then set moreptr to NULL so that
10575ffb0c9bSToomas Soome         // we don't access the stack variable after we return from this function.
1058*472cd20dSToomas Soome         if (!morebytes) { syslog(LOG_WARNING, "dnssd_clientstub:sdRef: CallbackwithError morebytes zero sdr %p", sdr); return; }
10595ffb0c9bSToomas Soome         else {sdr->moreptr = NULL;}
10605ffb0c9bSToomas Soome         sdr = sdrNext;
10614b22b933Srs     }
10625ffb0c9bSToomas Soome }
10635ffb0c9bSToomas Soome #endif // _DNS_SD_LIBDISPATCH
10655ffb0c9bSToomas Soome // Handle reply from server, calling application client callback. If there is no reply
10664b22b933Srs // from the daemon on the socket contained in sdRef, the call will block.
DNSServiceProcessResult(DNSServiceRef sdRef)10674b22b933Srs DNSServiceErrorType DNSSD_API DNSServiceProcessResult(DNSServiceRef sdRef)
10685ffb0c9bSToomas Soome {
10695ffb0c9bSToomas Soome     int morebytes = 0;
1070*472cd20dSToomas Soome     int ioresult;
1071*472cd20dSToomas Soome     DNSServiceErrorType error;
10725ffb0c9bSToomas Soome 
10735ffb0c9bSToomas Soome     if (!sdRef) { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceProcessResult called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam; }
10745ffb0c9bSToomas Soome 
10755ffb0c9bSToomas Soome     if (!DNSServiceRefValid(sdRef))
10764b22b933Srs     {
10775ffb0c9bSToomas Soome         syslog(LOG_WARNING, "dnssd_clientstub DNSServiceProcessResult called with invalid DNSServiceRef %p %08X %08X", sdRef, sdRef->sockfd, sdRef->validator);
10785ffb0c9bSToomas Soome         return kDNSServiceErr_BadReference;
10795ffb0c9bSToomas Soome     }
10815ffb0c9bSToomas Soome     if (sdRef->primary)
10825ffb0c9bSToomas Soome     {
10835ffb0c9bSToomas Soome         syslog(LOG_WARNING, "dnssd_clientstub DNSServiceProcessResult undefined for kDNSServiceFlagsShareConnection subordinate DNSServiceRef %p", sdRef);
10844b22b933Srs         return kDNSServiceErr_BadReference;
10855ffb0c9bSToomas Soome     }
10875ffb0c9bSToomas Soome     if (!sdRef->ProcessReply)
10885ffb0c9bSToomas Soome     {
10895ffb0c9bSToomas Soome         static int num_logs = 0;
10905ffb0c9bSToomas Soome         if (num_logs < 10) syslog(LOG_WARNING, "dnssd_clientstub DNSServiceProcessResult called with DNSServiceRef with no ProcessReply function");
10915ffb0c9bSToomas Soome         if (num_logs < 1000) num_logs++;else sleep(1);
10925ffb0c9bSToomas Soome         return kDNSServiceErr_BadReference;
10934b22b933Srs     }
10955ffb0c9bSToomas Soome     do
10965ffb0c9bSToomas Soome     {
10975ffb0c9bSToomas Soome         CallbackHeader cbh;
10985ffb0c9bSToomas Soome         char *data;
10995ffb0c9bSToomas Soome 
11005ffb0c9bSToomas Soome         // return NoError on EWOULDBLOCK. This will handle the case
11015ffb0c9bSToomas Soome         // where a non-blocking socket is told there is data, but it was a false positive.
11025ffb0c9bSToomas Soome         // On error, read_all will write a message to syslog for us, so don't need to duplicate that here
11035ffb0c9bSToomas Soome         // Note: If we want to properly support using non-blocking sockets in the future
1104*472cd20dSToomas Soome         ioresult = read_all(sdRef->sockfd, (void *)&cbh.ipc_hdr, sizeof(cbh.ipc_hdr));
1105*472cd20dSToomas Soome         if (ioresult == read_all_fail || ioresult == read_all_defunct)
11065ffb0c9bSToomas Soome         {
1107*472cd20dSToomas Soome             error = (ioresult == read_all_defunct) ? kDNSServiceErr_DefunctConnection : kDNSServiceErr_ServiceNotRunning;
1108*472cd20dSToomas Soome 
11095ffb0c9bSToomas Soome             // Set the ProcessReply to NULL before callback as the sdRef can get deallocated
11105ffb0c9bSToomas Soome             // in the callback.
11115ffb0c9bSToomas Soome             sdRef->ProcessReply = NULL;
11125ffb0c9bSToomas Soome #if _DNS_SD_LIBDISPATCH
11135ffb0c9bSToomas Soome             // Call the callbacks with an error if using the dispatch API, as DNSServiceProcessResult
11145ffb0c9bSToomas Soome             // is not called by the application and hence need to communicate the error. Cancel the
11155ffb0c9bSToomas Soome             // source so that we don't get any more events
11165ffb0c9bSToomas Soome             // Note: read_all fails if we could not read from the daemon which can happen if the
11175ffb0c9bSToomas Soome             // daemon dies or the file descriptor is disconnected (defunct).
11185ffb0c9bSToomas Soome             if (sdRef->disp_source)
11195ffb0c9bSToomas Soome             {
11205ffb0c9bSToomas Soome                 dispatch_source_cancel(sdRef->disp_source);
11215ffb0c9bSToomas Soome                 dispatch_release(sdRef->disp_source);
11225ffb0c9bSToomas Soome                 sdRef->disp_source = NULL;
1123*472cd20dSToomas Soome                 CallbackWithError(sdRef, error);
11245ffb0c9bSToomas Soome             }
11255ffb0c9bSToomas Soome #endif
11265ffb0c9bSToomas Soome             // Don't touch sdRef anymore as it might have been deallocated
1127*472cd20dSToomas Soome             return error;
11285ffb0c9bSToomas Soome         }
1129*472cd20dSToomas Soome         else if (ioresult == read_all_wouldblock)
11305ffb0c9bSToomas Soome         {
11315ffb0c9bSToomas Soome             if (morebytes && sdRef->logcounter < 100)
11325ffb0c9bSToomas Soome             {
11335ffb0c9bSToomas Soome                 sdRef->logcounter++;
11345ffb0c9bSToomas Soome                 syslog(LOG_WARNING, "dnssd_clientstub DNSServiceProcessResult error: select indicated data was waiting but read_all returned EWOULDBLOCK");
11355ffb0c9bSToomas Soome             }
11365ffb0c9bSToomas Soome             return kDNSServiceErr_NoError;
11375ffb0c9bSToomas Soome         }
11385ffb0c9bSToomas Soome 
11395ffb0c9bSToomas Soome         ConvertHeaderBytes(&cbh.ipc_hdr);
11405ffb0c9bSToomas Soome         if (cbh.ipc_hdr.version != VERSION)
11415ffb0c9bSToomas Soome         {
11425ffb0c9bSToomas Soome             syslog(LOG_WARNING, "dnssd_clientstub DNSServiceProcessResult daemon version %d does not match client version %d", cbh.ipc_hdr.version, VERSION);
11435ffb0c9bSToomas Soome             sdRef->ProcessReply = NULL;
11445ffb0c9bSToomas Soome             return kDNSServiceErr_Incompatible;
11455ffb0c9bSToomas Soome         }
11465ffb0c9bSToomas Soome 
11475ffb0c9bSToomas Soome         data = malloc(cbh.ipc_hdr.datalen);
11485ffb0c9bSToomas Soome         if (!data) return kDNSServiceErr_NoMemory;
1149*472cd20dSToomas Soome         ioresult = read_all(sdRef->sockfd, data, cbh.ipc_hdr.datalen);
1150*472cd20dSToomas Soome         if (ioresult < read_all_success) // On error, read_all will write a message to syslog for us
11515ffb0c9bSToomas Soome         {
1152*472cd20dSToomas Soome             error = (ioresult == read_all_defunct) ? kDNSServiceErr_DefunctConnection : kDNSServiceErr_ServiceNotRunning;
1153*472cd20dSToomas Soome 
11545ffb0c9bSToomas Soome             // Set the ProcessReply to NULL before callback as the sdRef can get deallocated
11555ffb0c9bSToomas Soome             // in the callback.
11565ffb0c9bSToomas Soome             sdRef->ProcessReply = NULL;
11575ffb0c9bSToomas Soome #if _DNS_SD_LIBDISPATCH
11585ffb0c9bSToomas Soome             // Call the callbacks with an error if using the dispatch API, as DNSServiceProcessResult
11595ffb0c9bSToomas Soome             // is not called by the application and hence need to communicate the error. Cancel the
11605ffb0c9bSToomas Soome             // source so that we don't get any more events
11615ffb0c9bSToomas Soome             if (sdRef->disp_source)
11625ffb0c9bSToomas Soome             {
11635ffb0c9bSToomas Soome                 dispatch_source_cancel(sdRef->disp_source);
11645ffb0c9bSToomas Soome                 dispatch_release(sdRef->disp_source);
11655ffb0c9bSToomas Soome                 sdRef->disp_source = NULL;
1166*472cd20dSToomas Soome                 CallbackWithError(sdRef, error);
11675ffb0c9bSToomas Soome             }
11685ffb0c9bSToomas Soome #endif
11695ffb0c9bSToomas Soome             // Don't touch sdRef anymore as it might have been deallocated
11705ffb0c9bSToomas Soome             free(data);
1171*472cd20dSToomas Soome             return error;
11725ffb0c9bSToomas Soome         }
11735ffb0c9bSToomas Soome         else
11745ffb0c9bSToomas Soome         {
11755ffb0c9bSToomas Soome             const char *ptr = data;
11765ffb0c9bSToomas Soome             cbh.cb_flags     = get_flags     (&ptr, data + cbh.ipc_hdr.datalen);
11775ffb0c9bSToomas Soome             cbh.cb_interface = get_uint32    (&ptr, data + cbh.ipc_hdr.datalen);
11785ffb0c9bSToomas Soome             cbh.cb_err       = get_error_code(&ptr, data + cbh.ipc_hdr.datalen);
11795ffb0c9bSToomas Soome 
11805ffb0c9bSToomas Soome             // CAUTION: We have to handle the case where the client calls DNSServiceRefDeallocate from within the callback function.
11815ffb0c9bSToomas Soome             // To do this we set moreptr to point to morebytes. If the client does call DNSServiceRefDeallocate(),
11825ffb0c9bSToomas Soome             // then that routine will clear morebytes for us, and cause us to exit our loop.
11835ffb0c9bSToomas Soome             morebytes = more_bytes(sdRef->sockfd);
11845ffb0c9bSToomas Soome             if (morebytes)
11855ffb0c9bSToomas Soome             {
11865ffb0c9bSToomas Soome                 cbh.cb_flags |= kDNSServiceFlagsMoreComing;
11875ffb0c9bSToomas Soome                 sdRef->moreptr = &morebytes;
11885ffb0c9bSToomas Soome             }
11895ffb0c9bSToomas Soome             if (ptr) sdRef->ProcessReply(sdRef, &cbh, ptr, data + cbh.ipc_hdr.datalen);
11905ffb0c9bSToomas Soome             // Careful code here:
11915ffb0c9bSToomas Soome             // If morebytes is non-zero, that means we set sdRef->moreptr above, and the operation was not
11925ffb0c9bSToomas Soome             // cancelled out from under us, so now we need to clear sdRef->moreptr so we don't leave a stray
11935ffb0c9bSToomas Soome             // dangling pointer pointing to a long-gone stack variable.
11945ffb0c9bSToomas Soome             // If morebytes is zero, then one of two thing happened:
11955ffb0c9bSToomas Soome             // (a) morebytes was 0 above, so we didn't set sdRef->moreptr, so we don't need to clear it
11965ffb0c9bSToomas Soome             // (b) morebytes was 1 above, and we set sdRef->moreptr, but the operation was cancelled (with DNSServiceRefDeallocate()),
11975ffb0c9bSToomas Soome             //     so we MUST NOT try to dereference our stale sdRef pointer.
11985ffb0c9bSToomas Soome             if (morebytes) sdRef->moreptr = NULL;
11995ffb0c9bSToomas Soome         }
12005ffb0c9bSToomas Soome         free(data);
12015ffb0c9bSToomas Soome     } while (morebytes);
12025ffb0c9bSToomas Soome 
12035ffb0c9bSToomas Soome     return kDNSServiceErr_NoError;
12045ffb0c9bSToomas Soome }
12055ffb0c9bSToomas Soome 
DNSServiceRefDeallocate(DNSServiceRef sdRef)12064b22b933Srs void DNSSD_API DNSServiceRefDeallocate(DNSServiceRef sdRef)
12075ffb0c9bSToomas Soome {
12085ffb0c9bSToomas Soome     if (!sdRef) { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRefDeallocate called with NULL DNSServiceRef"); return; }
12095ffb0c9bSToomas Soome 
12105ffb0c9bSToomas Soome     if (!DNSServiceRefValid(sdRef))     // Also verifies dnssd_SocketValid(sdRef->sockfd) for us too
12115ffb0c9bSToomas Soome     {
12125ffb0c9bSToomas Soome         syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRefDeallocate called with invalid DNSServiceRef %p %08X %08X", sdRef, sdRef->sockfd, sdRef->validator);
12135ffb0c9bSToomas Soome         return;
12145ffb0c9bSToomas Soome     }
12155ffb0c9bSToomas Soome 
12165ffb0c9bSToomas Soome     // 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
12175ffb0c9bSToomas Soome     if (sdRef->moreptr) *(sdRef->moreptr) = 0;
12185ffb0c9bSToomas Soome 
12195ffb0c9bSToomas Soome     if (sdRef->primary)     // If this is a subordinate DNSServiceOp, just send a 'stop' command
12205ffb0c9bSToomas Soome     {
12215ffb0c9bSToomas Soome         DNSServiceOp **p = &sdRef->primary->next;
12225ffb0c9bSToomas Soome         while (*p && *p != sdRef) p = &(*p)->next;
12235ffb0c9bSToomas Soome         if (*p)
12245ffb0c9bSToomas Soome         {
12255ffb0c9bSToomas Soome             char *ptr;
12265ffb0c9bSToomas Soome             size_t len = 0;
12275ffb0c9bSToomas Soome             ipc_msg_hdr *hdr = create_hdr(cancel_request, &len, &ptr, 0, sdRef);
12285ffb0c9bSToomas Soome             if (hdr)
12295ffb0c9bSToomas Soome             {
12305ffb0c9bSToomas Soome                 ConvertHeaderBytes(hdr);
12315ffb0c9bSToomas Soome                 write_all(sdRef->sockfd, (char *)hdr, len);
12325ffb0c9bSToomas Soome                 free(hdr);
12335ffb0c9bSToomas Soome             }
12345ffb0c9bSToomas Soome             *p = sdRef->next;
12355ffb0c9bSToomas Soome             FreeDNSServiceOp(sdRef);
12365ffb0c9bSToomas Soome         }
12375ffb0c9bSToomas Soome     }
12385ffb0c9bSToomas Soome     else                    // else, make sure to terminate all subordinates as well
12395ffb0c9bSToomas Soome     {
12405ffb0c9bSToomas Soome #if _DNS_SD_LIBDISPATCH
12415ffb0c9bSToomas Soome         // The cancel handler will close the fd if a dispatch source has been set
12425ffb0c9bSToomas Soome         if (sdRef->disp_source)
12435ffb0c9bSToomas Soome         {
12445ffb0c9bSToomas Soome             // By setting the ProcessReply to NULL, we make sure that we never call
12455ffb0c9bSToomas Soome             // the application callbacks ever, after returning from this function. We
12465ffb0c9bSToomas Soome             // assume that DNSServiceRefDeallocate is called from the serial queue
12475ffb0c9bSToomas Soome             // that was passed to DNSServiceSetDispatchQueue. Hence, dispatch_source_cancel
12485ffb0c9bSToomas Soome             // should cancel all the blocks on the queue and hence there should be no more
12495ffb0c9bSToomas Soome             // callbacks when we return from this function. Setting ProcessReply to NULL
12505ffb0c9bSToomas Soome             // provides extra protection.
12515ffb0c9bSToomas Soome             sdRef->ProcessReply = NULL;
12525ffb0c9bSToomas Soome             shutdown(sdRef->sockfd, SHUT_WR);
12535ffb0c9bSToomas Soome             dispatch_source_cancel(sdRef->disp_source);
12545ffb0c9bSToomas Soome             dispatch_release(sdRef->disp_source);
12555ffb0c9bSToomas Soome             sdRef->disp_source = NULL;
12565ffb0c9bSToomas Soome         }
12575ffb0c9bSToomas Soome         // if disp_queue is set, it means it used the DNSServiceSetDispatchQueue API. In that case,
12585ffb0c9bSToomas Soome         // when the source was cancelled, the fd was closed in the handler. Currently the source
12595ffb0c9bSToomas Soome         // is cancelled only when the mDNSResponder daemon dies
12605ffb0c9bSToomas Soome         else if (!sdRef->disp_queue) dnssd_close(sdRef->sockfd);
12615ffb0c9bSToomas Soome #else
12625ffb0c9bSToomas Soome         dnssd_close(sdRef->sockfd);
12635ffb0c9bSToomas Soome #endif
12645ffb0c9bSToomas Soome         // Free DNSRecords added in DNSRegisterRecord if they have not
12655ffb0c9bSToomas Soome         // been freed in DNSRemoveRecord
12665ffb0c9bSToomas Soome         while (sdRef)
12675ffb0c9bSToomas Soome         {
12685ffb0c9bSToomas Soome             DNSServiceOp *p = sdRef;
12695ffb0c9bSToomas Soome             sdRef = sdRef->next;
12705ffb0c9bSToomas Soome             // When there is an error reading from the daemon e.g., bad fd, CallbackWithError
12715ffb0c9bSToomas Soome             // is called which sets moreptr. It might set the moreptr on a subordinate sdRef
12725ffb0c9bSToomas Soome             // but the application might call DNSServiceRefDeallocate with the main sdRef from
12735ffb0c9bSToomas Soome             // the callback. Hence, when we loop through the subordinate sdRefs, we need
12745ffb0c9bSToomas Soome             // to clear the moreptr so that CallbackWithError can terminate itself instead of
12755ffb0c9bSToomas Soome             // walking through the freed sdRefs.
12765ffb0c9bSToomas Soome             if (p->moreptr) *(p->moreptr) = 0;
12775ffb0c9bSToomas Soome             FreeDNSServiceOp(p);
12785ffb0c9bSToomas Soome         }
12795ffb0c9bSToomas Soome     }
12805ffb0c9bSToomas Soome }
12815ffb0c9bSToomas Soome 
DNSServiceGetProperty(const char * property,void * result,uint32_t * size)12825ffb0c9bSToomas Soome DNSServiceErrorType DNSSD_API DNSServiceGetProperty(const char *property, void *result, uint32_t *size)
12835ffb0c9bSToomas Soome {
1284c65ebfc7SToomas Soome     DNSServiceErrorType err;
12855ffb0c9bSToomas Soome     char *ptr;
1286c65ebfc7SToomas Soome     size_t len;
12875ffb0c9bSToomas Soome     ipc_msg_hdr *hdr;
12885ffb0c9bSToomas Soome     DNSServiceOp *tmp;
12895ffb0c9bSToomas Soome     uint32_t actualsize;
1290*472cd20dSToomas Soome     int ioresult;
12915ffb0c9bSToomas Soome 
1292c65ebfc7SToomas Soome     if (!property || !result || !size)
1293c65ebfc7SToomas Soome         return kDNSServiceErr_BadParam;
1294c65ebfc7SToomas Soome 
1295c65ebfc7SToomas Soome     len = strlen(property) + 1;
1296c65ebfc7SToomas Soome     err = ConnectToServer(&tmp, 0, getproperty_request, NULL, NULL, NULL);
12975ffb0c9bSToomas Soome     if (err) return err;
12985ffb0c9bSToomas Soome 
12995ffb0c9bSToomas Soome     hdr = create_hdr(getproperty_request, &len, &ptr, 0, tmp);
13005ffb0c9bSToomas Soome     if (!hdr) { DNSServiceRefDeallocate(tmp); return kDNSServiceErr_NoMemory; }
13015ffb0c9bSToomas Soome 
13025ffb0c9bSToomas Soome     put_string(property, &ptr);
13035ffb0c9bSToomas Soome     err = deliver_request(hdr, tmp);        // Will free hdr for us
1304cda73f64SToomas Soome     if (err) { DNSServiceRefDeallocate(tmp); return err; }
1305cda73f64SToomas Soome 
1306*472cd20dSToomas Soome     ioresult = read_all(tmp->sockfd, (char*)&actualsize, (int)sizeof(actualsize));
1307*472cd20dSToomas Soome     if (ioresult < read_all_success)
1308*472cd20dSToomas Soome     { DNSServiceRefDeallocate(tmp); return (ioresult == read_all_defunct) ? kDNSServiceErr_DefunctConnection : kDNSServiceErr_ServiceNotRunning; }
13095ffb0c9bSToomas Soome 
13105ffb0c9bSToomas Soome     actualsize = ntohl(actualsize);
1311*472cd20dSToomas Soome     ioresult = read_all(tmp->sockfd, (char*)result, actualsize < *size ? actualsize : *size);
1312*472cd20dSToomas Soome     if (ioresult < read_all_success)
1313*472cd20dSToomas Soome     { DNSServiceRefDeallocate(tmp); return (ioresult == read_all_defunct) ? kDNSServiceErr_DefunctConnection : kDNSServiceErr_ServiceNotRunning; }
13145ffb0c9bSToomas Soome     DNSServiceRefDeallocate(tmp);
13155ffb0c9bSToomas Soome 
13165ffb0c9bSToomas Soome     // Swap version result back to local process byte order
13175ffb0c9bSToomas Soome     if (!strcmp(property, kDNSServiceProperty_DaemonVersion) && *size >= 4)
13185ffb0c9bSToomas Soome         *(