1 /* -*- Mode: C; tab-width: 4 -*-
3 * Copyright (c) 2002-2013, 2015 Apple Inc. All rights reserved.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
19 - Get unicode name of machine for nice name instead of just the host name.
20 - Use the IPv6 Internet Connection Firewall API to allow IPv6 mDNS without manually changing the firewall.
21 - Get DNS server address(es) from Windows and provide them to the uDNS layer.
22 - Implement TCP support for truncated packets (only stubs now).
36 #include "CommonServices.h"
37 #include "DebugServices.h"
49 #include <ntddndis.h> // This defines the IOCTL constants.
51 #include "mDNSEmbeddedAPI.h"
52 #include "GenLinkedList.h"
53 #include "DNSCommon.h"
54 #include "mDNSWin32.h"
59 #pragma mark == Constants ==
62 //===========================================================================================================================
64 //===========================================================================================================================
66 #define DEBUG_NAME "[mDNSWin32] "
68 #define MDNS_WINDOWS_USE_IPV6_IF_ADDRS 1
69 #define MDNS_WINDOWS_ENABLE_IPV4 1
70 #define MDNS_WINDOWS_ENABLE_IPV6 1
71 #define MDNS_FIX_IPHLPAPI_PREFIX_BUG 1
72 #define MDNS_SET_HINFO_STRINGS 0
74 #define kMDNSDefaultName "My Computer"
76 #define kWinSockMajorMin 2
77 #define kWinSockMinorMin 2
79 #define kRegistryMaxKeyLength 255
80 #define kRegistryMaxValueName 16383
82 static GUID kWSARecvMsgGUID
= WSAID_WSARECVMSG
;
84 #define kIPv6IfIndexBase (10000000L)
85 #define SMBPortAsNumber 445
86 #define DEVICE_PREFIX "\\\\.\\"
89 #pragma mark == Prototypes ==
92 //===========================================================================================================================
94 //===========================================================================================================================
96 mDNSlocal mStatus
SetupNiceName( mDNS
* const inMDNS
);
97 mDNSlocal mStatus
SetupHostName( mDNS
* const inMDNS
);
98 mDNSlocal mStatus
SetupName( mDNS
* const inMDNS
);
99 mDNSlocal mStatus
SetupInterface( mDNS
* const inMDNS
, const struct ifaddrs
*inIFA
, mDNSInterfaceData
**outIFD
);
100 mDNSlocal mStatus
TearDownInterface( mDNS
* const inMDNS
, mDNSInterfaceData
*inIFD
);
101 mDNSlocal
void CALLBACK
FreeInterface( mDNSInterfaceData
*inIFD
);
102 mDNSlocal mStatus
SetupSocket( mDNS
* const inMDNS
, const struct sockaddr
*inAddr
, mDNSIPPort port
, SocketRef
*outSocketRef
);
103 mDNSlocal mStatus
SockAddrToMDNSAddr( const struct sockaddr
* const inSA
, mDNSAddr
*outIP
, mDNSIPPort
*outPort
);
104 mDNSlocal OSStatus
GetWindowsVersionString( char *inBuffer
, size_t inBufferSize
);
105 mDNSlocal
int getifaddrs( struct ifaddrs
**outAddrs
);
106 mDNSlocal
void freeifaddrs( struct ifaddrs
*inAddrs
);
109 // Platform Accessors
115 typedef struct mDNSPlatformInterfaceInfo mDNSPlatformInterfaceInfo
;
116 struct mDNSPlatformInterfaceInfo
123 mDNSexport mStatus
mDNSPlatformInterfaceNameToID( mDNS
* const inMDNS
, const char *inName
, mDNSInterfaceID
*outID
);
124 mDNSexport mStatus
mDNSPlatformInterfaceIDToInfo( mDNS
* const inMDNS
, mDNSInterfaceID inID
, mDNSPlatformInterfaceInfo
*outInfo
);
129 #define kMulticastWakeupNumTries ( 18 )
130 #define kMulticastWakeupSleepBetweenTries ( 100 )
132 typedef struct MulticastWakeupStruct
135 struct sockaddr_in addr
;
137 unsigned char data
[ 102 ];
141 } MulticastWakeupStruct
;
146 #if( MDNS_WINDOWS_USE_IPV6_IF_ADDRS )
147 mDNSlocal
int getifaddrs_ipv6( struct ifaddrs
**outAddrs
);
150 mDNSlocal
int getifaddrs_ipv4( struct ifaddrs
**outAddrs
);
152 mDNSlocal DWORD
GetPrimaryInterface();
153 mDNSlocal mStatus
AddressToIndexAndMask( struct sockaddr
* address
, uint32_t * index
, struct sockaddr
* mask
);
154 mDNSlocal mDNSBool
CanReceiveUnicast( void );
155 mDNSlocal mDNSBool
IsPointToPoint( IP_ADAPTER_UNICAST_ADDRESS
* addr
);
157 mDNSlocal mStatus
StringToAddress( mDNSAddr
* ip
, LPSTR string
);
158 mDNSlocal mStatus
RegQueryString( HKEY key
, LPCSTR param
, LPSTR
* string
, DWORD
* stringLen
, DWORD
* enabled
);
159 mDNSlocal
struct ifaddrs
* myGetIfAddrs(int refresh
);
160 mDNSlocal OSStatus
TCHARtoUTF8( const TCHAR
*inString
, char *inBuffer
, size_t inBufferSize
);
161 mDNSlocal OSStatus
WindowsLatin1toUTF8( const char *inString
, char *inBuffer
, size_t inBufferSize
);
162 mDNSlocal
void CALLBACK
TCPSocketNotification( SOCKET sock
, LPWSANETWORKEVENTS event
, void *context
);
163 mDNSlocal
void TCPCloseSocket( TCPSocket
* socket
);
164 mDNSlocal
void CALLBACK
UDPSocketNotification( SOCKET sock
, LPWSANETWORKEVENTS event
, void *context
);
165 mDNSlocal
void UDPCloseSocket( UDPSocket
* sock
);
166 mDNSlocal mStatus
SetupAddr(mDNSAddr
*ip
, const struct sockaddr
*const sa
);
167 mDNSlocal
void GetDDNSFQDN( domainname
*const fqdn
);
169 mDNSlocal
void GetDDNSDomains( DNameListElem
** domains
, LPCWSTR lpSubKey
);
171 mDNSlocal
void GetDDNSDomains( DNameListElem
** domains
, LPCSTR lpSubKey
);
173 mDNSlocal
void SetDomainSecrets( mDNS
* const inMDNS
);
174 mDNSlocal
void SetDomainSecret( mDNS
* const m
, const domainname
* inDomain
);
175 mDNSlocal VOID CALLBACK
CheckFileSharesProc( LPVOID arg
, DWORD dwTimerLowValue
, DWORD dwTimerHighValue
);
176 mDNSlocal
void CheckFileShares( mDNS
* const inMDNS
);
177 mDNSlocal
void SMBCallback(mDNS
*const m
, ServiceRecordSet
*const srs
, mStatus result
);
178 mDNSlocal mDNSu8
IsWOMPEnabledForAdapter( const char * adapterName
);
179 mDNSlocal
void SendWakeupPacket( mDNS
* const inMDNS
, LPSOCKADDR addr
, INT addrlen
, const char * buf
, INT buflen
, INT numTries
, INT msecSleep
);
180 mDNSlocal
void _cdecl
SendMulticastWakeupPacket( void *arg
);
187 #pragma mark == Globals ==
190 //===========================================================================================================================
192 //===========================================================================================================================
194 mDNSlocal mDNS_PlatformSupport gMDNSPlatformSupport
;
195 mDNSs32 mDNSPlatformOneSecond
= 0;
196 mDNSlocal UDPSocket
* gUDPSockets
= NULL
;
197 mDNSlocal
int gUDPNumSockets
= 0;
198 mDNSlocal BOOL gEnableIPv6
= TRUE
;
200 #if( MDNS_WINDOWS_USE_IPV6_IF_ADDRS )
203 ( WINAPI
* GetAdaptersAddressesFunctionPtr
)(
207 PIP_ADAPTER_ADDRESSES inAdapter
,
208 PULONG outBufferSize
);
210 mDNSlocal HMODULE gIPHelperLibraryInstance
= NULL
;
211 mDNSlocal GetAdaptersAddressesFunctionPtr gGetAdaptersAddressesFunctionPtr
= NULL
;
216 typedef ULONG_PTR HCRYPTPROV
; // WinCrypt.h, line 249
219 #ifndef CRYPT_MACHINE_KEYSET
220 # define CRYPT_MACHINE_KEYSET 0x00000020
223 #ifndef CRYPT_NEWKEYSET
224 # define CRYPT_NEWKEYSET 0x00000008
227 #ifndef PROV_RSA_FULL
228 # define PROV_RSA_FULL 1
231 typedef BOOL (__stdcall
*fnCryptGenRandom
)( HCRYPTPROV
, DWORD
, BYTE
* );
232 typedef BOOL (__stdcall
*fnCryptAcquireContext
)( HCRYPTPROV
*, LPCTSTR
, LPCTSTR
, DWORD
, DWORD
);
233 typedef BOOL (__stdcall
*fnCryptReleaseContext
)(HCRYPTPROV
, DWORD
);
235 static fnCryptAcquireContext g_lpCryptAcquireContext
= NULL
;
236 static fnCryptReleaseContext g_lpCryptReleaseContext
= NULL
;
237 static fnCryptGenRandom g_lpCryptGenRandom
= NULL
;
238 static HINSTANCE g_hAAPI32
= NULL
;
239 static HCRYPTPROV g_hProvider
= ( ULONG_PTR
) NULL
;
242 typedef DNSServiceErrorType ( DNSSD_API
*DNSServiceRegisterFunc
)
244 DNSServiceRef
*sdRef
,
245 DNSServiceFlags flags
,
246 uint32_t interfaceIndex
,
247 const char *name
, /* may be NULL */
249 const char *domain
, /* may be NULL */
250 const char *host
, /* may be NULL */
253 const void *txtRecord
, /* may be NULL */
254 DNSServiceRegisterReply callBack
, /* may be NULL */
255 void *context
/* may be NULL */
259 typedef void ( DNSSD_API
*DNSServiceRefDeallocateFunc
)( DNSServiceRef sdRef
);
261 mDNSlocal HMODULE gDNSSDLibrary
= NULL
;
262 mDNSlocal DNSServiceRegisterFunc gDNSServiceRegister
= NULL
;
263 mDNSlocal DNSServiceRefDeallocateFunc gDNSServiceRefDeallocate
= NULL
;
264 mDNSlocal HANDLE gSMBThread
= NULL
;
265 mDNSlocal HANDLE gSMBThreadRegisterEvent
= NULL
;
266 mDNSlocal HANDLE gSMBThreadDeregisterEvent
= NULL
;
267 mDNSlocal HANDLE gSMBThreadStopEvent
= NULL
;
268 mDNSlocal HANDLE gSMBThreadQuitEvent
= NULL
;
270 #define kSMBStopEvent ( WAIT_OBJECT_0 + 0 )
271 #define kSMBRegisterEvent ( WAIT_OBJECT_0 + 1 )
272 #define kSMBDeregisterEvent ( WAIT_OBJECT_0 + 2 )
276 #pragma mark == Platform Support ==
279 //===========================================================================================================================
281 //===========================================================================================================================
283 mDNSexport mStatus
mDNSPlatformInit( mDNS
* const inMDNS
)
286 OSVERSIONINFO osInfo
;
290 struct sockaddr_in sa4
;
291 struct sockaddr_in6 sa6
;
296 dlog( kDebugLevelTrace
, DEBUG_NAME
"platform init\n" );
298 // Initialize variables. If the PlatformSupport pointer is not null then just assume that a non-Apple client is
299 // calling mDNS_Init and wants to provide its own storage for the platform-specific data so do not overwrite it.
301 mDNSPlatformMemZero( &gMDNSPlatformSupport
, sizeof( gMDNSPlatformSupport
) );
302 if( !inMDNS
->p
) inMDNS
->p
= &gMDNSPlatformSupport
;
303 inMDNS
->p
->mainThread
= OpenThread( THREAD_ALL_ACCESS
, FALSE
, GetCurrentThreadId() );
304 require_action( inMDNS
->p
->mainThread
, exit
, err
= mStatus_UnknownErr
);
305 inMDNS
->p
->checkFileSharesTimer
= CreateWaitableTimer( NULL
, FALSE
, NULL
);
306 require_action( inMDNS
->p
->checkFileSharesTimer
, exit
, err
= mStatus_UnknownErr
);
307 inMDNS
->p
->checkFileSharesTimeout
= 10; // Retry time for CheckFileShares() in seconds
308 mDNSPlatformOneSecond
= 1000; // Use milliseconds as the quantum of time
310 // Get OS version info
312 osInfo
.dwOSVersionInfoSize
= sizeof( OSVERSIONINFO
);
313 ok
= GetVersionEx( &osInfo
);
314 err
= translate_errno( ok
, (OSStatus
) GetLastError(), kUnknownErr
);
315 require_noerr( err
, exit
);
316 inMDNS
->p
->osMajorVersion
= osInfo
.dwMajorVersion
;
317 inMDNS
->p
->osMinorVersion
= osInfo
.dwMinorVersion
;
319 // Don't enable IPv6 on anything less recent than Windows Vista
321 if ( inMDNS
->p
->osMajorVersion
< 6 )
326 // Startup WinSock 2.2 or later.
328 err
= WSAStartup( MAKEWORD( kWinSockMajorMin
, kWinSockMinorMin
), &wsaData
);
329 require_noerr( err
, exit
);
331 supported
= ( ( LOBYTE( wsaData
.wVersion
) == kWinSockMajorMin
) && ( HIBYTE( wsaData
.wVersion
) == kWinSockMinorMin
) );
332 require_action( supported
, exit
, err
= mStatus_UnsupportedErr
);
334 inMDNS
->CanReceiveUnicastOn5353
= CanReceiveUnicast();
336 // Setup the HINFO HW strings.
337 //<rdar://problem/7245119> device-info should have model=Windows
339 strcpy_s( ( char* ) &inMDNS
->HIHardware
.c
[ 1 ], sizeof( inMDNS
->HIHardware
.c
) - 2, "Windows" );
340 inMDNS
->HIHardware
.c
[ 0 ] = ( mDNSu8
) mDNSPlatformStrLen( &inMDNS
->HIHardware
.c
[ 1 ] );
341 dlog( kDebugLevelInfo
, DEBUG_NAME
"HIHardware: %#s\n", inMDNS
->HIHardware
.c
);
343 // Setup the HINFO SW strings.
344 #if ( MDNS_SET_HINFO_STRINGS )
345 mDNS_snprintf( (char *) &inMDNS
->HISoftware
.c
[ 1 ], sizeof( inMDNS
->HISoftware
.c
) - 2,
346 "mDNSResponder (%s %s)", __DATE__
, __TIME__
);
347 inMDNS
->HISoftware
.c
[ 0 ] = (mDNSu8
) mDNSPlatformStrLen( &inMDNS
->HISoftware
.c
[ 1 ] );
348 dlog( kDebugLevelInfo
, DEBUG_NAME
"HISoftware: %#s\n", inMDNS
->HISoftware
.c
);
351 // Set up the IPv4 unicast socket
353 inMDNS
->p
->unicastSock4
.fd
= INVALID_SOCKET
;
354 inMDNS
->p
->unicastSock4
.recvMsgPtr
= NULL
;
355 inMDNS
->p
->unicastSock4
.ifd
= NULL
;
356 inMDNS
->p
->unicastSock4
.next
= NULL
;
357 inMDNS
->p
->unicastSock4
.m
= inMDNS
;
359 #if ( MDNS_WINDOWS_ENABLE_IPV4 )
361 sa4
.sin_family
= AF_INET
;
362 sa4
.sin_addr
.s_addr
= INADDR_ANY
;
363 err
= SetupSocket( inMDNS
, (const struct sockaddr
*) &sa4
, zeroIPPort
, &inMDNS
->p
->unicastSock4
.fd
);
365 sa4len
= sizeof( sa4
);
366 err
= getsockname( inMDNS
->p
->unicastSock4
.fd
, (struct sockaddr
*) &sa4
, &sa4len
);
367 require_noerr( err
, exit
);
368 inMDNS
->p
->unicastSock4
.port
.NotAnInteger
= sa4
.sin_port
;
369 inMDNS
->UnicastPort4
= inMDNS
->p
->unicastSock4
.port
;
370 err
= WSAIoctl( inMDNS
->p
->unicastSock4
.fd
, SIO_GET_EXTENSION_FUNCTION_POINTER
, &kWSARecvMsgGUID
, sizeof( kWSARecvMsgGUID
), &inMDNS
->p
->unicastSock4
.recvMsgPtr
, sizeof( inMDNS
->p
->unicastSock4
.recvMsgPtr
), &size
, NULL
, NULL
);
374 inMDNS
->p
->unicastSock4
.recvMsgPtr
= NULL
;
377 err
= mDNSPollRegisterSocket( inMDNS
->p
->unicastSock4
.fd
, FD_READ
, UDPSocketNotification
, &inMDNS
->p
->unicastSock4
);
378 require_noerr( err
, exit
);
382 // Set up the IPv6 unicast socket
384 inMDNS
->p
->unicastSock6
.fd
= INVALID_SOCKET
;
385 inMDNS
->p
->unicastSock6
.recvMsgPtr
= NULL
;
386 inMDNS
->p
->unicastSock6
.ifd
= NULL
;
387 inMDNS
->p
->unicastSock6
.next
= NULL
;
388 inMDNS
->p
->unicastSock6
.m
= inMDNS
;
390 #if ( MDNS_WINDOWS_ENABLE_IPV6 )
394 sa6
.sin6_family
= AF_INET6
;
395 sa6
.sin6_addr
= in6addr_any
;
396 sa6
.sin6_scope_id
= 0;
398 // This call will fail if the machine hasn't installed IPv6. In that case,
399 // the error will be WSAEAFNOSUPPORT.
401 err
= SetupSocket( inMDNS
, (const struct sockaddr
*) &sa6
, zeroIPPort
, &inMDNS
->p
->unicastSock6
.fd
);
402 require_action( !err
|| ( err
== WSAEAFNOSUPPORT
), exit
, err
= (mStatus
) WSAGetLastError() );
405 // If we weren't able to create the socket (because IPv6 hasn't been installed) don't do this
407 if ( inMDNS
->p
->unicastSock6
.fd
!= INVALID_SOCKET
)
409 sa6len
= sizeof( sa6
);
410 err
= getsockname( inMDNS
->p
->unicastSock6
.fd
, (struct sockaddr
*) &sa6
, &sa6len
);
411 require_noerr( err
, exit
);
412 inMDNS
->p
->unicastSock6
.port
.NotAnInteger
= sa6
.sin6_port
;
413 inMDNS
->UnicastPort6
= inMDNS
->p
->unicastSock6
.port
;
415 err
= WSAIoctl( inMDNS
->p
->unicastSock6
.fd
, SIO_GET_EXTENSION_FUNCTION_POINTER
, &kWSARecvMsgGUID
, sizeof( kWSARecvMsgGUID
), &inMDNS
->p
->unicastSock6
.recvMsgPtr
, sizeof( inMDNS
->p
->unicastSock6
.recvMsgPtr
), &size
, NULL
, NULL
);
419 inMDNS
->p
->unicastSock6
.recvMsgPtr
= NULL
;
422 err
= mDNSPollRegisterSocket( inMDNS
->p
->unicastSock6
.fd
, FD_READ
, UDPSocketNotification
, &inMDNS
->p
->unicastSock6
);
423 require_noerr( err
, exit
);
429 // Notify core of domain secret keys
431 SetDomainSecrets( inMDNS
);
435 mDNSCoreInitComplete( inMDNS
, err
);
442 mDNSPlatformClose( inMDNS
);
445 dlog( kDebugLevelTrace
, DEBUG_NAME
"platform init done (err=%d %m)\n", err
, err
);
449 //===========================================================================================================================
451 //===========================================================================================================================
453 mDNSexport
void mDNSPlatformClose( mDNS
* const inMDNS
)
457 dlog( kDebugLevelTrace
, DEBUG_NAME
"platform close\n" );
460 if ( gSMBThread
!= NULL
)
462 dlog( kDebugLevelTrace
, DEBUG_NAME
"tearing down smb registration thread\n" );
463 SetEvent( gSMBThreadStopEvent
);
465 if ( WaitForSingleObject( gSMBThreadQuitEvent
, 5 * 1000 ) == WAIT_OBJECT_0
)
467 if ( gSMBThreadQuitEvent
)
469 CloseHandle( gSMBThreadQuitEvent
);
470 gSMBThreadQuitEvent
= NULL
;
473 if ( gSMBThreadStopEvent
)
475 CloseHandle( gSMBThreadStopEvent
);
476 gSMBThreadStopEvent
= NULL
;
479 if ( gSMBThreadDeregisterEvent
)
481 CloseHandle( gSMBThreadDeregisterEvent
);
482 gSMBThreadDeregisterEvent
= NULL
;
485 if ( gSMBThreadRegisterEvent
)
487 CloseHandle( gSMBThreadRegisterEvent
);
488 gSMBThreadRegisterEvent
= NULL
;
493 FreeLibrary( gDNSSDLibrary
);
494 gDNSSDLibrary
= NULL
;
499 LogMsg( "Unable to stop SMBThread" );
502 inMDNS
->p
->smbFileSharing
= mDNSfalse
;
503 inMDNS
->p
->smbPrintSharing
= mDNSfalse
;
506 // Tear everything down in reverse order to how it was set up.
508 err
= TearDownInterfaceList( inMDNS
);
510 check( !inMDNS
->p
->inactiveInterfaceList
);
512 #if ( MDNS_WINDOWS_ENABLE_IPV4 )
514 UDPCloseSocket( &inMDNS
->p
->unicastSock4
);
518 #if ( MDNS_WINDOWS_ENABLE_IPV6 )
522 UDPCloseSocket( &inMDNS
->p
->unicastSock6
);
527 // Free the DLL needed for IPv6 support.
529 #if( MDNS_WINDOWS_USE_IPV6_IF_ADDRS )
530 if( gIPHelperLibraryInstance
)
532 gGetAdaptersAddressesFunctionPtr
= NULL
;
534 FreeLibrary( gIPHelperLibraryInstance
);
535 gIPHelperLibraryInstance
= NULL
;
541 // Release any resources
543 if ( g_hProvider
&& g_lpCryptReleaseContext
)
545 ( g_lpCryptReleaseContext
)( g_hProvider
, 0 );
548 // Free the AdvApi32.dll
550 FreeLibrary( g_hAAPI32
);
552 // And reset all the data
554 g_lpCryptAcquireContext
= NULL
;
555 g_lpCryptReleaseContext
= NULL
;
556 g_lpCryptGenRandom
= NULL
;
557 g_hProvider
= ( ULONG_PTR
) NULL
;
563 dlog( kDebugLevelTrace
, DEBUG_NAME
"platform close done\n" );
566 //===========================================================================================================================
568 //===========================================================================================================================
570 mDNSexport
void mDNSPlatformLock( const mDNS
* const inMDNS
)
575 //===========================================================================================================================
576 // mDNSPlatformUnlock
577 //===========================================================================================================================
579 mDNSexport
void mDNSPlatformUnlock( const mDNS
* const inMDNS
)
584 //===========================================================================================================================
585 // mDNSPlatformStrCopy
586 //===========================================================================================================================
588 mDNSexport
void mDNSPlatformStrCopy( void *inDst
, const void *inSrc
)
593 strcpy( (char *) inDst
, (const char*) inSrc
);
596 //===========================================================================================================================
597 // mDNSPlatformStrLCopy
598 //===========================================================================================================================
600 mDNSexport mDNSu32
mDNSPlatformStrLCopy( void *inDst
, const void *inSrc
, mDNSu32 inSize
)
602 const char * src
= (const char *) inSrc
;
607 char * dst
= (char *) inDst
;
609 for( n
= inSize
- 1; n
> 0; --n
)
611 if( ( *dst
++ = *src
++ ) == '\0' )
613 // Null terminator encountered, so exit.
620 while( *src
++ != '\0' )
622 // Stop at null terminator.
626 return( (mDNSu32
)( src
- (const char *) inSrc
) - 1 );
629 //===========================================================================================================================
630 // mDNSPlatformStrLen
631 //===========================================================================================================================
633 mDNSexport mDNSu32
mDNSPlatformStrLen( const void *inSrc
)
637 return( (mDNSu32
) strlen( (const char *) inSrc
) );
640 //===========================================================================================================================
641 // mDNSPlatformMemCopy
642 //===========================================================================================================================
644 mDNSexport
void mDNSPlatformMemCopy( void *inDst
, const void *inSrc
, mDNSu32 inSize
)
649 memcpy( inDst
, inSrc
, inSize
);
652 //===========================================================================================================================
653 // mDNSPlatformMemSame
654 //===========================================================================================================================
656 mDNSexport mDNSBool
mDNSPlatformMemSame( const void *inDst
, const void *inSrc
, mDNSu32 inSize
)
661 return( (mDNSBool
)( memcmp( inSrc
, inDst
, inSize
) == 0 ) );
664 //===========================================================================================================================
665 // mDNSPlatformMemCmp
666 //===========================================================================================================================
668 mDNSexport
int mDNSPlatformMemCmp( const void *inDst
, const void *inSrc
, mDNSu32 inSize
)
673 return( memcmp( inSrc
, inDst
, inSize
) );
676 mDNSexport
void mDNSPlatformQsort(void *base
, int nel
, int width
, int (*compar
)(const void *, const void *))
684 // DNSSEC stub functions
685 mDNSexport
void VerifySignature(mDNS
*const m
, DNSSECVerifier
*dv
, DNSQuestion
*q
)
692 mDNSexport mDNSBool
AddNSECSForCacheRecord(mDNS
*const m
, CacheRecord
*crlist
, CacheRecord
*negcr
, mDNSu8 rcode
)
701 mDNSexport
void BumpDNSSECStats(mDNS
*const m
, DNSSECStatsAction action
, DNSSECStatsType type
, mDNSu32 value
)
709 // Proxy stub functions
710 mDNSexport mDNSu8
*DNSProxySetAttributes(DNSQuestion
*q
, DNSMessageHeader
*h
, DNSMessage
*msg
, mDNSu8
*ptr
, mDNSu8
*limit
)
721 mDNSexport
void DNSProxyInit(mDNS
*const m
, mDNSu32 IpIfArr
[], mDNSu32 OpIf
)
728 mDNSexport
void DNSProxyTerminate(mDNS
*const m
)
733 //===========================================================================================================================
734 // mDNSPlatformMemZero
735 //===========================================================================================================================
737 mDNSexport
void mDNSPlatformMemZero( void *inDst
, mDNSu32 inSize
)
741 memset( inDst
, 0, inSize
);
744 //===========================================================================================================================
745 // mDNSPlatformMemAllocate
746 //===========================================================================================================================
748 mDNSexport
void * mDNSPlatformMemAllocate( mDNSu32 inSize
)
754 mem
= malloc( inSize
);
760 //===========================================================================================================================
761 // mDNSPlatformMemFree
762 //===========================================================================================================================
764 mDNSexport
void mDNSPlatformMemFree( void *inMem
)
771 //===========================================================================================================================
772 // mDNSPlatformRandomNumber
773 //===========================================================================================================================
775 mDNSexport mDNSu32
mDNSPlatformRandomNumber(void)
777 unsigned int randomNumber
;
780 err
= rand_s( &randomNumber
);
781 require_noerr( err
, exit
);
787 randomNumber
= rand();
790 return ( mDNSu32
) randomNumber
;
793 //===========================================================================================================================
794 // mDNSPlatformTimeInit
795 //===========================================================================================================================
797 mDNSexport mStatus
mDNSPlatformTimeInit( void )
799 // No special setup is required on Windows -- we just use GetTickCount().
800 return( mStatus_NoError
);
803 //===========================================================================================================================
804 // mDNSPlatformRawTime
805 //===========================================================================================================================
807 mDNSexport mDNSs32
mDNSPlatformRawTime( void )
809 return( (mDNSs32
) GetTickCount() );
812 //===========================================================================================================================
814 //===========================================================================================================================
816 mDNSexport mDNSs32
mDNSPlatformUTC( void )
818 return ( mDNSs32
) time( NULL
);
821 //===========================================================================================================================
822 // mDNSPlatformInterfaceNameToID
823 //===========================================================================================================================
825 mDNSexport mStatus
mDNSPlatformInterfaceNameToID( mDNS
* const inMDNS
, const char *inName
, mDNSInterfaceID
*outID
)
828 mDNSInterfaceData
* ifd
;
834 // Search for an interface with the specified name,
836 for( ifd
= inMDNS
->p
->interfaceList
; ifd
; ifd
= ifd
->next
)
838 if( strcmp( ifd
->name
, inName
) == 0 )
843 require_action_quiet( ifd
, exit
, err
= mStatus_NoSuchNameErr
);
849 *outID
= (mDNSInterfaceID
) ifd
;
851 err
= mStatus_NoError
;
857 //===========================================================================================================================
858 // mDNSPlatformInterfaceIDToInfo
859 //===========================================================================================================================
861 mDNSexport mStatus
mDNSPlatformInterfaceIDToInfo( mDNS
* const inMDNS
, mDNSInterfaceID inID
, mDNSPlatformInterfaceInfo
*outInfo
)
864 mDNSInterfaceData
* ifd
;
870 // Search for an interface with the specified ID,
872 for( ifd
= inMDNS
->p
->interfaceList
; ifd
; ifd
= ifd
->next
)
874 if( ifd
== (mDNSInterfaceData
*) inID
)
879 require_action_quiet( ifd
, exit
, err
= mStatus_NoSuchNameErr
);
883 outInfo
->name
= ifd
->name
;
884 outInfo
->ip
= ifd
->interfaceInfo
.ip
;
885 err
= mStatus_NoError
;
891 //===========================================================================================================================
892 // mDNSPlatformInterfaceIDfromInterfaceIndex
893 //===========================================================================================================================
895 mDNSexport mDNSInterfaceID
mDNSPlatformInterfaceIDfromInterfaceIndex( mDNS
* const inMDNS
, mDNSu32 inIndex
)
900 if( inIndex
== kDNSServiceInterfaceIndexLocalOnly
)
902 id
= mDNSInterface_LocalOnly
;
904 else if( inIndex
!= 0 )
906 mDNSInterfaceData
* ifd
;
908 for( ifd
= inMDNS
->p
->interfaceList
; ifd
; ifd
= ifd
->next
)
910 if( ( ifd
->scopeID
== inIndex
) && ifd
->interfaceInfo
.InterfaceActive
)
912 id
= ifd
->interfaceInfo
.InterfaceID
;
921 //===========================================================================================================================
922 // mDNSPlatformInterfaceIndexfromInterfaceID
923 //===========================================================================================================================
925 mDNSexport mDNSu32
mDNSPlatformInterfaceIndexfromInterfaceID( mDNS
* const inMDNS
, mDNSInterfaceID inID
, mDNSBool suppressNetworkChange
)
929 (void) suppressNetworkChange
;
932 if( inID
== mDNSInterface_LocalOnly
)
934 index
= (mDNSu32
) kDNSServiceInterfaceIndexLocalOnly
;
938 mDNSInterfaceData
* ifd
;
940 // Search active interfaces.
941 for( ifd
= inMDNS
->p
->interfaceList
; ifd
; ifd
= ifd
->next
)
943 if( (mDNSInterfaceID
) ifd
== inID
)
945 index
= ifd
->scopeID
;
950 // Search inactive interfaces too so remove events for inactive interfaces report the old interface index.
954 for( ifd
= inMDNS
->p
->inactiveInterfaceList
; ifd
; ifd
= ifd
->next
)
956 if( (mDNSInterfaceID
) ifd
== inID
)
958 index
= ifd
->scopeID
;
968 //===========================================================================================================================
969 // mDNSPlatformTCPSocket
970 //===========================================================================================================================
973 mDNSPlatformTCPSocket
976 TCPSocketFlags flags
,
978 mDNSBool useBackgroundTrafficClass
981 TCPSocket
* sock
= NULL
;
982 u_long on
= 1; // "on" for setsockopt
983 struct sockaddr_in saddr
;
985 mStatus err
= mStatus_NoError
;
988 DEBUG_UNUSED( useBackgroundTrafficClass
);
990 require_action( flags
== 0, exit
, err
= mStatus_UnsupportedErr
);
992 // Setup connection data object
994 sock
= (TCPSocket
*) malloc( sizeof( TCPSocket
) );
995 require_action( sock
, exit
, err
= mStatus_NoMemoryErr
);
996 mDNSPlatformMemZero( sock
, sizeof( TCPSocket
) );
997 sock
->fd
= INVALID_SOCKET
;
1001 mDNSPlatformMemZero(&saddr
, sizeof(saddr
));
1002 saddr
.sin_family
= AF_INET
;
1003 saddr
.sin_addr
.s_addr
= htonl( INADDR_ANY
);
1004 saddr
.sin_port
= port
->NotAnInteger
;
1006 // Create the socket
1008 sock
->fd
= socket(AF_INET
, SOCK_STREAM
, 0);
1009 err
= translate_errno( sock
->fd
!= INVALID_SOCKET
, WSAGetLastError(), mStatus_UnknownErr
);
1010 require_noerr( err
, exit
);
1014 err
= bind( sock
->fd
, ( struct sockaddr
* ) &saddr
, sizeof( saddr
) );
1015 err
= translate_errno( err
== 0, WSAGetLastError(), mStatus_UnknownErr
);
1016 require_noerr( err
, exit
);
1018 // Set it to be non-blocking
1020 err
= ioctlsocket( sock
->fd
, FIONBIO
, &on
);
1021 err
= translate_errno( err
== 0, WSAGetLastError(), mStatus_UnknownErr
);
1022 require_noerr( err
, exit
);
1026 mDNSPlatformMemZero( &saddr
, sizeof( saddr
) );
1027 len
= sizeof( saddr
);
1029 err
= getsockname( sock
->fd
, ( struct sockaddr
* ) &saddr
, &len
);
1030 err
= translate_errno( err
== 0, WSAGetLastError(), mStatus_UnknownErr
);
1031 require_noerr( err
, exit
);
1033 port
->NotAnInteger
= saddr
.sin_port
;
1039 TCPCloseSocket( sock
);
1047 //===========================================================================================================================
1048 // mDNSPlatformTCPConnect
1049 //===========================================================================================================================
1052 mDNSPlatformTCPConnect
1055 const mDNSAddr
* inDstIP
,
1056 mDNSOpaque16 inDstPort
,
1057 domainname
* hostname
,
1058 mDNSInterfaceID inInterfaceID
,
1059 TCPConnectionCallback inCallback
,
1063 struct sockaddr_in saddr
;
1064 mStatus err
= mStatus_NoError
;
1066 DEBUG_UNUSED( hostname
);
1067 DEBUG_UNUSED( inInterfaceID
);
1069 if ( inDstIP
->type
!= mDNSAddrType_IPv4
)
1071 LogMsg("ERROR: mDNSPlatformTCPConnect - attempt to connect to an IPv6 address: operation not supported");
1072 return mStatus_UnknownErr
;
1075 // Setup connection data object
1077 sock
->userCallback
= inCallback
;
1078 sock
->userContext
= inContext
;
1080 mDNSPlatformMemZero(&saddr
, sizeof(saddr
));
1081 saddr
.sin_family
= AF_INET
;
1082 saddr
.sin_port
= inDstPort
.NotAnInteger
;
1083 memcpy(&saddr
.sin_addr
, &inDstIP
->ip
.v4
.NotAnInteger
, sizeof(saddr
.sin_addr
));
1085 // Try and do connect
1087 err
= connect( sock
->fd
, ( struct sockaddr
* ) &saddr
, sizeof( saddr
) );
1088 require_action( !err
|| ( WSAGetLastError() == WSAEWOULDBLOCK
), exit
, err
= mStatus_ConnFailed
);
1089 sock
->connected
= !err
? TRUE
: FALSE
;
1091 err
= mDNSPollRegisterSocket( sock
->fd
, FD_CONNECT
| FD_READ
| FD_CLOSE
, TCPSocketNotification
, sock
);
1092 require_noerr( err
, exit
);
1098 err
= sock
->connected
? mStatus_ConnEstablished
: mStatus_ConnPending
;
1104 //===========================================================================================================================
1105 // mDNSPlatformTCPAccept
1106 //===========================================================================================================================
1108 mDNSexport TCPSocket
*mDNSPlatformTCPAccept( TCPSocketFlags flags
, int fd
)
1110 TCPSocket
* sock
= NULL
;
1111 mStatus err
= mStatus_NoError
;
1113 require_action( !flags
, exit
, err
= mStatus_UnsupportedErr
);
1115 sock
= malloc( sizeof( TCPSocket
) );
1116 require_action( sock
, exit
, err
= mStatus_NoMemoryErr
);
1118 mDNSPlatformMemZero( sock
, sizeof( *sock
) );
1121 sock
->flags
= flags
;
1134 //===========================================================================================================================
1135 // mDNSPlatformTCPCloseConnection
1136 //===========================================================================================================================
1138 mDNSexport
void mDNSPlatformTCPCloseConnection( TCPSocket
*sock
)
1144 dlog( kDebugLevelChatty
, DEBUG_NAME
"mDNSPlatformTCPCloseConnection 0x%x:%d\n", sock
, sock
->fd
);
1146 if ( sock
->fd
!= INVALID_SOCKET
)
1148 mDNSPollUnregisterSocket( sock
->fd
);
1149 closesocket( sock
->fd
);
1150 sock
->fd
= INVALID_SOCKET
;
1157 //===========================================================================================================================
1158 // mDNSPlatformReadTCP
1159 //===========================================================================================================================
1161 mDNSexport
long mDNSPlatformReadTCP( TCPSocket
*sock
, void *inBuffer
, unsigned long inBufferSize
, mDNSBool
* closed
)
1166 *closed
= mDNSfalse
;
1167 nread
= recv( sock
->fd
, inBuffer
, inBufferSize
, 0 );
1168 err
= translate_errno( ( nread
>= 0 ), WSAGetLastError(), mStatus_UnknownErr
);
1172 dlog( kDebugLevelChatty
, DEBUG_NAME
"mDNSPlatformReadTCP: 0x%x:%d read %d bytes\n", sock
, sock
->fd
, nread
);
1178 else if ( err
== WSAECONNRESET
)
1183 else if ( err
== WSAEWOULDBLOCK
)
1189 LogMsg( "ERROR: mDNSPlatformReadTCP - recv: %d\n", err
);
1196 //===========================================================================================================================
1197 // mDNSPlatformWriteTCP
1198 //===========================================================================================================================
1200 mDNSexport
long mDNSPlatformWriteTCP( TCPSocket
*sock
, const char *inMsg
, unsigned long inMsgSize
)
1205 nsent
= send( sock
->fd
, inMsg
, inMsgSize
, 0 );
1207 err
= translate_errno( ( nsent
>= 0 ) || ( WSAGetLastError() == WSAEWOULDBLOCK
), WSAGetLastError(), mStatus_UnknownErr
);
1208 require_noerr( err
, exit
);
1220 //===========================================================================================================================
1221 // mDNSPlatformTCPGetFD
1222 //===========================================================================================================================
1224 mDNSexport
int mDNSPlatformTCPGetFD(TCPSocket
*sock
)
1226 return ( int ) sock
->fd
;
1229 //===========================================================================================================================
1230 // TCPSocketNotification
1231 //===========================================================================================================================
1233 mDNSlocal
void CALLBACK
1234 TCPSocketNotification( SOCKET sock
, LPWSANETWORKEVENTS event
, void *context
)
1236 TCPSocket
*tcpSock
= ( TCPSocket
* ) context
;
1237 TCPConnectionCallback callback
;
1240 DEBUG_UNUSED( sock
);
1242 require_action( tcpSock
, exit
, err
= mStatus_BadParamErr
);
1243 callback
= ( TCPConnectionCallback
) tcpSock
->userCallback
;
1244 require_action( callback
, exit
, err
= mStatus_BadParamErr
);
1246 if ( event
&& ( event
->lNetworkEvents
& FD_CONNECT
) )
1248 if ( event
->iErrorCode
[ FD_CONNECT_BIT
] == 0 )
1250 callback( tcpSock
, tcpSock
->userContext
, mDNStrue
, 0 );
1251 tcpSock
->connected
= mDNStrue
;
1255 callback( tcpSock
, tcpSock
->userContext
, mDNSfalse
, event
->iErrorCode
[ FD_CONNECT_BIT
] );
1260 callback( tcpSock
, tcpSock
->userContext
, mDNSfalse
, 0 );
1268 //===========================================================================================================================
1269 // mDNSPlatformUDPSocket
1270 //===========================================================================================================================
1272 mDNSexport UDPSocket
* mDNSPlatformUDPSocket(mDNS
*const m
, const mDNSIPPort requestedport
)
1274 UDPSocket
* sock
= NULL
;
1275 mDNSIPPort port
= requestedport
;
1276 mStatus err
= mStatus_NoError
;
1279 // Setup connection data object
1281 sock
= ( UDPSocket
* ) malloc(sizeof( UDPSocket
) );
1282 require_action( sock
, exit
, err
= mStatus_NoMemoryErr
);
1283 memset( sock
, 0, sizeof( UDPSocket
) );
1285 // Create the socket
1287 sock
->fd
= INVALID_SOCKET
;
1288 sock
->recvMsgPtr
= m
->p
->unicastSock4
.recvMsgPtr
;
1289 sock
->addr
= m
->p
->unicastSock4
.addr
;
1293 // Try at most 10000 times to get a unique random port
1295 for (i
=0; i
<10000; i
++)
1297 struct sockaddr_in saddr
;
1299 saddr
.sin_family
= AF_INET
;
1300 saddr
.sin_addr
.s_addr
= 0;
1302 // The kernel doesn't do cryptographically strong random port
1303 // allocation, so we do it ourselves here
1305 if (mDNSIPPortIsZero(requestedport
))
1307 port
= mDNSOpaque16fromIntVal( ( mDNSu16
) ( 0xC000 + mDNSRandom(0x3FFF) ) );
1310 saddr
.sin_port
= port
.NotAnInteger
;
1312 err
= SetupSocket(m
, ( struct sockaddr
* ) &saddr
, port
, &sock
->fd
);
1316 require_noerr( err
, exit
);
1322 // Arm the completion routine
1324 err
= mDNSPollRegisterSocket( sock
->fd
, FD_READ
, UDPSocketNotification
, sock
);
1325 require_noerr( err
, exit
);
1329 sock
->next
= gUDPSockets
;
1337 UDPCloseSocket( sock
);
1345 //===========================================================================================================================
1346 // mDNSPlatformUDPClose
1347 //===========================================================================================================================
1349 mDNSexport
void mDNSPlatformUDPClose( UDPSocket
*sock
)
1351 UDPSocket
* current
= gUDPSockets
;
1352 UDPSocket
* last
= NULL
;
1356 if ( current
== sock
)
1360 gUDPSockets
= sock
->next
;
1364 last
->next
= sock
->next
;
1367 UDPCloseSocket( sock
);
1376 current
= current
->next
;
1380 //===========================================================================================================================
1381 // mDNSPlatformSendUDP
1382 //===========================================================================================================================
1385 mDNSPlatformSendUDP(
1386 const mDNS
* const inMDNS
,
1387 const void * const inMsg
,
1388 const mDNSu8
* const inMsgEnd
,
1389 mDNSInterfaceID inInterfaceID
,
1390 UDPSocket
* inSrcSocket
,
1391 const mDNSAddr
* inDstIP
,
1392 mDNSIPPort inDstPort
,
1393 mDNSBool useBackgroundTrafficClass
)
1395 SOCKET sendingsocket
= INVALID_SOCKET
;
1396 mStatus err
= mStatus_NoError
;
1397 mDNSInterfaceData
* ifd
= (mDNSInterfaceData
*) inInterfaceID
;
1398 struct sockaddr_storage addr
;
1401 DEBUG_USE_ONLY( inMDNS
);
1402 DEBUG_USE_ONLY( useBackgroundTrafficClass
);
1404 n
= (int)( inMsgEnd
- ( (const mDNSu8
* const) inMsg
) );
1410 dlog( kDebugLevelChatty
, DEBUG_NAME
"platform send %d bytes to %#a:%u\n", n
, inDstIP
, ntohs( inDstPort
.NotAnInteger
) );
1412 if( inDstIP
->type
== mDNSAddrType_IPv4
)
1414 struct sockaddr_in
* sa4
;
1416 sa4
= (struct sockaddr_in
*) &addr
;
1417 sa4
->sin_family
= AF_INET
;
1418 sa4
->sin_port
= inDstPort
.NotAnInteger
;
1419 sa4
->sin_addr
.s_addr
= inDstIP
->ip
.v4
.NotAnInteger
;
1420 sendingsocket
= ifd
? ifd
->sock
.fd
: inMDNS
->p
->unicastSock4
.fd
;
1422 if (inSrcSocket
) { sendingsocket
= inSrcSocket
->fd
; debugf("mDNSPlatformSendUDP using port %d, static port %d, sock %d", mDNSVal16(inSrcSocket
->port
), inMDNS
->p
->unicastSock4
.fd
, sendingsocket
); }
1424 else if( inDstIP
->type
== mDNSAddrType_IPv6
)
1426 struct sockaddr_in6
* sa6
;
1428 sa6
= (struct sockaddr_in6
*) &addr
;
1429 sa6
->sin6_family
= AF_INET6
;
1430 sa6
->sin6_port
= inDstPort
.NotAnInteger
;
1431 sa6
->sin6_flowinfo
= 0;
1432 sa6
->sin6_addr
= *( (struct in6_addr
*) &inDstIP
->ip
.v6
);
1433 sa6
->sin6_scope_id
= 0; // Windows requires the scope ID to be zero. IPV6_MULTICAST_IF specifies interface.
1434 sendingsocket
= ifd
? ifd
->sock
.fd
: inMDNS
->p
->unicastSock6
.fd
;
1438 dlog( kDebugLevelError
, DEBUG_NAME
"%s: dst is not an IPv4 or IPv6 address (type=%d)\n", __ROUTINE__
, inDstIP
->type
);
1439 err
= mStatus_BadParamErr
;
1443 if (IsValidSocket(sendingsocket
))
1445 n
= sendto( sendingsocket
, (char *) inMsg
, n
, 0, (struct sockaddr
*) &addr
, sizeof( addr
) );
1446 err
= translate_errno( n
> 0, errno_compat(), kWriteErr
);
1450 // Don't report EHOSTDOWN (i.e. ARP failure), ENETDOWN, or no route to host for unicast destinations
1452 if ( !mDNSAddressIsAllDNSLinkGroup( inDstIP
) && ( WSAGetLastError() == WSAEHOSTDOWN
|| WSAGetLastError() == WSAENETDOWN
|| WSAGetLastError() == WSAEHOSTUNREACH
|| WSAGetLastError() == WSAENETUNREACH
) )
1454 err
= mStatus_TransientErr
;
1458 require_noerr( err
, exit
);
1467 mDNSexport
void mDNSPlatformUpdateProxyList(mDNS
*const m
, const mDNSInterfaceID InterfaceID
)
1470 DEBUG_UNUSED( InterfaceID
);
1473 mDNSexport
void mDNSPlatformSetAllowSleep(mDNS
*const m
, mDNSBool allowSleep
, const char *reason
)
1476 DEBUG_UNUSED( allowSleep
);
1477 DEBUG_UNUSED( reason
);
1480 //===========================================================================================================================
1481 // mDNSPlatformSendRawPacket
1482 //===========================================================================================================================
1484 mDNSexport
void mDNSPlatformSendWakeupPacket(mDNS
*const m
, mDNSInterfaceID InterfaceID
, char *ethaddr
, char *ipaddr
, int iteration
)
1486 unsigned char mac
[ 6 ];
1487 unsigned char buf
[ 102 ];
1488 char hex
[ 3 ] = { 0 };
1489 unsigned char *bufPtr
= buf
;
1490 MulticastWakeupStruct
*info
;
1494 (void) InterfaceID
; // unused
1495 (void) ipaddr
; // unused
1496 (void) iteration
; // unused
1498 require_action( ethaddr
, exit
, err
= mStatus_BadParamErr
);
1500 for ( i
= 0; i
< 6; i
++ )
1502 memcpy( hex
, ethaddr
+ ( i
* 3 ), 2 );
1503 mac
[ i
] = ( unsigned char ) strtoul( hex
, NULL
, 16 );
1506 memset( buf
, 0, sizeof( buf
) );
1508 for ( i
= 0; i
< 6; i
++ )
1513 for ( i
= 0; i
< 16; i
++ )
1515 memcpy( bufPtr
, mac
, sizeof( mac
) );
1516 bufPtr
+= sizeof( mac
);
1519 info
= ( MulticastWakeupStruct
* ) malloc( sizeof( MulticastWakeupStruct
) );
1520 require_action( info
, exit
, err
= mStatus_NoMemoryErr
);
1522 memset( &info
->addr
, 0, sizeof( info
->addr
) );
1523 info
->addr
.sin_family
= AF_INET
;
1524 info
->addr
.sin_addr
.s_addr
= AllDNSLinkGroup_v4
.ip
.v4
.NotAnInteger
;
1525 info
->addr
.sin_port
= htons( 9 );
1526 info
->addrLen
= sizeof( info
->addr
);
1527 memcpy( info
->data
, buf
, sizeof( buf
) );
1528 info
->dataLen
= sizeof( buf
);
1529 info
->numTries
= kMulticastWakeupNumTries
;
1530 info
->msecSleep
= kMulticastWakeupSleepBetweenTries
;
1532 _beginthread( SendMulticastWakeupPacket
, 0, ( void* ) info
);
1539 mDNSexport mDNSBool
mDNSPlatformValidRecordForInterface(const AuthRecord
*rr
, mDNSInterfaceID InterfaceID
)
1542 DEBUG_UNUSED( InterfaceID
);
1547 mDNSexport mDNSBool
mDNSPlatformValidQuestionForInterface(DNSQuestion
*q
, const NetworkInterfaceInfo
*intf
)
1550 DEBUG_UNUSED( intf
);
1555 mDNSexport
void mDNSPlatformSendRawPacket(const void *const msg
, const mDNSu8
*const end
, mDNSInterfaceID InterfaceID
)
1557 DEBUG_UNUSED( msg
);
1558 DEBUG_UNUSED( end
);
1559 DEBUG_UNUSED( InterfaceID
);
1562 // Used for debugging purposes. For now, just set the buffer to zero
1563 mDNSexport
void mDNSPlatformFormatTime(unsigned long te
, mDNSu8
*buf
, int bufsize
)
1566 if (bufsize
) buf
[0] = 0;
1569 mDNSexport
void mDNSPlatformSetLocalAddressCacheEntry(mDNS
*const m
, const mDNSAddr
*const tpa
, const mDNSEthAddr
*const tha
, mDNSInterfaceID InterfaceID
)
1572 DEBUG_UNUSED( tpa
);
1573 DEBUG_UNUSED( tha
);
1574 DEBUG_UNUSED( InterfaceID
);
1577 mDNSexport
void mDNSPlatformReceiveRawPacket(const void *const msg
, const mDNSu8
*const end
, mDNSInterfaceID InterfaceID
)
1579 DEBUG_UNUSED( msg
);
1580 DEBUG_UNUSED( end
);
1581 DEBUG_UNUSED( InterfaceID
);
1584 mDNSexport
void mDNSPlatformSetLocalARP( const mDNSv4Addr
* const tpa
, const mDNSEthAddr
* const tha
, mDNSInterfaceID InterfaceID
)
1586 DEBUG_UNUSED( tpa
);
1587 DEBUG_UNUSED( tha
);
1588 DEBUG_UNUSED( InterfaceID
);
1591 mDNSexport
void mDNSPlatformWriteDebugMsg(const char *msg
)
1593 dlog( kDebugLevelInfo
, "%s\n", msg
);
1596 mDNSexport
void mDNSPlatformWriteLogMsg( const char * ident
, const char * msg
, mDNSLogLevel_t loglevel
)
1598 extern mDNS mDNSStorage
;
1601 DEBUG_UNUSED( ident
);
1603 type
= EVENTLOG_ERROR_TYPE
;
1607 case MDNS_LOG_MSG
: type
= EVENTLOG_ERROR_TYPE
; break;
1608 case MDNS_LOG_OPERATION
: type
= EVENTLOG_WARNING_TYPE
; break;
1609 case MDNS_LOG_SPS
: type
= EVENTLOG_INFORMATION_TYPE
; break;
1610 case MDNS_LOG_INFO
: type
= EVENTLOG_INFORMATION_TYPE
; break;
1611 case MDNS_LOG_DEBUG
: type
= EVENTLOG_INFORMATION_TYPE
; break;
1613 fprintf(stderr
, "Unknown loglevel %d, assuming LOG_ERR\n", loglevel
);
1617 mDNSStorage
.p
->reportStatusFunc( type
, msg
);
1618 dlog( kDebugLevelInfo
, "%s\n", msg
);
1621 mDNSexport
void mDNSPlatformSourceAddrForDest( mDNSAddr
* const src
, const mDNSAddr
* const dst
)
1623 DEBUG_UNUSED( src
);
1624 DEBUG_UNUSED( dst
);
1627 //===========================================================================================================================
1628 // mDNSPlatformTLSSetupCerts
1629 //===========================================================================================================================
1632 mDNSPlatformTLSSetupCerts(void)
1634 return mStatus_UnsupportedErr
;
1637 //===========================================================================================================================
1638 // mDNSPlatformTLSTearDownCerts
1639 //===========================================================================================================================
1642 mDNSPlatformTLSTearDownCerts(void)
1646 //===========================================================================================================================
1647 // mDNSPlatformSetDNSConfig
1648 //===========================================================================================================================
1650 mDNSlocal
void SetDNSServers( mDNS
*const m
);
1651 mDNSlocal
void SetSearchDomainList( void );
1653 mDNSexport mDNSBool
mDNSPlatformSetDNSConfig(mDNS
*const m
, mDNSBool setservers
, mDNSBool setsearch
, domainname
*const fqdn
, DNameListElem
**regDomains
, DNameListElem
**browseDomains
, mDNSBool ackConfig
)
1657 if (setservers
) SetDNSServers(m
);
1658 if (setsearch
) SetSearchDomainList();
1662 GetDDNSFQDN( fqdn
);
1665 if ( browseDomains
)
1667 GetDDNSDomains( browseDomains
, kServiceParametersNode
TEXT("\\DynDNS\\Setup\\") kServiceDynDNSBrowseDomains
);
1672 GetDDNSDomains( regDomains
, kServiceParametersNode
TEXT("\\DynDNS\\Setup\\") kServiceDynDNSRegistrationDomains
);
1677 //===========================================================================================================================
1678 // mDNSPlatformDynDNSHostNameStatusChanged
1679 //===========================================================================================================================
1682 mDNSPlatformDynDNSHostNameStatusChanged(const domainname
*const dname
, const mStatus status
)
1684 char uname
[MAX_ESCAPED_DOMAIN_NAME
];
1691 ConvertDomainNameToCString(dname
, uname
);
1697 *p
= (char) tolower(*p
);
1698 if (!(*(p
+1)) && *p
== '.') *p
= 0; // if last character, strip trailing dot
1702 check( strlen( p
) <= MAX_ESCAPED_DOMAIN_NAME
);
1703 name
= kServiceParametersNode
TEXT("\\DynDNS\\State\\HostNames");
1704 err
= RegCreateKey( HKEY_LOCAL_MACHINE
, name
, &key
);
1705 require_noerr( err
, exit
);
1707 bStatus
= ( status
) ? 0 : 1;
1708 err
= RegSetValueEx( key
, kServiceDynDNSStatus
, 0, REG_DWORD
, (const LPBYTE
) &bStatus
, sizeof(DWORD
) );
1709 require_noerr( err
, exit
);
1721 //===========================================================================================================================
1723 //===========================================================================================================================
1725 // This routine needs to be called whenever the system secrets database changes.
1726 // We call it from DynDNSConfigDidChange and mDNSPlatformInit
1729 SetDomainSecrets( mDNS
* const m
)
1731 DomainAuthInfo
*ptr
;
1733 DNameListElem
* regDomains
= NULL
;
1735 // Rather than immediately deleting all keys now, we mark them for deletion in ten seconds.
1736 // In the case where the user simultaneously removes their DDNS host name and the key
1737 // for it, this gives mDNSResponder ten seconds to gracefully delete the name from the
1738 // server before it loses access to the necessary key. Otherwise, we'd leave orphaned
1739 // address records behind that we no longer have permission to delete.
1741 for (ptr
= m
->AuthInfoList
; ptr
; ptr
= ptr
->next
)
1742 ptr
->deltime
= NonZeroTime(m
->timenow
+ mDNSPlatformOneSecond
*10);
1744 GetDDNSFQDN( &fqdn
);
1748 SetDomainSecret( m
, &fqdn
);
1751 GetDDNSDomains( ®Domains
, kServiceParametersNode
TEXT("\\DynDNS\\Setup\\") kServiceDynDNSRegistrationDomains
);
1753 while ( regDomains
)
1755 DNameListElem
* current
= regDomains
;
1756 SetDomainSecret( m
, ¤t
->name
);
1757 regDomains
= regDomains
->next
;
1762 //===========================================================================================================================
1763 // SetSearchDomainList
1764 //===========================================================================================================================
1766 mDNSlocal
void SetDomainFromDHCP( void );
1767 mDNSlocal
void SetReverseMapSearchDomainList( void );
1770 SetSearchDomainList( void )
1772 char * searchList
= NULL
;
1773 DWORD searchListLen
;
1774 //DNameListElem * head = NULL;
1775 //DNameListElem * current = NULL;
1780 err
= RegCreateKey( HKEY_LOCAL_MACHINE
, TEXT("SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters"), &key
);
1781 require_noerr( err
, exit
);
1783 err
= RegQueryString( key
, "SearchList", &searchList
, &searchListLen
, NULL
);
1784 require_noerr( err
, exit
);
1786 // Windows separates the search domains with ','
1788 tok
= strtok( searchList
, "," );
1791 if ( ( strcmp( tok
, "" ) != 0 ) && ( strcmp( tok
, "." ) != 0 ) )
1792 mDNS_AddSearchDomain_CString(tok
, mDNSNULL
);
1793 tok
= strtok( NULL
, "," );
1808 SetDomainFromDHCP();
1809 SetReverseMapSearchDomainList();
1812 //===========================================================================================================================
1813 // SetReverseMapSearchDomainList
1814 //===========================================================================================================================
1817 SetReverseMapSearchDomainList( void )
1819 struct ifaddrs
* ifa
;
1821 ifa
= myGetIfAddrs( 1 );
1826 if (ifa
->ifa_addr
->sa_family
== AF_INET
&& !SetupAddr(&addr
, ifa
->ifa_addr
) && !(ifa
->ifa_flags
& IFF_LOOPBACK
) && ifa
->ifa_netmask
)
1831 if (!SetupAddr(&netmask
, ifa
->ifa_netmask
))
1833 _snprintf(buffer
, sizeof( buffer
), "%d.%d.%d.%d.in-addr.arpa.", addr
.ip
.v4
.b
[3] & netmask
.ip
.v4
.b
[3],
1834 addr
.ip
.v4
.b
[2] & netmask
.ip
.v4
.b
[2],
1835 addr
.ip
.v4
.b
[1] & netmask
.ip
.v4
.b
[1],
1836 addr
.ip
.v4
.b
[0] & netmask
.ip
.v4
.b
[0]);
1837 mDNS_AddSearchDomain_CString(buffer
, mDNSNULL
);
1841 ifa
= ifa
->ifa_next
;
1847 //===========================================================================================================================
1849 //===========================================================================================================================
1852 SetDNSServers( mDNS
*const m
)
1854 PIP_PER_ADAPTER_INFO pAdapterInfo
= NULL
;
1855 FIXED_INFO
* fixedInfo
= NULL
;
1857 IP_ADDR_STRING
* dnsServerList
;
1858 IP_ADDR_STRING
* ipAddr
;
1861 mStatus err
= kUnknownErr
;
1863 // Get the primary interface.
1865 index
= GetPrimaryInterface();
1867 // This should have the interface index of the primary index. Fall back in cases where
1868 // it can't be determined.
1874 for ( i
= 0; i
< 100; i
++ )
1876 err
= GetPerAdapterInfo( index
, pAdapterInfo
, &bufLen
);
1878 if ( err
!= ERROR_BUFFER_OVERFLOW
)
1883 pAdapterInfo
= (PIP_PER_ADAPTER_INFO
) realloc( pAdapterInfo
, bufLen
);
1884 require_action( pAdapterInfo
, exit
, err
= mStatus_NoMemoryErr
);
1887 require_noerr( err
, exit
);
1889 dnsServerList
= &pAdapterInfo
->DnsServerList
;
1893 bufLen
= sizeof( FIXED_INFO
);
1895 for ( i
= 0; i
< 100; i
++ )
1899 GlobalFree( fixedInfo
);
1903 fixedInfo
= (FIXED_INFO
*) GlobalAlloc( GPTR
, bufLen
);
1904 require_action( fixedInfo
, exit
, err
= mStatus_NoMemoryErr
);
1906 err
= GetNetworkParams( fixedInfo
, &bufLen
);
1908 if ( err
!= ERROR_BUFFER_OVERFLOW
)
1914 require_noerr( err
, exit
);
1916 dnsServerList
= &fixedInfo
->DnsServerList
;
1919 for ( ipAddr
= dnsServerList
; ipAddr
; ipAddr
= ipAddr
->Next
)
1922 err
= StringToAddress( &addr
, ipAddr
->IpAddress
.String
);
1923 if ( !err
) mDNS_AddDNSServer(m
, mDNSNULL
, mDNSInterface_Any
, 0, &addr
, UnicastDNSPort
, kScopeNone
, DEFAULT_UDNS_TIMEOUT
, mDNSfalse
, mDNSfalse
, mDNSfalse
, 0, mDNStrue
, mDNStrue
, mDNSfalse
);
1930 free( pAdapterInfo
);
1935 GlobalFree( fixedInfo
);
1939 //===========================================================================================================================
1940 // SetDomainFromDHCP
1941 //===========================================================================================================================
1944 SetDomainFromDHCP( void )
1947 IP_ADAPTER_INFO
* pAdapterInfo
;
1948 IP_ADAPTER_INFO
* pAdapter
;
1952 LPSTR domain
= NULL
;
1954 mStatus err
= mStatus_NoError
;
1956 pAdapterInfo
= NULL
;
1958 for ( i
= 0; i
< 100; i
++ )
1960 err
= GetAdaptersInfo( pAdapterInfo
, &bufLen
);
1962 if ( err
!= ERROR_BUFFER_OVERFLOW
)
1967 pAdapterInfo
= (IP_ADAPTER_INFO
*) realloc( pAdapterInfo
, bufLen
);
1968 require_action( pAdapterInfo
, exit
, err
= kNoMemoryErr
);
1971 require_noerr( err
, exit
);
1973 index
= GetPrimaryInterface();
1975 for ( pAdapter
= pAdapterInfo
; pAdapter
; pAdapter
= pAdapter
->Next
)
1977 if ( pAdapter
->IpAddressList
.IpAddress
.String
&&
1978 pAdapter
->IpAddressList
.IpAddress
.String
[0] &&
1979 pAdapter
->GatewayList
.IpAddress
.String
&&
1980 pAdapter
->GatewayList
.IpAddress
.String
[0] &&
1981 ( !index
|| ( pAdapter
->Index
== index
) ) )
1983 // Found one that will work
1987 _snprintf( keyName
, 1024, "%s%s", "SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Interfaces\\", pAdapter
->AdapterName
);
1989 err
= RegCreateKeyA( HKEY_LOCAL_MACHINE
, keyName
, &key
);
1990 require_noerr( err
, exit
);
1992 err
= RegQueryString( key
, "Domain", &domain
, &dwSize
, NULL
);
1995 if ( !domain
|| !domain
[0] )
2003 err
= RegQueryString( key
, "DhcpDomain", &domain
, &dwSize
, NULL
);
2007 if ( domain
&& domain
[0] ) mDNS_AddSearchDomain_CString(domain
, mDNSNULL
);
2017 free( pAdapterInfo
);
2031 //===========================================================================================================================
2032 // mDNSPlatformGetPrimaryInterface
2033 //===========================================================================================================================
2036 mDNSPlatformGetPrimaryInterface( mDNS
* const m
, mDNSAddr
* v4
, mDNSAddr
* v6
, mDNSAddr
* router
)
2038 IP_ADAPTER_INFO
* pAdapterInfo
;
2039 IP_ADAPTER_INFO
* pAdapter
;
2044 mStatus err
= mStatus_NoError
;
2050 pAdapterInfo
= NULL
;
2054 for ( i
= 0; i
< 100; i
++ )
2056 err
= GetAdaptersInfo( pAdapterInfo
, &bufLen
);
2058 if ( err
!= ERROR_BUFFER_OVERFLOW
)
2063 pAdapterInfo
= (IP_ADAPTER_INFO
*) realloc( pAdapterInfo
, bufLen
);
2064 require_action( pAdapterInfo
, exit
, err
= kNoMemoryErr
);
2067 require_noerr( err
, exit
);
2069 index
= GetPrimaryInterface();
2071 for ( pAdapter
= pAdapterInfo
; pAdapter
; pAdapter
= pAdapter
->Next
)
2073 if ( pAdapter
->IpAddressList
.IpAddress
.String
&&
2074 pAdapter
->IpAddressList
.IpAddress
.String
[0] &&
2075 pAdapter
->GatewayList
.IpAddress
.String
&&
2076 pAdapter
->GatewayList
.IpAddress
.String
[0] &&
2077 ( StringToAddress( v4
, pAdapter
->IpAddressList
.IpAddress
.String
) == mStatus_NoError
) &&
2078 ( StringToAddress( router
, pAdapter
->GatewayList
.IpAddress
.String
) == mStatus_NoError
) &&
2079 ( !index
|| ( pAdapter
->Index
== index
) ) )
2081 // Found one that will work
2083 if ( pAdapter
->AddressLength
== sizeof( m
->PrimaryMAC
) )
2085 memcpy( &m
->PrimaryMAC
, pAdapter
->Address
, pAdapter
->AddressLength
);
2097 free( pAdapterInfo
);
2103 mDNSexport
void mDNSPlatformSendKeepalive(mDNSAddr
*sadd
, mDNSAddr
*dadd
, mDNSIPPort
*lport
, mDNSIPPort
*rport
, mDNSu32 seq
, mDNSu32 ack
, mDNSu16 win
)
2105 (void) sadd
; // Unused
2106 (void) dadd
; // Unused
2107 (void) lport
; // Unused
2108 (void) rport
; // Unused
2109 (void) seq
; // Unused
2110 (void) ack
; // Unused
2111 (void) win
; // Unused
2114 mDNSexport mStatus
mDNSPlatformGetRemoteMacAddr(mDNS
*const m
, mDNSAddr
*raddr
)
2117 (void) raddr
; // Unused
2119 return mStatus_UnsupportedErr
;
2122 mDNSexport mStatus
mDNSPlatformStoreSPSMACAddr(mDNSAddr
*spsaddr
, char *ifname
)
2124 (void) spsaddr
; // Unused
2125 (void) ifname
; // Unused
2127 return mStatus_UnsupportedErr
;
2130 mDNSexport mStatus
mDNSPlatformClearSPSData(void)
2132 return mStatus_UnsupportedErr
;
2135 mDNSexport mStatus
mDNSPlatformStoreOwnerOptRecord(char *ifname
, DNSMessage
*msg
, int length
)
2137 (void) ifname
; // Unused
2138 (void) msg
; // Unused
2139 (void) length
; // Unused
2140 return mStatus_UnsupportedErr
;
2143 mDNSexport mStatus
mDNSPlatformRetrieveTCPInfo(mDNS
*const m
, mDNSAddr
*laddr
, mDNSIPPort
*lport
, mDNSAddr
*raddr
, mDNSIPPort
*rport
, mDNSTCPInfo
*mti
)
2146 (void) laddr
; // Unused
2147 (void) raddr
; // Unused
2148 (void) lport
; // Unused
2149 (void) rport
; // Unused
2150 (void) mti
; // Unused
2152 return mStatus_UnsupportedErr
;
2155 mDNSexport
void mDNSPlatformSetSocktOpt(void *sock
, mDNSTransport_Type transType
, mDNSAddr_Type addrType
, const DNSQuestion
*q
)
2163 mDNSexport mDNSs32
mDNSPlatformGetPID()
2168 mDNSexport mDNSu16
mDNSPlatformGetUDPPort(UDPSocket
*sock
)
2170 DEBUG_UNUSED( sock
);
2175 mDNSexport mDNSBool
mDNSPlatformInterfaceIsD2D(mDNSInterfaceID InterfaceID
)
2177 DEBUG_UNUSED( InterfaceID
);
2186 //===========================================================================================================================
2188 //===========================================================================================================================
2189 #if( MDNS_DEBUGMSGS )
2190 mDNSexport
void debugf_( const char *inFormat
, ... )
2196 va_start( args
, inFormat
);
2197 length
= mDNS_vsnprintf( buffer
, sizeof( buffer
), inFormat
, args
);
2200 dlog( kDebugLevelInfo
, "%s\n", buffer
);
2204 //===========================================================================================================================
2206 //===========================================================================================================================
2208 #if( MDNS_DEBUGMSGS > 1 )
2209 mDNSexport
void verbosedebugf_( const char *inFormat
, ... )
2215 va_start( args
, inFormat
);
2216 length
= mDNS_vsnprintf( buffer
, sizeof( buffer
), inFormat
, args
);
2219 dlog( kDebugLevelVerbose
, "%s\n", buffer
);
2225 #pragma mark == Platform Internals ==
2228 //===========================================================================================================================
2230 //===========================================================================================================================
2232 mStatus
SetupNiceName( mDNS
* const inMDNS
)
2234 HKEY descKey
= NULL
;
2238 NETSETUP_JOIN_STATUS joinStatus
;
2245 // Set up the nice name.
2248 // First try and open the registry key that contains the computer description value
2249 s
= TEXT("SYSTEM\\CurrentControlSet\\Services\\lanmanserver\\parameters");
2250 err
= RegOpenKeyEx( HKEY_LOCAL_MACHINE
, s
, 0, KEY_READ
, &descKey
);
2251 check_translated_errno( err
== 0, errno_compat(), kNameErr
);
2256 DWORD descSize
= sizeof( desc
);
2258 // look for the computer description
2259 err
= RegQueryValueEx( descKey
, TEXT("srvcomment"), 0, NULL
, (LPBYTE
) &desc
, &descSize
);
2263 err
= TCHARtoUTF8( desc
, utf8
, sizeof( utf8
) );
2272 // if we can't find it in the registry, then use the hostname of the machine
2273 if ( err
|| ( utf8
[ 0 ] == '\0' ) )
2275 TCHAR hostname
[256];
2277 namelen
= sizeof( hostname
) / sizeof( TCHAR
);
2279 ok
= GetComputerNameExW( ComputerNamePhysicalDnsHostname
, hostname
, &namelen
);
2280 err
= translate_errno( ok
, (mStatus
) GetLastError(), kNameErr
);
2285 err
= TCHARtoUTF8( hostname
, utf8
, sizeof( utf8
) );
2294 // if we can't get the hostname
2295 if ( err
|| ( utf8
[ 0 ] == '\0' ) )
2297 // Invalidate name so fall back to a default name.
2299 strcpy_s( utf8
, sizeof( utf8
), kMDNSDefaultName
);
2302 utf8
[ sizeof( utf8
) - 1 ] = '\0';
2303 inMDNS
->nicelabel
.c
[ 0 ] = (mDNSu8
) (strlen( utf8
) < MAX_DOMAIN_LABEL
? strlen( utf8
) : MAX_DOMAIN_LABEL
);
2304 memcpy( &inMDNS
->nicelabel
.c
[ 1 ], utf8
, inMDNS
->nicelabel
.c
[ 0 ] );
2306 dlog( kDebugLevelInfo
, DEBUG_NAME
"nice name \"%.*s\"\n", inMDNS
->nicelabel
.c
[ 0 ], &inMDNS
->nicelabel
.c
[ 1 ] );
2310 RegCloseKey( descKey
);
2313 ZeroMemory( inMDNS
->p
->nbname
, sizeof( inMDNS
->p
->nbname
) );
2314 ZeroMemory( inMDNS
->p
->nbdomain
, sizeof( inMDNS
->p
->nbdomain
) );
2316 namelen
= sizeof( inMDNS
->p
->nbname
);
2317 ok
= GetComputerNameExA( ComputerNamePhysicalNetBIOS
, inMDNS
->p
->nbname
, &namelen
);
2319 if ( ok
) dlog( kDebugLevelInfo
, DEBUG_NAME
"netbios name \"%s\"\n", inMDNS
->p
->nbname
);
2321 err
= NetGetJoinInformation( NULL
, &joinName
, &joinStatus
);
2322 check ( err
== NERR_Success
);
2323 if ( err
== NERR_Success
)
2325 if ( ( joinStatus
== NetSetupWorkgroupName
) || ( joinStatus
== NetSetupDomainName
) )
2327 err
= TCHARtoUTF8( joinName
, inMDNS
->p
->nbdomain
, sizeof( inMDNS
->p
->nbdomain
) );
2329 if ( !err
) dlog( kDebugLevelInfo
, DEBUG_NAME
"netbios domain/workgroup \"%s\"\n", inMDNS
->p
->nbdomain
);
2332 NetApiBufferFree( joinName
);
2341 //===========================================================================================================================
2343 //===========================================================================================================================
2345 mDNSlocal mStatus
SetupHostName( mDNS
* const inMDNS
)
2348 char tempString
[ 256 ];
2349 DWORD tempStringLen
;
2350 domainlabel tempLabel
;
2355 // Set up the nice name.
2356 tempString
[ 0 ] = '\0';
2358 // use the hostname of the machine
2359 tempStringLen
= sizeof( tempString
);
2360 ok
= GetComputerNameExA( ComputerNamePhysicalDnsHostname
, tempString
, &tempStringLen
);
2361 err
= translate_errno( ok
, (mStatus
) GetLastError(), kNameErr
);
2364 // if we can't get the hostname
2365 if( err
|| ( tempString
[ 0 ] == '\0' ) )
2367 // Invalidate name so fall back to a default name.
2369 strcpy_s( tempString
, sizeof( tempString
), kMDNSDefaultName
);
2372 tempString
[ sizeof( tempString
) - 1 ] = '\0';
2373 tempLabel
.c
[ 0 ] = (mDNSu8
) (strlen( tempString
) < MAX_DOMAIN_LABEL
? strlen( tempString
) : MAX_DOMAIN_LABEL
);
2374 memcpy( &tempLabel
.c
[ 1 ], tempString
, tempLabel
.c
[ 0 ] );
2376 // Set up the host name.
2378 ConvertUTF8PstringToRFC1034HostLabel( tempLabel
.c
, &inMDNS
->hostlabel
);
2379 if( inMDNS
->hostlabel
.c
[ 0 ] == 0 )
2381 // Nice name has no characters that are representable as an RFC1034 name (e.g. Japanese) so use the default.
2383 MakeDomainLabelFromLiteralString( &inMDNS
->hostlabel
, kMDNSDefaultName
);
2386 check( inMDNS
->hostlabel
.c
[ 0 ] != 0 );
2388 mDNS_SetFQDN( inMDNS
);
2390 dlog( kDebugLevelInfo
, DEBUG_NAME
"host name \"%.*s\"\n", inMDNS
->hostlabel
.c
[ 0 ], &inMDNS
->hostlabel
.c
[ 1 ] );
2395 //===========================================================================================================================
2397 //===========================================================================================================================
2399 mDNSlocal mStatus
SetupName( mDNS
* const inMDNS
)
2405 err
= SetupNiceName( inMDNS
);
2408 err
= SetupHostName( inMDNS
);
2414 //===========================================================================================================================
2415 // SetupInterfaceList
2416 //===========================================================================================================================
2418 mStatus
SetupInterfaceList( mDNS
* const inMDNS
)
2421 mDNSInterfaceData
** next
;
2422 mDNSInterfaceData
* ifd
;
2423 struct ifaddrs
* addrs
;
2425 struct ifaddrs
* loopbackv4
;
2426 struct ifaddrs
* loopbackv6
;
2431 mDNSBool foundUnicastSock4DestAddr
;
2432 mDNSBool foundUnicastSock6DestAddr
;
2434 dlog( kDebugLevelTrace
, DEBUG_NAME
"setting up interface list\n" );
2438 inMDNS
->p
->registeredLoopback4
= mDNSfalse
;
2439 inMDNS
->p
->nextDHCPLeaseExpires
= 0x7FFFFFFF;
2441 foundv4
= mDNSfalse
;
2442 foundv6
= mDNSfalse
;
2443 foundUnicastSock4DestAddr
= mDNSfalse
;
2444 foundUnicastSock6DestAddr
= mDNSfalse
;
2446 // Tear down any existing interfaces that may be set up.
2448 TearDownInterfaceList( inMDNS
);
2450 // Set up the name of this machine.
2452 err
= SetupName( inMDNS
);
2455 // Set up IPv4 interface(s). We have to set up IPv4 first so any IPv6 interface with an IPv4-routable address
2456 // can refer to the IPv4 interface when it registers to allow DNS AAAA records over the IPv4 interface.
2458 err
= getifaddrs( &addrs
);
2459 require_noerr( err
, exit
);
2463 next
= &inMDNS
->p
->interfaceList
;
2465 flagMask
= IFF_UP
| IFF_MULTICAST
;
2466 flagTest
= IFF_UP
| IFF_MULTICAST
;
2468 #if( MDNS_WINDOWS_ENABLE_IPV4 )
2469 for( p
= addrs
; p
; p
= p
->ifa_next
)
2471 if( !p
->ifa_addr
|| ( p
->ifa_addr
->sa_family
!= AF_INET
) || ( ( p
->ifa_flags
& flagMask
) != flagTest
) )
2475 if( p
->ifa_flags
& IFF_LOOPBACK
)
2483 dlog( kDebugLevelVerbose
, DEBUG_NAME
"Interface %40s (0x%08X) %##a\n",
2484 p
->ifa_name
? p
->ifa_name
: "<null>", p
->ifa_extra
.index
, p
->ifa_addr
);
2486 err
= SetupInterface( inMDNS
, p
, &ifd
);
2487 require_noerr( err
, exit
);
2489 // If this guy is point-to-point (ifd->interfaceInfo.McastTxRx == 0 ) we still want to
2490 // register him, but we also want to note that we haven't found a v4 interface
2491 // so that we register loopback so same host operations work
2493 if ( ifd
->interfaceInfo
.McastTxRx
== mDNStrue
)
2498 if ( p
->ifa_dhcpEnabled
&& ( p
->ifa_dhcpLeaseExpires
< inMDNS
->p
->nextDHCPLeaseExpires
) )
2500 inMDNS
->p
->nextDHCPLeaseExpires
= p
->ifa_dhcpLeaseExpires
;
2503 // If we're on a platform that doesn't have WSARecvMsg(), there's no way
2504 // of determing the destination address of a packet that is sent to us.
2505 // For multicast packets, that's easy to determine. But for the unicast
2506 // sockets, we'll fake it by taking the address of the first interface
2507 // that is successfully setup.
2509 if ( !foundUnicastSock4DestAddr
)
2511 inMDNS
->p
->unicastSock4
.addr
= ifd
->interfaceInfo
.ip
;
2512 foundUnicastSock4DestAddr
= TRUE
;
2517 ++inMDNS
->p
->interfaceCount
;
2521 // Set up IPv6 interface(s) after IPv4 is set up (see IPv4 notes above for reasoning).
2523 #if( MDNS_WINDOWS_ENABLE_IPV6 )
2527 for( p
= addrs
; p
; p
= p
->ifa_next
)
2529 if( !p
->ifa_addr
|| ( p
->ifa_addr
->sa_family
!= AF_INET6
) || ( ( p
->ifa_flags
& flagMask
) != flagTest
) )
2533 if( p
->ifa_flags
& IFF_LOOPBACK
)
2541 dlog( kDebugLevelVerbose
, DEBUG_NAME
"Interface %40s (0x%08X) %##a\n",
2542 p
->ifa_name
? p
->ifa_name
: "<null>", p
->ifa_extra
.index
, p
->ifa_addr
);
2544 err
= SetupInterface( inMDNS
, p
, &ifd
);
2545 require_noerr( err
, exit
);
2547 // If this guy is point-to-point (ifd->interfaceInfo.McastTxRx == 0 ) we still want to
2548 // register him, but we also want to note that we haven't found a v4 interface
2549 // so that we register loopback so same host operations work
2551 if ( ifd
->interfaceInfo
.McastTxRx
== mDNStrue
)
2556 // If we're on a platform that doesn't have WSARecvMsg(), there's no way
2557 // of determing the destination address of a packet that is sent to us.
2558 // For multicast packets, that's easy to determine. But for the unicast
2559 // sockets, we'll fake it by taking the address of the first interface
2560 // that is successfully setup.
2562 if ( !foundUnicastSock6DestAddr
)
2564 inMDNS
->p
->unicastSock6
.addr
= ifd
->interfaceInfo
.ip
;
2565 foundUnicastSock6DestAddr
= TRUE
;
2570 ++inMDNS
->p
->interfaceCount
;
2576 // If there are no real interfaces, but there is a loopback interface, use that so same-machine operations work.
2578 #if( !MDNS_WINDOWS_ENABLE_IPV4 && !MDNS_WINDOWS_ENABLE_IPV6 )
2580 flagMask
|= IFF_LOOPBACK
;
2581 flagTest
|= IFF_LOOPBACK
;
2583 for( p
= addrs
; p
; p
= p
->ifa_next
)
2585 if( !p
->ifa_addr
|| ( ( p
->ifa_flags
& flagMask
) != flagTest
) )
2589 if( ( p
->ifa_addr
->sa_family
!= AF_INET
) && ( p
->ifa_addr
->sa_family
!= AF_INET6
) )
2600 if ( !foundv4
&& loopbackv4
)
2602 dlog( kDebugLevelInfo
, DEBUG_NAME
"Interface %40s (0x%08X) %##a\n",
2603 loopbackv4
->ifa_name
? loopbackv4
->ifa_name
: "<null>", loopbackv4
->ifa_extra
.index
, loopbackv4
->ifa_addr
);
2605 err
= SetupInterface( inMDNS
, loopbackv4
, &ifd
);
2606 require_noerr( err
, exit
);
2608 inMDNS
->p
->registeredLoopback4
= mDNStrue
;
2610 #if( MDNS_WINDOWS_ENABLE_IPV4 )
2612 // If we're on a platform that doesn't have WSARecvMsg(), there's no way
2613 // of determing the destination address of a packet that is sent to us.
2614 // For multicast packets, that's easy to determine. But for the unicast
2615 // sockets, we'll fake it by taking the address of the first interface
2616 // that is successfully setup.
2618 if ( !foundUnicastSock4DestAddr
)
2620 inMDNS
->p
->unicastSock4
.addr
= ifd
->sock
.addr
;
2621 foundUnicastSock4DestAddr
= TRUE
;
2627 ++inMDNS
->p
->interfaceCount
;
2630 if ( !foundv6
&& loopbackv6
)
2632 dlog( kDebugLevelInfo
, DEBUG_NAME
"Interface %40s (0x%08X) %##a\n",
2633 loopbackv6
->ifa_name
? loopbackv6
->ifa_name
: "<null>", loopbackv6
->ifa_extra
.index
, loopbackv6
->ifa_addr
);
2635 err
= SetupInterface( inMDNS
, loopbackv6
, &ifd
);
2636 require_noerr( err
, exit
);
2638 #if( MDNS_WINDOWS_ENABLE_IPV6 )
2642 // If we're on a platform that doesn't have WSARecvMsg(), there's no way
2643 // of determing the destination address of a packet that is sent to us.
2644 // For multicast packets, that's easy to determine. But for the unicast
2645 // sockets, we'll fake it by taking the address of the first interface
2646 // that is successfully setup.
2648 if ( !foundUnicastSock6DestAddr
)
2650 inMDNS
->p
->unicastSock6
.addr
= ifd
->sock
.addr
;
2651 foundUnicastSock6DestAddr
= TRUE
;
2659 ++inMDNS
->p
->interfaceCount
;
2662 CheckFileShares( inMDNS
);
2667 TearDownInterfaceList( inMDNS
);
2671 freeifaddrs( addrs
);
2673 dlog( kDebugLevelTrace
, DEBUG_NAME
"setting up interface list done (err=%d %m)\n", err
, err
);
2677 //===========================================================================================================================
2678 // TearDownInterfaceList
2679 //===========================================================================================================================
2681 mStatus
TearDownInterfaceList( mDNS
* const inMDNS
)
2683 mDNSInterfaceData
** p
;
2684 mDNSInterfaceData
* ifd
;
2686 dlog( kDebugLevelTrace
, DEBUG_NAME
"tearing down interface list\n" );
2690 // Free any interfaces that were previously marked inactive and are no longer referenced by the mDNS cache.
2691 // Interfaces are marked inactive, but not deleted immediately if they were still referenced by the mDNS cache
2692 // so that remove events that occur after an interface goes away can still report the correct interface.
2694 p
= &inMDNS
->p
->inactiveInterfaceList
;
2698 if( NumCacheRecordsForInterfaceID( inMDNS
, (mDNSInterfaceID
) ifd
) > 0 )
2704 dlog( kDebugLevelInfo
, DEBUG_NAME
"freeing unreferenced, inactive interface %#p %#a\n", ifd
, &ifd
->interfaceInfo
.ip
);
2707 QueueUserAPC( ( PAPCFUNC
) FreeInterface
, inMDNS
->p
->mainThread
, ( ULONG_PTR
) ifd
);
2710 // Tear down all the interfaces.
2712 while( inMDNS
->p
->interfaceList
)
2714 ifd
= inMDNS
->p
->interfaceList
;
2715 inMDNS
->p
->interfaceList
= ifd
->next
;
2717 TearDownInterface( inMDNS
, ifd
);
2719 inMDNS
->p
->interfaceCount
= 0;
2721 dlog( kDebugLevelTrace
, DEBUG_NAME
"tearing down interface list done\n" );
2722 return( mStatus_NoError
);
2725 //===========================================================================================================================
2727 //===========================================================================================================================
2729 mDNSlocal mStatus
SetupInterface( mDNS
* const inMDNS
, const struct ifaddrs
*inIFA
, mDNSInterfaceData
**outIFD
)
2731 mDNSInterfaceData
* ifd
;
2732 mDNSInterfaceData
* p
;
2736 dlog( kDebugLevelTrace
, DEBUG_NAME
"setting up interface\n" );
2740 check( inIFA
->ifa_addr
);
2743 // Allocate memory for the interface and initialize it.
2745 ifd
= (mDNSInterfaceData
*) calloc( 1, sizeof( *ifd
) );
2746 require_action( ifd
, exit
, err
= mStatus_NoMemoryErr
);
2747 ifd
->sock
.fd
= kInvalidSocketRef
;
2748 ifd
->sock
.ifd
= ifd
;
2749 ifd
->sock
.next
= NULL
;
2750 ifd
->sock
.m
= inMDNS
;
2751 ifd
->index
= inIFA
->ifa_extra
.index
;
2752 ifd
->scopeID
= inIFA
->ifa_extra
.index
;
2753 check( strlen( inIFA
->ifa_name
) < sizeof( ifd
->name
) );
2754 strncpy( ifd
->name
, inIFA
->ifa_name
, sizeof( ifd
->name
) - 1 );
2755 ifd
->name
[ sizeof( ifd
->name
) - 1 ] = '\0';
2757 strncpy(ifd
->interfaceInfo
.ifname
, inIFA
->ifa_name
, sizeof(ifd
->interfaceInfo
.ifname
));
2758 ifd
->interfaceInfo
.ifname
[sizeof(ifd
->interfaceInfo
.ifname
)-1] = 0;
2760 // We always send and receive using IPv4, but to reduce traffic, we send and receive using IPv6 only on interfaces
2761 // that have no routable IPv4 address. Having a routable IPv4 address assigned is a reasonable indicator of being
2762 // on a large configured network, which means there's a good chance that most or all the other devices on that
2763 // network should also have v4. By doing this we lose the ability to talk to true v6-only devices on that link,
2764 // but we cut the packet rate in half. At this time, reducing the packet rate is more important than v6-only
2765 // devices on a large configured network, so we are willing to make that sacrifice.
2767 ifd
->interfaceInfo
.McastTxRx
= ( ( inIFA
->ifa_flags
& IFF_MULTICAST
) && !( inIFA
->ifa_flags
& IFF_POINTTOPOINT
) ) ? mDNStrue
: mDNSfalse
;
2768 ifd
->interfaceInfo
.InterfaceID
= NULL
;
2770 for( p
= inMDNS
->p
->interfaceList
; p
; p
= p
->next
)
2772 if ( strcmp( p
->name
, ifd
->name
) == 0 )
2774 if (!ifd
->interfaceInfo
.InterfaceID
)
2776 ifd
->interfaceInfo
.InterfaceID
= (mDNSInterfaceID
) p
;
2779 if ( ( inIFA
->ifa_addr
->sa_family
!= AF_INET
) &&
2780 ( p
->interfaceInfo
.ip
.type
== mDNSAddrType_IPv4
) &&
2781 ( p
->interfaceInfo
.ip
.ip
.v4
.b
[ 0 ] != 169 || p
->interfaceInfo
.ip
.ip
.v4
.b
[ 1 ] != 254 ) )
2783 ifd
->interfaceInfo
.McastTxRx
= mDNSfalse
;
2790 if ( !ifd
->interfaceInfo
.InterfaceID
)
2792 ifd
->interfaceInfo
.InterfaceID
= (mDNSInterfaceID
) ifd
;
2795 // Set up a socket for this interface (if needed).
2797 if( ifd
->interfaceInfo
.McastTxRx
)
2801 err
= SetupSocket( inMDNS
, inIFA
->ifa_addr
, MulticastDNSPort
, &ifd
->sock
.fd
);
2802 require_noerr( err
, exit
);
2803 ifd
->sock
.addr
= ( inIFA
->ifa_addr
->sa_family
== AF_INET6
) ? AllDNSLinkGroup_v6
: AllDNSLinkGroup_v4
;
2804 ifd
->sock
.port
= MulticastDNSPort
;
2806 // Get a ptr to the WSARecvMsg function, if supported. Otherwise, we'll fallback to recvfrom.
2808 err
= WSAIoctl( ifd
->sock
.fd
, SIO_GET_EXTENSION_FUNCTION_POINTER
, &kWSARecvMsgGUID
, sizeof( kWSARecvMsgGUID
), &ifd
->sock
.recvMsgPtr
, sizeof( ifd
->sock
.recvMsgPtr
), &size
, NULL
, NULL
);
2812 ifd
->sock
.recvMsgPtr
= NULL
;
2816 if ( inIFA
->ifa_dhcpEnabled
&& ( inIFA
->ifa_dhcpLeaseExpires
< inMDNS
->p
->nextDHCPLeaseExpires
) )
2818 inMDNS
->p
->nextDHCPLeaseExpires
= inIFA
->ifa_dhcpLeaseExpires
;
2821 ifd
->interfaceInfo
.NetWake
= inIFA
->ifa_womp
;
2823 // Register this interface with mDNS.
2825 err
= SockAddrToMDNSAddr( inIFA
->ifa_addr
, &ifd
->interfaceInfo
.ip
, NULL
);
2826 require_noerr( err
, exit
);
2828 err
= SockAddrToMDNSAddr( inIFA
->ifa_netmask
, &ifd
->interfaceInfo
.mask
, NULL
);
2829 require_noerr( err
, exit
);
2831 memcpy( ifd
->interfaceInfo
.MAC
.b
, inIFA
->ifa_physaddr
, sizeof( ifd
->interfaceInfo
.MAC
.b
) );
2833 ifd
->interfaceInfo
.Advertise
= ( mDNSu8
) inMDNS
->AdvertiseLocalAddresses
;
2835 if ( ifd
->sock
.fd
!= kInvalidSocketRef
)
2837 err
= mDNSPollRegisterSocket( ifd
->sock
.fd
, FD_READ
, UDPSocketNotification
, &ifd
->sock
);
2838 require_noerr( err
, exit
);
2841 // If interface is a direct link, address record will be marked as kDNSRecordTypeKnownUnique
2842 // and skip the probe phase of the probe/announce packet sequence.
2843 ifd
->interfaceInfo
.DirectLink
= mDNSfalse
;
2844 ifd
->interfaceInfo
.SupportsUnicastMDNSResponse
= mDNStrue
;
2846 err
= mDNS_RegisterInterface( inMDNS
, &ifd
->interfaceInfo
, NormalActivation
);
2847 require_noerr( err
, exit
);
2848 ifd
->hostRegistered
= mDNStrue
;
2850 dlog( kDebugLevelInfo
, DEBUG_NAME
"Registered interface %##a with mDNS\n", inIFA
->ifa_addr
);
2861 TearDownInterface( inMDNS
, ifd
);
2863 dlog( kDebugLevelTrace
, DEBUG_NAME
"setting up interface done (err=%d %m)\n", err
, err
);
2867 //===========================================================================================================================
2868 // TearDownInterface
2869 //===========================================================================================================================
2871 mDNSlocal mStatus
TearDownInterface( mDNS
* const inMDNS
, mDNSInterfaceData
*inIFD
)
2876 // Deregister this interface with mDNS.
2878 dlog( kDebugLevelInfo
, DEBUG_NAME
"Deregistering interface %#a with mDNS\n", &inIFD
->interfaceInfo
.ip
);
2880 if( inIFD
->hostRegistered
)
2882 inIFD
->hostRegistered
= mDNSfalse
;
2883 mDNS_DeregisterInterface( inMDNS
, &inIFD
->interfaceInfo
, NormalActivation
);
2886 // Tear down the multicast socket.
2888 UDPCloseSocket( &inIFD
->sock
);
2890 // If the interface is still referenced by items in the mDNS cache then put it on the inactive list. This keeps
2891 // the InterfaceID valid so remove events report the correct interface. If it is no longer referenced, free it.
2893 if( NumCacheRecordsForInterfaceID( inMDNS
, (mDNSInterfaceID
) inIFD
) > 0 )
2895 inIFD
->next
= inMDNS
->p
->inactiveInterfaceList
;
2896 inMDNS
->p
->inactiveInterfaceList
= inIFD
;
2897 dlog( kDebugLevelInfo
, DEBUG_NAME
"deferring free of interface %#p %#a\n", inIFD
, &inIFD
->interfaceInfo
.ip
);
2901 dlog( kDebugLevelInfo
, DEBUG_NAME
"freeing interface %#p %#a immediately\n", inIFD
, &inIFD
->interfaceInfo
.ip
);
2902 QueueUserAPC( ( PAPCFUNC
) FreeInterface
, inMDNS
->p
->mainThread
, ( ULONG_PTR
) inIFD
);
2905 return( mStatus_NoError
);
2908 mDNSlocal
void CALLBACK
FreeInterface( mDNSInterfaceData
*inIFD
)
2913 //===========================================================================================================================
2915 //===========================================================================================================================
2917 mDNSlocal mStatus
SetupSocket( mDNS
* const inMDNS
, const struct sockaddr
*inAddr
, mDNSIPPort port
, SocketRef
*outSocketRef
)
2922 DWORD bytesReturned
= 0;
2923 BOOL behavior
= FALSE
;
2925 DEBUG_UNUSED( inMDNS
);
2927 dlog( kDebugLevelTrace
, DEBUG_NAME
"setting up socket %##a\n", inAddr
);
2929 check( outSocketRef
);
2931 // Set up an IPv4 or IPv6 UDP socket.
2933 sock
= socket( inAddr
->sa_family
, SOCK_DGRAM
, IPPROTO_UDP
);
2934 err
= translate_errno( IsValidSocket( sock
), errno_compat(), kUnknownErr
);
2935 require_noerr( err
, exit
);
2937 // Turn on reuse address option so multiple servers can listen for Multicast DNS packets,
2938 // if we're creating a multicast socket
2940 if ( !mDNSIPPortIsZero( port
) )
2943 err
= setsockopt( sock
, SOL_SOCKET
, SO_REUSEADDR
, (char *) &option
, sizeof( option
) );
2944 check_translated_errno( err
== 0, errno_compat(), kOptionErr
);
2947 // <rdar://problem/7894393> Bonjour for Windows broken on Windows XP
2949 // Not sure why, but the default behavior for sockets is to behave incorrectly
2950 // when using them in Overlapped I/O mode on XP. According to MSDN:
2952 // SIO_UDP_CONNRESET (opcode setting: I, T==3)
2953 // Windows XP: Controls whether UDP PORT_UNREACHABLE messages are reported. Set to TRUE to enable reporting.
2954 // Set to FALSE to disable reporting.
2956 // Packet traces from misbehaving Bonjour installations showed that ICMP port unreachable
2957 // messages were being sent to us after we sent out packets to a multicast address. This is clearly
2958 // incorrect behavior, but should be harmless. However, after receiving a port unreachable error, WinSock
2959 // will no longer receive any packets from that socket, which is not harmless. This behavior is only
2962 // So we turn off port unreachable reporting to make sure our sockets that are reading
2963 // multicast packets function correctly under all circumstances.
2965 err
= WSAIoctl( sock
, SIO_UDP_CONNRESET
, &behavior
, sizeof(behavior
), NULL
, 0, &bytesReturned
, NULL
, NULL
);
2966 check_translated_errno( err
== 0, errno_compat(), kOptionErr
);
2968 if( inAddr
->sa_family
== AF_INET
)
2971 struct sockaddr_in sa4
;
2972 struct ip_mreq mreqv4
;
2974 // Bind the socket to the desired port
2976 ipv4
.NotAnInteger
= ( (const struct sockaddr_in
*) inAddr
)->sin_addr
.s_addr
;
2977 mDNSPlatformMemZero( &sa4
, sizeof( sa4
) );
2978 sa4
.sin_family
= AF_INET
;
2979 sa4
.sin_port
= port
.NotAnInteger
;
2980 sa4
.sin_addr
.s_addr
= ipv4
.NotAnInteger
;
2982 err
= bind( sock
, (struct sockaddr
*) &sa4
, sizeof( sa4
) );
2983 check_translated_errno( err
== 0, errno_compat(), kUnknownErr
);
2985 // Turn on option to receive destination addresses and receiving interface.
2988 err
= setsockopt( sock
, IPPROTO_IP
, IP_PKTINFO
, (char *) &option
, sizeof( option
) );
2989 check_translated_errno( err
== 0, errno_compat(), kOptionErr
);
2991 if ( !mDNSIPPortIsZero( port
) )
2993 // Join the all-DNS multicast group so we receive Multicast DNS packets
2995 mreqv4
.imr_multiaddr
.s_addr
= AllDNSLinkGroup_v4
.ip
.v4
.NotAnInteger
;
2996 mreqv4
.imr_interface
.s_addr
= ipv4
.NotAnInteger
;
2997 err
= setsockopt( sock
, IPPROTO_IP
, IP_ADD_MEMBERSHIP
, (char *) &mreqv4
, sizeof( mreqv4
) );
2998 check_translated_errno( err
== 0, errno_compat(), kOptionErr
);
3000 // Specify the interface to send multicast packets on this socket.
3002 sa4
.sin_addr
.s_addr
= ipv4
.NotAnInteger
;
3003 err
= setsockopt( sock
, IPPROTO_IP
, IP_MULTICAST_IF
, (char *) &sa4
.sin_addr
, sizeof( sa4
.sin_addr
) );
3004 check_translated_errno( err
== 0, errno_compat(), kOptionErr
);
3006 // Enable multicast loopback so we receive multicast packets we send (for same-machine operations).
3009 err
= setsockopt( sock
, IPPROTO_IP
, IP_MULTICAST_LOOP
, (char *) &option
, sizeof( option
) );
3010 check_translated_errno( err
== 0, errno_compat(), kOptionErr
);
3013 // Send unicast packets with TTL 255 (helps against spoofing).
3016 err
= setsockopt( sock
, IPPROTO_IP
, IP_TTL
, (char *) &option
, sizeof( option
) );
3017 check_translated_errno( err
== 0, errno_compat(), kOptionErr
);
3019 // Send multicast packets with TTL 255 (helps against spoofing).
3022 err
= setsockopt( sock
, IPPROTO_IP
, IP_MULTICAST_TTL
, (char *) &option
, sizeof( option
) );
3023 check_translated_errno( err
== 0, errno_compat(), kOptionErr
);
3026 else if( inAddr
->sa_family
== AF_INET6
)
3028 struct sockaddr_in6
* sa6p
;
3029 struct sockaddr_in6 sa6
;
3030 struct ipv6_mreq mreqv6
;
3032 sa6p
= (struct sockaddr_in6
*) inAddr
;
3034 // Bind the socket to the desired port
3036 mDNSPlatformMemZero( &sa6
, sizeof( sa6
) );
3037 sa6
.sin6_family
= AF_INET6
;
3038 sa6
.sin6_port
= port
.NotAnInteger
;
3039 sa6
.sin6_flowinfo
= 0;
3040 sa6
.sin6_addr
= sa6p
->sin6_addr
;
3041 sa6
.sin6_scope_id
= sa6p
->sin6_scope_id
;
3043 err
= bind( sock
, (struct sockaddr
*) &sa6
, sizeof( sa6
) );
3044 check_translated_errno( err
== 0, errno_compat(), kUnknownErr
);
3046 // Turn on option to receive destination addresses and receiving interface.
3049 err
= setsockopt( sock
, IPPROTO_IPV6
, IPV6_PKTINFO
, (char *) &option
, sizeof( option
) );
3050 check_translated_errno( err
== 0, errno_compat(), kOptionErr
);
3052 // We only want to receive IPv6 packets (not IPv4-mapped IPv6 addresses) because we have a separate socket
3053 // for IPv4, but the IPv6 stack in Windows currently doesn't support IPv4-mapped IPv6 addresses and doesn't
3054 // support the IPV6_V6ONLY socket option so the following code would typically not be executed (or needed).
3056 #if( defined( IPV6_V6ONLY ) )
3058 err
= setsockopt( sock
, IPPROTO_IPV6
, IPV6_V6ONLY
, (char *) &option
, sizeof( option
) );
3059 check_translated_errno( err
== 0, errno_compat(), kOptionErr
);
3062 if ( !mDNSIPPortIsZero( port
) )
3064 // Join the all-DNS multicast group so we receive Multicast DNS packets.
3066 mreqv6
.ipv6mr_multiaddr
= *( (struct in6_addr
*) &AllDNSLinkGroup_v6
.ip
.v6
);
3067 mreqv6
.ipv6mr_interface
= sa6p
->sin6_scope_id
;
3068 err
= setsockopt( sock
, IPPROTO_IPV6
, IPV6_JOIN_GROUP
, (char *) &mreqv6
, sizeof( mreqv6
) );
3069 check_translated_errno( err
== 0, errno_compat(), kOptionErr
);
3071 // Specify the interface to send multicast packets on this socket.
3073 option
= (int) sa6p
->sin6_scope_id
;
3074 err
= setsockopt( sock
, IPPROTO_IPV6
, IPV6_MULTICAST_IF
, (char *) &option
, sizeof( option
) );
3075 check_translated_errno( err
== 0, errno_compat(), kOptionErr
);
3077 // Enable multicast loopback so we receive multicast packets we send (for same-machine operations).
3080 err
= setsockopt( sock
, IPPROTO_IPV6
, IPV6_MULTICAST_LOOP
, (char *) &option
, sizeof( option
) );
3081 check_translated_errno( err
== 0, errno_compat(), kOptionErr
);
3084 // Send unicast packets with TTL 255 (helps against spoofing).
3087 err
= setsockopt( sock
, IPPROTO_IPV6
, IPV6_UNICAST_HOPS
, (char *) &option
, sizeof( option
) );
3088 check_translated_errno( err
== 0, errno_compat(), kOptionErr
);
3090 // Send multicast packets with TTL 255 (helps against spoofing).
3093 err
= setsockopt( sock
, IPPROTO_IPV6
, IPV6_MULTICAST_HOPS
, (char *) &option
, sizeof( option
) );
3094 check_translated_errno( err
== 0, errno_compat(), kOptionErr
);
3098 dlog( kDebugLevelError
, DEBUG_NAME
"%s: unsupport socket family (%d)\n", __ROUTINE__
, inAddr
->sa_family
);
3099 err
= kUnsupportedErr
;
3105 *outSocketRef
= sock
;
3106 sock
= kInvalidSocketRef
;
3107 err
= mStatus_NoError
;
3110 if( IsValidSocket( sock
) )
3112 close_compat( sock
);
3117 //===========================================================================================================================
3119 //===========================================================================================================================
3121 mDNSlocal mStatus
SockAddrToMDNSAddr( const struct sockaddr
* const inSA
, mDNSAddr
*outIP
, mDNSIPPort
*outPort
)
3128 if( inSA
->sa_family
== AF_INET
)
3130 struct sockaddr_in
* sa4
;
3132 sa4
= (struct sockaddr_in
*) inSA
;
3133 outIP
->type
= mDNSAddrType_IPv4
;
3134 outIP
->ip
.v4
.NotAnInteger
= sa4
->sin_addr
.s_addr
;
3137 outPort
->NotAnInteger
= sa4
->sin_port
;
3139 err
= mStatus_NoError
;
3141 else if( inSA
->sa_family
== AF_INET6
)
3143 struct sockaddr_in6
* sa6
;
3145 sa6
= (struct sockaddr_in6
*) inSA
;
3146 outIP
->type
= mDNSAddrType_IPv6
;
3147 outIP
->ip
.v6
= *( (mDNSv6Addr
*) &sa6
->sin6_addr
);
3148 if( IN6_IS_ADDR_LINKLOCAL( &sa6
->sin6_addr
) )
3150 outIP
->ip
.v6
.w
[ 1 ] = 0;
3154 outPort
->NotAnInteger
= sa6
->sin6_port
;
3156 err
= mStatus_NoError
;
3160 dlog( kDebugLevelError
, DEBUG_NAME
"%s: invalid sa_family %d", __ROUTINE__
, inSA
->sa_family
);
3161 err
= mStatus_BadParamErr
;
3170 //===========================================================================================================================
3171 // UDPSocketNotification
3172 //===========================================================================================================================
3174 mDNSlocal
void CALLBACK
3175 UDPSocketNotification( SOCKET sock
, LPWSANETWORKEVENTS event
, void *context
)
3177 UDPSocket
*udpSock
= ( UDPSocket
* ) context
;
3180 struct sockaddr_storage sockSrcAddr
; // This is filled in by the WSARecv* function
3181 INT sockSrcAddrLen
; // See above
3183 mDNSInterfaceID iid
;
3187 uint8_t controlBuffer
[ 128 ];
3193 DEBUG_UNUSED( sock
);
3194 DEBUG_UNUSED( event
);
3196 require_action( udpSock
!= NULL
, exit
, err
= mStatus_BadStateErr
);
3198 dlog( kDebugLevelChatty
, DEBUG_NAME
"%s: sock = %d\n", __ROUTINE__
, udpSock
->fd
);
3200 // Initialize the buffer structure
3202 wbuf
.buf
= (char *) &udpSock
->packet
;
3203 wbuf
.len
= (u_long
) sizeof( udpSock
->packet
);
3204 sockSrcAddrLen
= sizeof( sockSrcAddr
);
3210 if ( udpSock
->recvMsgPtr
)
3214 wmsg
.name
= ( LPSOCKADDR
) &sockSrcAddr
;
3215 wmsg
.namelen
= sockSrcAddrLen
;
3216 wmsg
.lpBuffers
= &wbuf
;
3217 wmsg
.dwBufferCount
= 1;
3218 wmsg
.Control
.buf
= ( CHAR
* ) controlBuffer
;
3219 wmsg
.Control
.len
= sizeof( controlBuffer
);
3222 err
= udpSock
->recvMsgPtr( udpSock
->fd
, &wmsg
, &size
, NULL
, NULL
);
3223 err
= translate_errno( ( err
== 0 ), (OSStatus
) WSAGetLastError(), kUnknownErr
);
3226 // <rdar://problem/7824093> iTunes 9.1 fails to install with Bonjour service on Windows 7 Ultimate
3228 // There seems to be a bug in some network device drivers that involves calling WSARecvMsg().
3229 // Although all the parameters to WSARecvMsg() are correct, it returns a
3230 // WSAEFAULT error code when there is no actual error. We have found experientially that falling
3231 // back to using WSARecvFrom() when this happens will work correctly.
3233 if ( err
== WSAEFAULT
) udpSock
->recvMsgPtr
= NULL
;
3239 num
= WSARecvFrom( udpSock
->fd
, &wbuf
, 1, NULL
, &flags
, ( LPSOCKADDR
) &sockSrcAddr
, &sockSrcAddrLen
, NULL
, NULL
);
3240 err
= translate_errno( ( num
>= 0 ), ( OSStatus
) WSAGetLastError(), kUnknownErr
);
3243 // According to MSDN <http://msdn.microsoft.com/en-us/library/ms741687(VS.85).aspx>:
3245 // "WSAECONNRESET: For a UDP datagram socket, this error would indicate that a previous
3246 // send operation resulted in an ICMP "Port Unreachable" message."
3248 // Because this is the case, we want to ignore this error and try again. Just in case
3249 // this is some kind of pathological condition, we'll break out of the retry loop
3250 // after 100 iterations
3252 require_action( !err
|| ( err
== WSAECONNRESET
) || ( err
== WSAEFAULT
), exit
, err
= WSAGetLastError() );
3254 while ( ( ( err
== WSAECONNRESET
) || ( err
== WSAEFAULT
) ) && ( numTries
++ < 100 ) );
3256 require_noerr( err
, exit
);
3258 // Translate the source of this packet into mDNS data types
3260 SockAddrToMDNSAddr( (struct sockaddr
* ) &sockSrcAddr
, &srcAddr
, &srcPort
);
3262 // Initialize the destination of this packet. Just in case
3263 // we can't determine this info because we couldn't call
3264 // WSARecvMsg (recvMsgPtr)
3266 dstAddr
= udpSock
->addr
;
3267 dstPort
= udpSock
->port
;
3269 if ( udpSock
->recvMsgPtr
)
3271 LPWSACMSGHDR header
;
3272 LPWSACMSGHDR last
= NULL
;
3275 // Parse the control information. Reject packets received on the wrong interface.
3277 // <rdar://problem/7832196> INSTALL: Bonjour 2.0 on Windows can not start / stop
3279 // There seems to be an interaction between Bullguard and this next bit of code.
3280 // When a user's machine is running Bullguard, the control information that is
3281 // returned is corrupted, and the code would go into an infinite loop. We'll add
3282 // two bits of defensive coding here. The first will check that each pointer to
3283 // the LPWSACMSGHDR that is returned in the for loop is different than the last.
3284 // This fixes the problem with Bullguard. The second will break out of this loop
3285 // after 100 iterations, just in case the corruption isn't caught by the first
3288 for ( header
= WSA_CMSG_FIRSTHDR( &wmsg
); header
; header
= WSA_CMSG_NXTHDR( &wmsg
, header
) )
3290 if ( ( header
!= last
) && ( ++count
< 100 ) )
3294 if ( ( header
->cmsg_level
== IPPROTO_IP
) && ( header
->cmsg_type
== IP_PKTINFO
) )
3296 IN_PKTINFO
* ipv4PacketInfo
;
3298 ipv4PacketInfo
= (IN_PKTINFO
*) WSA_CMSG_DATA( header
);
3300 if ( udpSock
->ifd
!= NULL
)
3302 require_action( ipv4PacketInfo
->ipi_ifindex
== udpSock
->ifd
->index
, exit
, err
= ( DWORD
) kMismatchErr
);
3305 dstAddr
.type
= mDNSAddrType_IPv4
;
3306 dstAddr
.ip
.v4
.NotAnInteger
= ipv4PacketInfo
->ipi_addr
.s_addr
;
3308 else if( ( header
->cmsg_level
== IPPROTO_IPV6
) && ( header
->cmsg_type
== IPV6_PKTINFO
) )
3310 IN6_PKTINFO
* ipv6PacketInfo
;
3312 ipv6PacketInfo
= (IN6_PKTINFO
*) WSA_CMSG_DATA( header
);
3314 if ( udpSock
->ifd
!= NULL
)
3316 require_action( ipv6PacketInfo
->ipi6_ifindex
== ( udpSock
->ifd
->index
- kIPv6IfIndexBase
), exit
, err
= ( DWORD
) kMismatchErr
);
3319 dstAddr
.type
= mDNSAddrType_IPv6
;
3320 dstAddr
.ip
.v6
= *( (mDNSv6Addr
*) &ipv6PacketInfo
->ipi6_addr
);
3325 static BOOL loggedMessage
= FALSE
;
3327 if ( !loggedMessage
)
3329 LogMsg( "UDPEndRecv: WSARecvMsg control information error." );
3330 loggedMessage
= TRUE
;
3338 dlog( kDebugLevelChatty
, DEBUG_NAME
"packet received\n" );
3339 dlog( kDebugLevelChatty
, DEBUG_NAME
" size = %d\n", num
);
3340 dlog( kDebugLevelChatty
, DEBUG_NAME
" src = %#a:%u\n", &srcAddr
, ntohs( srcPort
.NotAnInteger
) );
3341 dlog( kDebugLevelChatty
, DEBUG_NAME
" dst = %#a:%u\n", &dstAddr
, ntohs( dstPort
.NotAnInteger
) );
3343 if ( udpSock
->ifd
!= NULL
)
3345 dlog( kDebugLevelChatty
, DEBUG_NAME
" interface = %#a (index=0x%08X)\n", &udpSock
->ifd
->interfaceInfo
.ip
, udpSock
->ifd
->index
);
3348 dlog( kDebugLevelChatty
, DEBUG_NAME
"\n" );
3350 iid
= udpSock
->ifd
? udpSock
->ifd
->interfaceInfo
.InterfaceID
: NULL
;
3351 end
= ( (mDNSu8
*) &udpSock
->packet
) + num
;
3353 mDNSCoreReceive( udpSock
->m
, &udpSock
->packet
, end
, &srcAddr
, srcPort
, &dstAddr
, dstPort
, iid
);
3360 //===========================================================================================================================
3361 // InterfaceListDidChange
3362 //===========================================================================================================================
3363 void InterfaceListDidChange( mDNS
* const inMDNS
)
3367 dlog( kDebugLevelInfo
, DEBUG_NAME
"interface list changed\n" );
3370 // Tear down the existing interfaces and set up new ones using the new IP info.
3372 err
= TearDownInterfaceList( inMDNS
);
3375 err
= SetupInterfaceList( inMDNS
);
3378 err
= uDNS_SetupDNSConfig( inMDNS
);
3381 // Inform clients of the change.
3383 mDNS_ConfigChanged(inMDNS
);
3385 // Force mDNS to update.
3387 mDNSCoreMachineSleep( inMDNS
, mDNSfalse
); // What is this for? Mac OS X does not do this
3390 //===========================================================================================================================
3391 // ComputerDescriptionDidChange
3392 //===========================================================================================================================
3393 void ComputerDescriptionDidChange( mDNS
* const inMDNS
)
3395 dlog( kDebugLevelInfo
, DEBUG_NAME
"computer description has changed\n" );
3399 SetupNiceName( inMDNS
);
3402 //===========================================================================================================================
3403 // TCPIPConfigDidChange
3404 //===========================================================================================================================
3405 void TCPIPConfigDidChange( mDNS
* const inMDNS
)
3409 dlog( kDebugLevelInfo
, DEBUG_NAME
"TCP/IP config has changed\n" );
3412 err
= uDNS_SetupDNSConfig( inMDNS
);
3416 //===========================================================================================================================
3417 // DynDNSConfigDidChange
3418 //===========================================================================================================================
3419 void DynDNSConfigDidChange( mDNS
* const inMDNS
)
3423 dlog( kDebugLevelInfo
, DEBUG_NAME
"DynDNS config has changed\n" );
3426 SetDomainSecrets( inMDNS
);
3428 err
= uDNS_SetupDNSConfig( inMDNS
);
3432 //===========================================================================================================================
3433 // FileSharingDidChange
3434 //===========================================================================================================================
3435 void FileSharingDidChange( mDNS
* const inMDNS
)
3437 dlog( kDebugLevelInfo
, DEBUG_NAME
"File shares has changed\n" );
3440 CheckFileShares( inMDNS
);
3443 //===========================================================================================================================
3444 // FilewallDidChange
3445 //===========================================================================================================================
3446 void FirewallDidChange( mDNS
* const inMDNS
)
3448 dlog( kDebugLevelInfo
, DEBUG_NAME
"Firewall has changed\n" );
3451 CheckFileShares( inMDNS
);
3456 #pragma mark == Utilities ==
3459 //===========================================================================================================================
3461 //===========================================================================================================================
3463 mDNSlocal
int getifaddrs( struct ifaddrs
**outAddrs
)
3467 #if( MDNS_WINDOWS_USE_IPV6_IF_ADDRS )
3469 // Try to the load the GetAdaptersAddresses function from the IP Helpers DLL. This API is only available on Windows
3470 // XP or later. Looking up the symbol at runtime allows the code to still work on older systems without that API.
3472 if( !gIPHelperLibraryInstance
)
3474 gIPHelperLibraryInstance
= LoadLibrary( TEXT( "Iphlpapi" ) );
3475 if( gIPHelperLibraryInstance
)
3477 gGetAdaptersAddressesFunctionPtr
=
3478 (GetAdaptersAddressesFunctionPtr
) GetProcAddress( gIPHelperLibraryInstance
, "GetAdaptersAddresses" );
3479 if( !gGetAdaptersAddressesFunctionPtr
)
3483 ok
= FreeLibrary( gIPHelperLibraryInstance
);
3484 check_translated_errno( ok
, GetLastError(), kUnknownErr
);
3485 gIPHelperLibraryInstance
= NULL
;
3490 // Use the new IPv6-capable routine if supported. Otherwise, fall back to the old and compatible IPv4-only code.
3491 // <rdar://problem/4278934> Fall back to using getifaddrs_ipv4 if getifaddrs_ipv6 fails
3492 // <rdar://problem/6145913> Fall back to using getifaddrs_ipv4 if getifaddrs_ipv6 returns no addrs
3494 if( !gGetAdaptersAddressesFunctionPtr
|| ( ( ( err
= getifaddrs_ipv6( outAddrs
) ) != mStatus_NoError
) || ( ( outAddrs
!= NULL
) && ( *outAddrs
== NULL
) ) ) )
3496 err
= getifaddrs_ipv4( outAddrs
);
3497 require_noerr( err
, exit
);
3502 err
= getifaddrs_ipv4( outAddrs
);
3503 require_noerr( err
, exit
);
3511 #if( MDNS_WINDOWS_USE_IPV6_IF_ADDRS )
3512 //===========================================================================================================================
3514 //===========================================================================================================================
3516 mDNSlocal
int getifaddrs_ipv6( struct ifaddrs
**outAddrs
)
3521 struct ifaddrs
* head
;
3522 struct ifaddrs
** next
;
3523 IP_ADAPTER_ADDRESSES
* iaaList
;
3525 IP_ADAPTER_ADDRESSES
* iaa
;
3527 struct ifaddrs
* ifa
;
3529 check( gGetAdaptersAddressesFunctionPtr
);
3535 // Get the list of interfaces. The first call gets the size and the second call gets the actual data.
3536 // This loops to handle the case where the interface changes in the window after getting the size, but before the
3537 // second call completes. A limit of 100 retries is enforced to prevent infinite loops if something else is wrong.
3539 flags
= GAA_FLAG_INCLUDE_PREFIX
| GAA_FLAG_SKIP_ANYCAST
| GAA_FLAG_SKIP_MULTICAST
| GAA_FLAG_SKIP_DNS_SERVER
| GAA_FLAG_SKIP_FRIENDLY_NAME
;
3544 err
= gGetAdaptersAddressesFunctionPtr( AF_UNSPEC
, flags
, NULL
, NULL
, &iaaListSize
);
3545 check( err
== ERROR_BUFFER_OVERFLOW
);
3546 check( iaaListSize
>= sizeof( IP_ADAPTER_ADDRESSES
) );
3548 iaaList
= (IP_ADAPTER_ADDRESSES
*) malloc( iaaListSize
);
3549 require_action( iaaList
, exit
, err
= ERROR_NOT_ENOUGH_MEMORY
);
3551 err
= gGetAdaptersAddressesFunctionPtr( AF_UNSPEC
, flags
, NULL
, iaaList
, &iaaListSize
);
3552 if( err
== ERROR_SUCCESS
) break;
3557 require( i
< 100, exit
);
3558 dlog( kDebugLevelWarning
, "%s: retrying GetAdaptersAddresses after %d failure(s) (%d %m)\n", __ROUTINE__
, i
, err
, err
);
3561 for( iaa
= iaaList
; iaa
; iaa
= iaa
->Next
)
3564 IP_ADAPTER_UNICAST_ADDRESS
* addr
;
3566 IP_ADAPTER_PREFIX
* firstPrefix
;
3568 if( iaa
->IfIndex
> 0xFFFFFF )
3570 dlog( kDebugLevelAlert
, DEBUG_NAME
"%s: IPv4 ifindex out-of-range (0x%08X)\n", __ROUTINE__
, iaa
->IfIndex
);
3572 if( iaa
->Ipv6IfIndex
> 0xFF )
3574 dlog( kDebugLevelAlert
, DEBUG_NAME
"%s: IPv6 ifindex out-of-range (0x%08X)\n", __ROUTINE__
, iaa
->Ipv6IfIndex
);
3577 // For IPv4 interfaces, there seems to be a bug in iphlpapi.dll that causes the
3578 // following code to crash when iterating through the prefix list. This seems
3579 // to occur when iaa->Ipv6IfIndex != 0 when IPv6 is not installed on the host.
3580 // This shouldn't happen according to Microsoft docs which states:
3582 // "Ipv6IfIndex contains 0 if IPv6 is not available on the interface."
3584 // So the data structure seems to be corrupted when we return from
3585 // GetAdaptersAddresses(). The bug seems to occur when iaa->Length <
3586 // sizeof(IP_ADAPTER_ADDRESSES), so when that happens, we'll manually
3587 // modify iaa to have the correct values.
3589 if ( iaa
->Length
>= sizeof( IP_ADAPTER_ADDRESSES
) )
3591 ipv6IfIndex
= iaa
->Ipv6IfIndex
;
3592 firstPrefix
= iaa
->FirstPrefix
;
3600 // Skip pseudo and tunnel interfaces.
3602 if( ( ( ipv6IfIndex
== 1 ) && ( iaa
->IfType
!= IF_TYPE_SOFTWARE_LOOPBACK
) ) || ( iaa
->IfType
== IF_TYPE_TUNNEL
) )
3607 // Add each address as a separate interface to emulate the way getifaddrs works.
3609 for( addrIndex
= 0, addr
= iaa
->FirstUnicastAddress
; addr
; ++addrIndex
, addr
= addr
->Next
)
3612 IP_ADAPTER_PREFIX
* prefix
;
3614 struct sockaddr_in ipv4Netmask
;
3616 family
= addr
->Address
.lpSockaddr
->sa_family
;
3617 if( ( family
!= AF_INET
) && ( family
!= AF_INET6
) ) continue;
3619 // <rdar://problem/6220642> iTunes 8: Bonjour doesn't work after upgrading iTunes 8
3620 // Seems as if the problem here is a buggy implementation of some network interface
3621 // driver. It is reporting that is has a link-local address when it is actually
3622 // disconnected. This was causing a problem in AddressToIndexAndMask.
3623 // The solution is to call AddressToIndexAndMask first, and if unable to lookup
3624 // the address, to ignore that address.
3627 memset( &ipv4Netmask
, 0, sizeof( ipv4Netmask
) );
3629 if ( family
== AF_INET
)
3631 err
= AddressToIndexAndMask( addr
->Address
.lpSockaddr
, &ipv4Index
, ( struct sockaddr
* ) &ipv4Netmask
);
3640 ifa
= (struct ifaddrs
*) calloc( 1, sizeof( struct ifaddrs
) );
3641 require_action( ifa
, exit
, err
= WSAENOBUFS
);
3644 next
= &ifa
->ifa_next
;
3648 size
= strlen( iaa
->AdapterName
) + 1;
3649 ifa
->ifa_name
= (char *) malloc( size
);
3650 require_action( ifa
->ifa_name
, exit
, err
= WSAENOBUFS
);
3651 memcpy( ifa
->ifa_name
, iaa
->AdapterName
, size
);
3653 // Get interface flags.
3656 if( iaa
->OperStatus
== IfOperStatusUp
) ifa
->ifa_flags
|= IFF_UP
;
3657 if( iaa
->IfType
== IF_TYPE_SOFTWARE_LOOPBACK
) ifa
->ifa_flags
|= IFF_LOOPBACK
;
3658 else if ( IsPointToPoint( addr
) ) ifa
->ifa_flags
|= IFF_POINTTOPOINT
;
3659 if( !( iaa
->Flags
& IP_ADAPTER_NO_MULTICAST
) ) ifa
->ifa_flags
|= IFF_MULTICAST
;
3662 // <rdar://problem/4045657> Interface index being returned is 512
3664 // Windows does not have a uniform scheme for IPv4 and IPv6 interface indexes.
3665 // This code used to shift the IPv4 index up to ensure uniqueness between
3666 // it and IPv6 indexes. Although this worked, it was somewhat confusing to developers, who
3667 // then see interface indexes passed back that don't correspond to anything
3668 // that is seen in Win32 APIs or command line tools like "route". As a relatively
3669 // small percentage of developers are actively using IPv6, it seems to
3670 // make sense to make our use of IPv4 as confusion free as possible.
3671 // So now, IPv6 interface indexes will be shifted up by a
3672 // constant value which will serve to uniquely identify them, and we will
3673 // leave IPv4 interface indexes unmodified.
3677 case AF_INET
: ifa
->ifa_extra
.index
= iaa
->IfIndex
; break;
3678 case AF_INET6
: ifa
->ifa_extra
.index
= ipv6IfIndex
+ kIPv6IfIndexBase
; break;
3682 // Get lease lifetime
3684 if ( ( iaa
->IfType
!= IF_TYPE_SOFTWARE_LOOPBACK
) && ( addr
->LeaseLifetime
!= 0 ) && ( addr
->ValidLifetime
!= 0xFFFFFFFF ) )
3686 ifa
->ifa_dhcpEnabled
= TRUE
;
3687 ifa
->ifa_dhcpLeaseExpires
= time( NULL
) + addr
->ValidLifetime
;
3691 ifa
->ifa_dhcpEnabled
= FALSE
;
3692 ifa
->ifa_dhcpLeaseExpires
= 0;
3695 if ( iaa
->PhysicalAddressLength
== sizeof( ifa
->ifa_physaddr
) )
3697 memcpy( ifa
->ifa_physaddr
, iaa
->PhysicalAddress
, iaa
->PhysicalAddressLength
);
3700 // Because we don't get notified of womp changes, we're going to just assume
3701 // that all wired interfaces have it enabled. Before we go to sleep, we'll check
3702 // if the interface actually supports it, and update mDNS->SystemWakeOnLANEnabled
3705 ifa
->ifa_womp
= ( iaa
->IfType
== IF_TYPE_ETHERNET_CSMACD
) ? mDNStrue
: mDNSfalse
;
3713 ifa
->ifa_addr
= (struct sockaddr
*) calloc( 1, (size_t) addr
->Address
.iSockaddrLength
);
3714 require_action( ifa
->ifa_addr
, exit
, err
= WSAENOBUFS
);
3715 memcpy( ifa
->ifa_addr
, addr
->Address
.lpSockaddr
, (size_t) addr
->Address
.iSockaddrLength
);
3721 check( ifa
->ifa_addr
);
3723 // Get subnet mask (IPv4)/link prefix (IPv6). It is specified as a bit length (e.g. 24 for 255.255.255.0).
3729 struct sockaddr_in
* sa4
;
3731 sa4
= (struct sockaddr_in
*) calloc( 1, sizeof( *sa4
) );
3732 require_action( sa4
, exit
, err
= WSAENOBUFS
);
3733 sa4
->sin_family
= AF_INET
;
3734 sa4
->sin_addr
.s_addr
= ipv4Netmask
.sin_addr
.s_addr
;
3736 dlog( kDebugLevelInfo
, DEBUG_NAME
"%s: IPv4 mask = %s\n", __ROUTINE__
, inet_ntoa( sa4
->sin_addr
) );
3737 ifa
->ifa_netmask
= (struct sockaddr
*) sa4
;
3743 struct sockaddr_in6
*sa6
;
3744 char buf
[ 256 ] = { 0 };
3745 DWORD buflen
= sizeof( buf
);
3747 sa6
= (struct sockaddr_in6
*) calloc( 1, sizeof( *sa6
) );
3748 require_action( sa6
, exit
, err
= WSAENOBUFS
);
3749 sa6
->sin6_family
= AF_INET6
;
3750 memset( sa6
->sin6_addr
.s6_addr
, 0xFF, sizeof( sa6
->sin6_addr
.s6_addr
) );
3751 ifa
->ifa_netmask
= (struct sockaddr
*) sa6
;
3753 for ( prefix
= firstPrefix
; prefix
; prefix
= prefix
->Next
)
3756 IN6_ADDR maskedAddr
;
3760 // According to MSDN:
3761 // "On Windows Vista and later, the linked IP_ADAPTER_PREFIX structures pointed to by the FirstPrefix member
3762 // include three IP adapter prefixes for each IP address assigned to the adapter. These include the host IP address prefix,
3763 // the subnet IP address prefix, and the subnet broadcast IP address prefix.
3764 // In addition, for each adapter there is a multicast address prefix and a broadcast address prefix.
3765 // On Windows XP with SP1 and later prior to Windows Vista, the linked IP_ADAPTER_PREFIX structures pointed to by the FirstPrefix member
3766 // include only a single IP adapter prefix for each IP address assigned to the adapter."
3768 // We're only interested in the subnet IP address prefix. We'll determine if the prefix is the
3769 // subnet prefix by masking our address with a mask (computed from the prefix length) and see if that is the same
3770 // as the prefix address.
3772 if ( ( prefix
->PrefixLength
== 0 ) ||
3773 ( prefix
->PrefixLength
> 128 ) ||
3774 ( addr
->Address
.iSockaddrLength
!= prefix
->Address
.iSockaddrLength
) ||
3775 ( memcmp( addr
->Address
.lpSockaddr
, prefix
->Address
.lpSockaddr
, addr
->Address
.iSockaddrLength
) == 0 ) )
3782 memset( mask
.s6_addr
, 0, sizeof( mask
.s6_addr
) );
3784 for ( len
= (int) prefix
->PrefixLength
, maskIndex
= 0; len
> 0; len
-= 8 )
3786 uint8_t maskByte
= ( len
>= 8 ) ? 0xFF : (uint8_t)( ( 0xFFU
<< ( 8 - len
) ) & 0xFFU
);
3787 mask
.s6_addr
[ maskIndex
++ ] = maskByte
;
3792 for ( i
= 0; i
< 16; i
++ )
3794 maskedAddr
.s6_addr
[ i
] = ( ( struct sockaddr_in6
* ) addr
->Address
.lpSockaddr
)->sin6_addr
.s6_addr
[ i
] & mask
.s6_addr
[ i
];
3799 if ( memcmp( ( ( struct sockaddr_in6
* ) prefix
->Address
.lpSockaddr
)->sin6_addr
.s6_addr
, maskedAddr
.s6_addr
, sizeof( maskedAddr
.s6_addr
) ) == 0 )
3801 memcpy( sa6
->sin6_addr
.s6_addr
, mask
.s6_addr
, sizeof( mask
.s6_addr
) );
3806 WSAAddressToStringA( ( LPSOCKADDR
) sa6
, sizeof( struct sockaddr_in6
), NULL
, buf
, &buflen
);
3807 dlog( kDebugLevelInfo
, DEBUG_NAME
"%s: IPv6 mask = %s\n", __ROUTINE__
, buf
);
3825 err
= ERROR_SUCCESS
;
3830 freeifaddrs( head
);
3836 return( (int) err
);
3839 #endif // MDNS_WINDOWS_USE_IPV6_IF_ADDRS
3841 //===========================================================================================================================
3843 //===========================================================================================================================
3845 mDNSlocal
int getifaddrs_ipv4( struct ifaddrs
**outAddrs
)
3851 INTERFACE_INFO
* buffer
;
3852 INTERFACE_INFO
* tempBuffer
;
3853 INTERFACE_INFO
* ifInfo
;
3856 struct ifaddrs
* head
;
3857 struct ifaddrs
** next
;
3858 struct ifaddrs
* ifa
;
3860 sock
= INVALID_SOCKET
;
3865 // Get the interface list. WSAIoctl is called with SIO_GET_INTERFACE_LIST, but since this does not provide a
3866 // way to determine the size of the interface list beforehand, we have to start with an initial size guess and
3867 // call WSAIoctl repeatedly with increasing buffer sizes until it succeeds. Limit this to 100 tries for safety.
3869 sock
= socket( AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
3870 err
= translate_errno( IsValidSocket( sock
), errno_compat(), kUnknownErr
);
3871 require_noerr( err
, exit
);
3874 size
= 16 * sizeof( INTERFACE_INFO
);
3877 tempBuffer
= (INTERFACE_INFO
*) realloc( buffer
, size
);
3878 require_action( tempBuffer
, exit
, err
= WSAENOBUFS
);
3879 buffer
= tempBuffer
;
3881 err
= WSAIoctl( sock
, SIO_GET_INTERFACE_LIST
, NULL
, 0, buffer
, size
, &actualSize
, NULL
, NULL
);
3888 require_action( n
< 100, exit
, err
= WSAEADDRNOTAVAIL
);
3890 size
+= ( 16 * sizeof( INTERFACE_INFO
) );
3892 check( actualSize
<= size
);
3893 check( ( actualSize
% sizeof( INTERFACE_INFO
) ) == 0 );
3894 n
= (int)( actualSize
/ sizeof( INTERFACE_INFO
) );
3896 // Process the raw interface list and build a linked list of IPv4 interfaces.
3898 for( i
= 0; i
< n
; ++i
)
3901 struct sockaddr_in netmask
;
3903 ifInfo
= &buffer
[ i
];
3904 if( ifInfo
->iiAddress
.Address
.sa_family
!= AF_INET
)
3909 // <rdar://problem/6220642> iTunes 8: Bonjour doesn't work after upgrading iTunes 8
3910 // See comment in getifaddrs_ipv6
3913 memset( &netmask
, 0, sizeof( netmask
) );
3914 err
= AddressToIndexAndMask( ( struct sockaddr
* ) &ifInfo
->iiAddress
.AddressIn
, &ifIndex
, ( struct sockaddr
* ) &netmask
);
3921 ifa
= (struct ifaddrs
*) calloc( 1, sizeof( struct ifaddrs
) );
3922 require_action( ifa
, exit
, err
= WSAENOBUFS
);
3925 next
= &ifa
->ifa_next
;
3929 ifa
->ifa_name
= (char *) malloc( 16 );
3930 require_action( ifa
->ifa_name
, exit
, err
= WSAENOBUFS
);
3931 _snprintf( ifa
->ifa_name
, 16, "%d", i
+ 1 );
3933 // Get interface flags.
3935 ifa
->ifa_flags
= (u_int
) ifInfo
->iiFlags
;
3939 if ( ifInfo
->iiAddress
.Address
.sa_family
== AF_INET
)
3941 struct sockaddr_in
* sa4
;
3943 sa4
= &ifInfo
->iiAddress
.AddressIn
;
3944 ifa
->ifa_addr
= (struct sockaddr
*) calloc( 1, sizeof( *sa4
) );
3945 require_action( ifa
->ifa_addr
, exit
, err
= WSAENOBUFS
);
3946 memcpy( ifa
->ifa_addr
, sa4
, sizeof( *sa4
) );
3948 ifa
->ifa_netmask
= (struct sockaddr
*) calloc(1, sizeof( *sa4
) );
3949 require_action( ifa
->ifa_netmask
, exit
, err
= WSAENOBUFS
);
3951 // <rdar://problem/4076478> Service won't start on Win2K. The address
3952 // family field was not being initialized.
3954 ifa
->ifa_netmask
->sa_family
= AF_INET
;
3955 ( ( struct sockaddr_in
* ) ifa
->ifa_netmask
)->sin_addr
= netmask
.sin_addr
;
3956 ifa
->ifa_extra
.index
= ifIndex
;
3960 // Emulate an interface index.
3962 ifa
->ifa_extra
.index
= (uint32_t)( i
+ 1 );
3979 freeifaddrs( head
);
3985 if( sock
!= INVALID_SOCKET
)
3987 closesocket( sock
);
3992 //===========================================================================================================================
3994 //===========================================================================================================================
3996 mDNSlocal
void freeifaddrs( struct ifaddrs
*inIFAs
)
4001 // Free each piece of the structure. Set to null after freeing to handle macro-aliased fields.
4003 for( p
= inIFAs
; p
; p
= q
)
4009 free( p
->ifa_name
);
4014 free( p
->ifa_addr
);
4017 if( p
->ifa_netmask
)
4019 free( p
->ifa_netmask
);
4020 p
->ifa_netmask
= NULL
;
4022 if( p
->ifa_broadaddr
)
4024 free( p
->ifa_broadaddr
);
4025 p
->ifa_broadaddr
= NULL
;
4027 if( p
->ifa_dstaddr
)
4029 free( p
->ifa_dstaddr
);
4030 p
->ifa_dstaddr
= NULL
;
4034 free( p
->ifa_data
);
4041 //===========================================================================================================================
4042 // GetPrimaryInterface
4043 //===========================================================================================================================
4046 GetPrimaryInterface()
4048 PMIB_IPFORWARDTABLE pIpForwardTable
= NULL
;
4050 BOOL bOrder
= FALSE
;
4054 unsigned long int i
;
4056 // Find out how big our buffer needs to be.
4058 err
= GetIpForwardTable(NULL
, &dwSize
, bOrder
);
4059 require_action( err
== ERROR_INSUFFICIENT_BUFFER
, exit
, err
= kUnknownErr
);
4061 // Allocate the memory for the table
4063 pIpForwardTable
= (PMIB_IPFORWARDTABLE
) malloc( dwSize
);
4064 require_action( pIpForwardTable
, exit
, err
= kNoMemoryErr
);
4066 // Now get the table.
4068 err
= GetIpForwardTable(pIpForwardTable
, &dwSize
, bOrder
);
4069 require_noerr( err
, exit
);
4071 // Search for the row in the table we want.
4073 for ( i
= 0; i
< pIpForwardTable
->dwNumEntries
; i
++)
4075 // Look for a default route
4077 if ( pIpForwardTable
->table
[i
].dwForwardDest
== 0 )
4079 if ( index
&& ( pIpForwardTable
->table
[i
].dwForwardMetric1
>= metric
) )
4084 index
= pIpForwardTable
->table
[i
].dwForwardIfIndex
;
4085 metric
= pIpForwardTable
->table
[i
].dwForwardMetric1
;
4091 if ( pIpForwardTable
!= NULL
)
4093 free( pIpForwardTable
);
4099 //===========================================================================================================================
4100 // AddressToIndexAndMask
4101 //===========================================================================================================================
4104 AddressToIndexAndMask( struct sockaddr
* addr
, uint32_t * ifIndex
, struct sockaddr
* mask
)
4106 // Before calling AddIPAddress we use GetIpAddrTable to get
4107 // an adapter to which we can add the IP.
4109 PMIB_IPADDRTABLE pIPAddrTable
= NULL
;
4111 mStatus err
= mStatus_UnknownErr
;
4114 // For now, this is only for IPv4 addresses. That is why we can safely cast
4115 // addr's to sockaddr_in.
4117 require_action( addr
->sa_family
== AF_INET
, exit
, err
= mStatus_UnknownErr
);
4119 // Make an initial call to GetIpAddrTable to get the
4120 // necessary size into the dwSize variable
4122 for ( i
= 0; i
< 100; i
++ )
4124 err
= GetIpAddrTable( pIPAddrTable
, &dwSize
, 0 );
4126 if ( err
!= ERROR_INSUFFICIENT_BUFFER
)
4131 pIPAddrTable
= (MIB_IPADDRTABLE
*) realloc( pIPAddrTable
, dwSize
);
4132 require_action( pIPAddrTable
, exit
, err
= WSAENOBUFS
);
4135 require_noerr( err
, exit
);
4136 err
= mStatus_UnknownErr
;
4138 for ( i
= 0; i
< pIPAddrTable
->dwNumEntries
; i
++ )
4140 if ( ( ( struct sockaddr_in
* ) addr
)->sin_addr
.s_addr
== pIPAddrTable
->table
[i
].dwAddr
)
4142 *ifIndex
= pIPAddrTable
->table
[i
].dwIndex
;
4143 ( ( struct sockaddr_in
*) mask
)->sin_addr
.s_addr
= pIPAddrTable
->table
[i
].dwMask
;
4144 err
= mStatus_NoError
;
4153 free( pIPAddrTable
);
4159 //===========================================================================================================================
4160 // CanReceiveUnicast
4161 //===========================================================================================================================
4163 mDNSlocal mDNSBool
CanReceiveUnicast( void )
4167 struct sockaddr_in addr
;
4169 // Try to bind to the port without the SO_REUSEADDR option to test if someone else has already bound to it.
4171 sock
= socket( AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
4172 check_translated_errno( IsValidSocket( sock
), errno_compat(), kUnknownErr
);
4173 ok
= IsValidSocket( sock
);
4176 mDNSPlatformMemZero( &addr
, sizeof( addr
) );
4177 addr
.sin_family
= AF_INET
;
4178 addr
.sin_port
= MulticastDNSPort
.NotAnInteger
;
4179 addr
.sin_addr
.s_addr
= htonl( INADDR_ANY
);
4181 ok
= ( bind( sock
, (struct sockaddr
*) &addr
, sizeof( addr
) ) == 0 );
4182 close_compat( sock
);
4185 dlog( kDebugLevelInfo
, DEBUG_NAME
"Unicast UDP responses %s\n", ok
? "okay" : "*not allowed*" );
4189 //===========================================================================================================================
4191 //===========================================================================================================================
4193 mDNSlocal mDNSBool
IsPointToPoint( IP_ADAPTER_UNICAST_ADDRESS
* addr
)
4195 struct ifaddrs
* addrs
= NULL
;
4196 struct ifaddrs
* p
= NULL
;
4198 mDNSBool ret
= mDNSfalse
;
4200 // For now, only works for IPv4 interfaces
4202 if ( addr
->Address
.lpSockaddr
->sa_family
== AF_INET
)
4204 // The getifaddrs_ipv4 call will give us correct information regarding IFF_POINTTOPOINT flags.
4206 err
= getifaddrs_ipv4( &addrs
);
4207 require_noerr( err
, exit
);
4209 for ( p
= addrs
; p
; p
= p
->ifa_next
)
4211 if ( ( addr
->Address
.lpSockaddr
->sa_family
== p
->ifa_addr
->sa_family
) &&
4212 ( ( ( struct sockaddr_in
* ) addr
->Address
.lpSockaddr
)->sin_addr
.s_addr
== ( ( struct sockaddr_in
* ) p
->ifa_addr
)->sin_addr
.s_addr
) )
4214 ret
= ( p
->ifa_flags
& IFF_POINTTOPOINT
) ? mDNStrue
: mDNSfalse
;
4224 freeifaddrs( addrs
);
4230 //===========================================================================================================================
4231 // GetWindowsVersionString
4232 //===========================================================================================================================
4234 mDNSlocal OSStatus
GetWindowsVersionString( char *inBuffer
, size_t inBufferSize
)
4236 #if( !defined( VER_PLATFORM_WIN32_CE ) )
4237 #define VER_PLATFORM_WIN32_CE 3
4241 OSVERSIONINFO osInfo
;
4243 const char * versionString
;
4249 versionString
= "unknown Windows version";
4251 osInfo
.dwOSVersionInfoSize
= sizeof( OSVERSIONINFO
);
4252 ok
= GetVersionEx( &osInfo
);
4253 err
= translate_errno( ok
, (OSStatus
) GetLastError(), kUnknownErr
);
4254 require_noerr( err
, exit
);
4256 platformID
= osInfo
.dwPlatformId
;
4257 majorVersion
= osInfo
.dwMajorVersion
;
4258 minorVersion
= osInfo
.dwMinorVersion
;
4259 buildNumber
= osInfo
.dwBuildNumber
& 0xFFFF;
4261 if( ( platformID
== VER_PLATFORM_WIN32_WINDOWS
) && ( majorVersion
== 4 ) )
4263 if( ( minorVersion
< 10 ) && ( buildNumber
== 950 ) )
4265 versionString
= "Windows 95";
4267 else if( ( minorVersion
< 10 ) && ( ( buildNumber
> 950 ) && ( buildNumber
<= 1080 ) ) )
4269 versionString
= "Windows 95 SP1";
4271 else if( ( minorVersion
< 10 ) && ( buildNumber
> 1080 ) )
4273 versionString
= "Windows 95 OSR2";
4275 else if( ( minorVersion
== 10 ) && ( buildNumber
== 1998 ) )
4277 versionString
= "Windows 98";
4279 else if( ( minorVersion
== 10 ) && ( ( buildNumber
> 1998 ) && ( buildNumber
< 2183 ) ) )
4281 versionString
= "Windows 98 SP1";
4283 else if( ( minorVersion
== 10 ) && ( buildNumber
>= 2183 ) )
4285 versionString
= "Windows 98 SE";
4287 else if( minorVersion
== 90 )
4289 versionString
= "Windows ME";
4292 else if( platformID
== VER_PLATFORM_WIN32_NT
)
4294 if( ( majorVersion
== 3 ) && ( minorVersion
== 51 ) )
4296 versionString
= "Windows NT 3.51";
4298 else if( ( majorVersion
== 4 ) && ( minorVersion
== 0 ) )
4300 versionString
= "Windows NT 4";
4302 else if( ( majorVersion
== 5 ) && ( minorVersion
== 0 ) )
4304 versionString
= "Windows 2000";
4306 else if( ( majorVersion
== 5 ) && ( minorVersion
== 1 ) )
4308 versionString
= "Windows XP";
4310 else if( ( majorVersion
== 5 ) && ( minorVersion
== 2 ) )
4312 versionString
= "Windows Server 2003";
4315 else if( platformID
== VER_PLATFORM_WIN32_CE
)
4317 versionString
= "Windows CE";
4321 if( inBuffer
&& ( inBufferSize
> 0 ) )
4324 strncpy( inBuffer
, versionString
, inBufferSize
);
4325 inBuffer
[ inBufferSize
] = '\0';
4330 //===========================================================================================================================
4332 //===========================================================================================================================
4335 RegQueryString( HKEY key
, LPCSTR valueName
, LPSTR
* string
, DWORD
* stringLen
, DWORD
* enabled
)
4341 *stringLen
= MAX_ESCAPED_DOMAIN_NAME
;
4352 *string
= (char*) malloc( *stringLen
);
4353 require_action( *string
, exit
, err
= mStatus_NoMemoryErr
);
4355 err
= RegQueryValueExA( key
, valueName
, 0, &type
, (LPBYTE
) *string
, stringLen
);
4359 while ( ( err
== ERROR_MORE_DATA
) && ( i
< 100 ) );
4361 require_noerr_quiet( err
, exit
);
4365 DWORD dwSize
= sizeof( DWORD
);
4367 err
= RegQueryValueEx( key
, TEXT("Enabled"), NULL
, NULL
, (LPBYTE
) enabled
, &dwSize
);
4378 //===========================================================================================================================
4380 //===========================================================================================================================
4382 mDNSlocal mStatus
StringToAddress( mDNSAddr
* ip
, LPSTR string
)
4384 struct sockaddr_in6 sa6
;
4385 struct sockaddr_in sa4
;
4389 sa6
.sin6_family
= AF_INET6
;
4390 dwSize
= sizeof( sa6
);
4392 err
= WSAStringToAddressA( string
, AF_INET6
, NULL
, (struct sockaddr
*) &sa6
, &dwSize
);
4394 if ( err
== mStatus_NoError
)
4396 err
= SetupAddr( ip
, (struct sockaddr
*) &sa6
);
4397 require_noerr( err
, exit
);
4401 sa4
.sin_family
= AF_INET
;
4402 dwSize
= sizeof( sa4
);
4404 err
= WSAStringToAddressA( string
, AF_INET
, NULL
, (struct sockaddr
*) &sa4
, &dwSize
);
4405 err
= translate_errno( err
== 0, WSAGetLastError(), kUnknownErr
);
4406 require_noerr( err
, exit
);
4408 err
= SetupAddr( ip
, (struct sockaddr
*) &sa4
);
4409 require_noerr( err
, exit
);
4417 //===========================================================================================================================
4419 //===========================================================================================================================
4421 mDNSlocal
struct ifaddrs
*
4422 myGetIfAddrs(int refresh
)
4424 static struct ifaddrs
*ifa
= NULL
;
4440 //===========================================================================================================================
4442 //===========================================================================================================================
4445 TCHARtoUTF8( const TCHAR
*inString
, char *inBuffer
, size_t inBufferSize
)
4447 #if( defined( UNICODE ) || defined( _UNICODE ) )
4451 len
= WideCharToMultiByte( CP_UTF8
, 0, inString
, -1, inBuffer
, (int) inBufferSize
, NULL
, NULL
);
4452 err
= translate_errno( len
> 0, errno_compat(), kUnknownErr
);
4453 require_noerr( err
, exit
);
4458 return( WindowsLatin1toUTF8( inString
, inBuffer
, inBufferSize
) );
4462 //===========================================================================================================================
4463 // WindowsLatin1toUTF8
4464 //===========================================================================================================================
4467 WindowsLatin1toUTF8( const char *inString
, char *inBuffer
, size_t inBufferSize
)
4475 // Windows doesn't support going directly from Latin-1 to UTF-8 so we have to go from Latin-1 to UTF-16 first.
4477 len
= MultiByteToWideChar( CP_ACP
, 0, inString
, -1, NULL
, 0 );
4478 err
= translate_errno( len
> 0, errno_compat(), kUnknownErr
);
4479 require_noerr( err
, exit
);
4481 utf16
= (WCHAR
*) malloc( len
* sizeof( *utf16
) );
4482 require_action( utf16
, exit
, err
= kNoMemoryErr
);
4484 len
= MultiByteToWideChar( CP_ACP
, 0, inString
, -1, utf16
, len
);
4485 err
= translate_errno( len
> 0, errno_compat(), kUnknownErr
);
4486 require_noerr( err
, exit
);
4488 // Now convert the temporary UTF-16 to UTF-8.
4490 len
= WideCharToMultiByte( CP_UTF8
, 0, utf16
, -1, inBuffer
, (int) inBufferSize
, NULL
, NULL
);
4491 err
= translate_errno( len
> 0, errno_compat(), kUnknownErr
);
4492 require_noerr( err
, exit
);
4495 if( utf16
) free( utf16
);
4499 //===========================================================================================================================
4501 //===========================================================================================================================
4504 TCPCloseSocket( TCPSocket
* sock
)
4506 dlog( kDebugLevelChatty
, DEBUG_NAME
"closing TCPSocket 0x%x:%d\n", sock
, sock
->fd
);
4508 if ( sock
->fd
!= INVALID_SOCKET
)
4510 closesocket( sock
->fd
);
4511 sock
->fd
= INVALID_SOCKET
;
4515 //===========================================================================================================================
4517 //===========================================================================================================================
4520 UDPCloseSocket( UDPSocket
* sock
)
4522 dlog( kDebugLevelChatty
, DEBUG_NAME
"closing UDPSocket %d\n", sock
->fd
);
4524 if ( sock
->fd
!= INVALID_SOCKET
)
4526 mDNSPollUnregisterSocket( sock
->fd
);
4527 closesocket( sock
->fd
);
4528 sock
->fd
= INVALID_SOCKET
;
4532 //===========================================================================================================================
4534 //===========================================================================================================================
4536 mDNSlocal mStatus
SetupAddr(mDNSAddr
*ip
, const struct sockaddr
*const sa
)
4538 if (!sa
) { LogMsg("SetupAddr ERROR: NULL sockaddr"); return(mStatus_Invalid
); }
4540 if (sa
->sa_family
== AF_INET
)
4542 struct sockaddr_in
*ifa_addr
= (struct sockaddr_in
*)sa
;
4543 ip
->type
= mDNSAddrType_IPv4
;
4544 ip
->ip
.v4
.NotAnInteger
= ifa_addr
->sin_addr
.s_addr
;
4545 return(mStatus_NoError
);
4548 if (sa
->sa_family
== AF_INET6
)
4550 struct sockaddr_in6
*ifa_addr
= (struct sockaddr_in6
*)sa
;
4551 ip
->type
= mDNSAddrType_IPv6
;
4552 if (IN6_IS_ADDR_LINKLOCAL(&ifa_addr
->sin6_addr
)) ifa_addr
->sin6_addr
.u
.Word
[1] = 0;
4553 ip
->ip
.v6
= *(mDNSv6Addr
*)&ifa_addr
->sin6_addr
;
4554 return(mStatus_NoError
);
4557 LogMsg("SetupAddr invalid sa_family %d", sa
->sa_family
);
4558 return(mStatus_Invalid
);
4561 mDNSlocal
void GetDDNSFQDN( domainname
*const fqdn
)
4575 // Get info from Bonjour registry key
4577 err
= RegCreateKey( HKEY_LOCAL_MACHINE
, kServiceParametersNode
TEXT("\\DynDNS\\Setup\\") kServiceDynDNSHostNames
, &key
);
4578 require_noerr( err
, exit
);
4580 err
= RegQueryString( key
, "", &name
, &dwSize
, &enabled
);
4581 if ( !err
&& ( name
[0] != '\0' ) && enabled
)
4583 if ( !MakeDomainNameFromDNSNameString( fqdn
, name
) || !fqdn
->c
[0] )
4585 dlog( kDebugLevelError
, "bad DDNS host name in registry: %s", name
[0] ? name
: "(unknown)");
4605 mDNSlocal
void GetDDNSDomains( DNameListElem
** domains
, LPCWSTR lpSubKey
)
4607 mDNSlocal
void GetDDNSConfig( DNameListElem
** domains
, LPCSTR lpSubKey
)
4610 char subKeyName
[kRegistryMaxKeyLength
+ 1];
4627 err
= RegCreateKey( HKEY_LOCAL_MACHINE
, lpSubKey
, &key
);
4628 require_noerr( err
, exit
);
4630 // Get information about this node
4632 err
= RegQueryInfoKey( key
, NULL
, NULL
, NULL
, &cSubKeys
, &cbMaxSubKey
, &cchMaxClass
, NULL
, NULL
, NULL
, NULL
, NULL
);
4633 require_noerr( err
, exit
);
4635 for ( i
= 0; i
< cSubKeys
; i
++)
4639 dwSize
= kRegistryMaxKeyLength
;
4641 err
= RegEnumKeyExA( key
, i
, subKeyName
, &dwSize
, NULL
, NULL
, NULL
, NULL
);
4645 err
= RegOpenKeyExA( key
, subKeyName
, 0, KEY_READ
, &subKey
);
4646 require_noerr( err
, exit
);
4648 dwSize
= sizeof( DWORD
);
4649 err
= RegQueryValueExA( subKey
, "Enabled", NULL
, NULL
, (LPBYTE
) &enabled
, &dwSize
);
4651 if ( !err
&& ( subKeyName
[0] != '\0' ) && enabled
)
4653 if ( !MakeDomainNameFromDNSNameString( &dname
, subKeyName
) || !dname
.c
[0] )
4655 dlog( kDebugLevelError
, "bad DDNS domain in registry: %s", subKeyName
[0] ? subKeyName
: "(unknown)");
4659 DNameListElem
* domain
= (DNameListElem
*) malloc( sizeof( DNameListElem
) );
4660 require_action( domain
, exit
, err
= mStatus_NoMemoryErr
);
4662 AssignDomainName(&domain
->name
, &dname
);
4663 domain
->next
= *domains
;
4669 RegCloseKey( subKey
);
4678 RegCloseKey( subKey
);
4687 mDNSlocal
void SetDomainSecret( mDNS
* const m
, const domainname
* inDomain
)
4689 char domainUTF8
[ 256 ];
4690 DomainAuthInfo
*foundInList
;
4691 DomainAuthInfo
*ptr
;
4692 char outDomain
[ 256 ];
4694 char outSecret
[ 256 ];
4697 ConvertDomainNameToCString( inDomain
, domainUTF8
);
4699 // If we're able to find a secret for this domain
4701 if ( LsaGetSecret( domainUTF8
, outDomain
, sizeof( outDomain
), outKey
, sizeof( outKey
), outSecret
, sizeof( outSecret
) ) )
4706 // Tell the core about this secret
4708 MakeDomainNameFromDNSNameString( &domain
, outDomain
);
4709 MakeDomainNameFromDNSNameString( &key
, outKey
);
4711 for (foundInList
= m
->AuthInfoList
; foundInList
; foundInList
= foundInList
->next
)
4712 if (SameDomainName(&foundInList
->domain
, &domain
) ) break;
4718 ptr
= (DomainAuthInfo
*)malloc(sizeof(DomainAuthInfo
));
4719 require_action( ptr
, exit
, err
= mStatus_NoMemoryErr
);
4722 err
= mDNS_SetSecretForDomain(m
, ptr
, &domain
, &key
, outSecret
, NULL
, NULL
, FALSE
);
4723 require_action( err
!= mStatus_BadParamErr
, exit
, if (!foundInList
) mDNSPlatformMemFree( ptr
) );
4725 debugf("Setting shared secret for zone %s with key %##s", outDomain
, key
.c
);
4733 mDNSlocal VOID CALLBACK
4734 CheckFileSharesProc( LPVOID arg
, DWORD dwTimerLowValue
, DWORD dwTimerHighValue
)
4736 mDNS
* const m
= ( mDNS
* const ) arg
;
4738 ( void ) dwTimerLowValue
;
4739 ( void ) dwTimerHighValue
;
4741 CheckFileShares( m
);
4744 mDNSlocal
unsigned __stdcall
4745 SMBRegistrationThread( void * arg
)
4747 mDNS
* const m
= ( mDNS
* const ) arg
;
4748 DNSServiceRef sref
= NULL
;
4749 HANDLE handles
[ 3 ];
4750 mDNSu8 txtBuf
[ 256 ];
4754 mDNSIPPort port
= { { SMBPortAsNumber
>> 8, SMBPortAsNumber
& 0xFF } };
4755 DNSServiceErrorType err
;
4757 DEBUG_UNUSED( arg
);
4759 handles
[ 0 ] = gSMBThreadStopEvent
;
4760 handles
[ 1 ] = gSMBThreadRegisterEvent
;
4761 handles
[ 2 ] = gSMBThreadDeregisterEvent
;
4763 memset( txtBuf
, 0, sizeof( txtBuf
) );
4765 keyLen
= strlen( "netbios=" );
4766 valLen
= strlen( m
->p
->nbname
);
4767 require_action( valLen
< 32, exit
, err
= kUnknownErr
); // This should never happen, but check to avoid further memory corruption
4768 *txtPtr
++ = ( mDNSu8
) ( keyLen
+ valLen
);
4769 memcpy( txtPtr
, "netbios=", keyLen
);
4771 if ( valLen
) { memcpy( txtPtr
, m
->p
->nbname
, valLen
); txtPtr
+= ( mDNSu8
) valLen
; }
4772 keyLen
= strlen( "domain=" );
4773 valLen
= strlen( m
->p
->nbdomain
);
4774 require_action( valLen
< 32, exit
, err
= kUnknownErr
); // This should never happen, but check to avoid further memory corruption
4775 *txtPtr
++ = ( mDNSu8
)( keyLen
+ valLen
);
4776 memcpy( txtPtr
, "domain=", keyLen
);
4778 if ( valLen
) { memcpy( txtPtr
, m
->p
->nbdomain
, valLen
); txtPtr
+= valLen
; }
4784 ret
= WaitForMultipleObjects( 3, handles
, FALSE
, INFINITE
);
4786 if ( ret
!= WAIT_FAILED
)
4788 if ( ret
== kSMBStopEvent
)
4792 else if ( ret
== kSMBRegisterEvent
)
4794 err
= gDNSServiceRegister( &sref
, 0, 0, NULL
, "_smb._tcp,_file", NULL
, NULL
, ( uint16_t ) port
.NotAnInteger
, ( mDNSu16
)( txtPtr
- txtBuf
), txtBuf
, NULL
, NULL
);
4798 LogMsg( "SMBRegistrationThread: DNSServiceRegister returned %d\n", err
);
4803 else if ( ret
== kSMBDeregisterEvent
)
4807 gDNSServiceRefDeallocate( sref
);
4814 LogMsg( "SMBRegistrationThread: WaitForMultipleObjects returned %d\n", GetLastError() );
4823 gDNSServiceRefDeallocate( sref
);
4827 SetEvent( gSMBThreadQuitEvent
);
4833 CheckFileShares( mDNS
* const m
)
4835 PSHARE_INFO_1 bufPtr
= ( PSHARE_INFO_1
) NULL
;
4836 DWORD entriesRead
= 0;
4837 DWORD totalEntries
= 0;
4839 mDNSBool advertise
= mDNSfalse
;
4840 mDNSBool fileSharing
= mDNSfalse
;
4841 mDNSBool printSharing
= mDNSfalse
;
4849 // Only do this if we're not shutting down
4851 require_action_quiet( m
->AdvertiseLocalAddresses
&& !m
->ShutdownTime
, exit
, err
= kNoErr
);
4853 err
= RegCreateKey( HKEY_LOCAL_MACHINE
, kServiceParametersNode L
"\\Services\\SMB", &key
);
4857 DWORD dwSize
= sizeof( DWORD
);
4858 RegQueryValueEx( key
, L
"Advertise", NULL
, NULL
, (LPBYTE
) &advertise
, &dwSize
);
4861 if ( advertise
&& mDNSIsFileAndPrintSharingEnabled( &retry
) )
4863 dlog( kDebugLevelTrace
, DEBUG_NAME
"Sharing is enabled\n" );
4865 res
= NetShareEnum( NULL
, 1, ( LPBYTE
* )&bufPtr
, MAX_PREFERRED_LENGTH
, &entriesRead
, &totalEntries
, &resume
);
4867 if ( ( res
== ERROR_SUCCESS
) || ( res
== ERROR_MORE_DATA
) )
4869 PSHARE_INFO_1 p
= bufPtr
;
4872 for( i
= 0; i
< entriesRead
; i
++ )
4874 // We are only interested if the user is sharing anything other
4875 // than the built-in "print$" source
4877 if ( ( p
->shi1_type
== STYPE_DISKTREE
) && ( wcscmp( p
->shi1_netname
, TEXT( "print$" ) ) != 0 ) )
4879 fileSharing
= mDNStrue
;
4881 else if ( p
->shi1_type
== STYPE_PRINTQ
)
4883 printSharing
= mDNStrue
;
4889 NetApiBufferFree( bufPtr
);
4893 else if ( res
== NERR_ServerNotStarted
)
4902 LARGE_INTEGER liTimeout
;
4904 qwTimeout
= -m
->p
->checkFileSharesTimeout
* 10000000;
4905 liTimeout
.LowPart
= ( DWORD
)( qwTimeout
& 0xFFFFFFFF );
4906 liTimeout
.HighPart
= ( LONG
)( qwTimeout
>> 32 );
4908 SetWaitableTimer( m
->p
->checkFileSharesTimer
, &liTimeout
, 0, CheckFileSharesProc
, m
, FALSE
);
4911 if ( !m
->p
->smbFileSharing
&& fileSharing
)
4915 if ( !gDNSSDLibrary
)
4917 gDNSSDLibrary
= LoadLibrary( TEXT( "dnssd.dll" ) );
4918 require_action( gDNSSDLibrary
, exit
, err
= GetLastError() );
4921 if ( !gDNSServiceRegister
)
4923 gDNSServiceRegister
= ( DNSServiceRegisterFunc
) GetProcAddress( gDNSSDLibrary
, "DNSServiceRegister" );
4924 require_action( gDNSServiceRegister
, exit
, err
= GetLastError() );
4927 if ( !gDNSServiceRefDeallocate
)
4929 gDNSServiceRefDeallocate
= ( DNSServiceRefDeallocateFunc
) GetProcAddress( gDNSSDLibrary
, "DNSServiceRefDeallocate" );
4930 require_action( gDNSServiceRefDeallocate
, exit
, err
= GetLastError() );
4933 if ( !gSMBThreadRegisterEvent
)
4935 gSMBThreadRegisterEvent
= CreateEvent( NULL
, FALSE
, FALSE
, NULL
);
4936 require_action( gSMBThreadRegisterEvent
!= NULL
, exit
, err
= GetLastError() );
4939 if ( !gSMBThreadDeregisterEvent
)
4941 gSMBThreadDeregisterEvent
= CreateEvent( NULL
, FALSE
, FALSE
, NULL
);
4942 require_action( gSMBThreadDeregisterEvent
!= NULL
, exit
, err
= GetLastError() );
4945 if ( !gSMBThreadStopEvent
)
4947 gSMBThreadStopEvent
= CreateEvent( NULL
, FALSE
, FALSE
, NULL
);
4948 require_action( gSMBThreadStopEvent
!= NULL
, exit
, err
= GetLastError() );
4951 if ( !gSMBThreadQuitEvent
)
4953 gSMBThreadQuitEvent
= CreateEvent( NULL
, FALSE
, FALSE
, NULL
);
4954 require_action( gSMBThreadQuitEvent
!= NULL
, exit
, err
= GetLastError() );
4957 gSMBThread
= ( HANDLE
) _beginthreadex( NULL
, 0, SMBRegistrationThread
, m
, 0, NULL
);
4958 require_action( gSMBThread
!= NULL
, exit
, err
= GetLastError() );
4961 SetEvent( gSMBThreadRegisterEvent
);
4963 m
->p
->smbFileSharing
= mDNStrue
;
4965 else if ( m
->p
->smbFileSharing
&& !fileSharing
)
4967 dlog( kDebugLevelTrace
, DEBUG_NAME
"deregistering smb type\n" );
4969 if ( gSMBThreadDeregisterEvent
!= NULL
)
4971 SetEvent( gSMBThreadDeregisterEvent
);
4974 m
->p
->smbFileSharing
= mDNSfalse
;
4986 IsWOMPEnabled( mDNS
* const m
)
4990 mDNSInterfaceData
* ifd
;
4994 for( ifd
= m
->p
->interfaceList
; ifd
; ifd
= ifd
->next
)
4996 if ( IsWOMPEnabledForAdapter( ifd
->name
) )
5007 IsWOMPEnabledForAdapter( const char * adapterName
)
5012 HANDLE handle
= INVALID_HANDLE_VALUE
;
5013 NDIS_PNP_CAPABILITIES
* pNPC
= NULL
;
5017 require_action( adapterName
!= NULL
, exit
, ok
= FALSE
);
5019 dlog( kDebugLevelTrace
, DEBUG_NAME
"IsWOMPEnabledForAdapter: %s\n", adapterName
);
5021 // Construct a device name to pass to CreateFile
5023 strncpy_s( fileName
, sizeof( fileName
), DEVICE_PREFIX
, strlen( DEVICE_PREFIX
) );
5024 strcat_s( fileName
, sizeof( fileName
), adapterName
);
5025 handle
= CreateFileA( fileName
, GENERIC_READ
, FILE_SHARE_READ
| FILE_SHARE_WRITE
, NULL
, OPEN_EXISTING
, 0, INVALID_HANDLE_VALUE
);
5026 require_action ( handle
!= INVALID_HANDLE_VALUE
, exit
, ok
= FALSE
);
5028 // We successfully opened the driver, format the IOCTL to pass the driver.
5030 oid
= OID_PNP_CAPABILITIES
;
5031 pNPC
= ( NDIS_PNP_CAPABILITIES
* ) malloc( sizeof( NDIS_PNP_CAPABILITIES
) );
5032 require_action( pNPC
!= NULL
, exit
, ok
= FALSE
);
5033 ok
= ( mDNSu8
) DeviceIoControl( handle
, IOCTL_NDIS_QUERY_GLOBAL_STATS
, &oid
, sizeof( oid
), pNPC
, sizeof( NDIS_PNP_CAPABILITIES
), &count
, NULL
);
5034 err
= translate_errno( ok
, GetLastError(), kUnknownErr
);
5035 require_action( !err
, exit
, ok
= FALSE
);
5036 ok
= ( mDNSu8
) ( ( count
== sizeof( NDIS_PNP_CAPABILITIES
) ) && ( pNPC
->Flags
& NDIS_DEVICE_WAKE_ON_MAGIC_PACKET_ENABLE
) );
5045 if ( handle
!= INVALID_HANDLE_VALUE
)
5047 CloseHandle( handle
);
5050 dlog( kDebugLevelTrace
, DEBUG_NAME
"IsWOMPEnabledForAdapter returns %s\n", ok
? "true" : "false" );
5052 return ( mDNSu8
) ok
;
5056 SendWakeupPacket( mDNS
* const inMDNS
, LPSOCKADDR addr
, INT addrlen
, const char * buf
, INT buflen
, INT numTries
, INT msecSleep
)
5058 mDNSBool repeat
= ( numTries
== 1 ) ? mDNStrue
: mDNSfalse
;
5065 sock
= socket( addr
->sa_family
, SOCK_DGRAM
, IPPROTO_UDP
);
5066 require_action( sock
!= INVALID_SOCKET
, exit
, err
= mStatus_UnknownErr
);
5068 while ( numTries
-- )
5070 num
= sendto( sock
, ( const char* ) buf
, buflen
, 0, addr
, addrlen
);
5072 if ( num
!= buflen
)
5074 LogMsg( "SendWakeupPacket error: sent %d bytes: %d\n", num
, WSAGetLastError() );
5079 num
= sendto( sock
, buf
, buflen
, 0, addr
, addrlen
);
5081 if ( num
!= buflen
)
5083 LogMsg( "SendWakeupPacket error: sent %d bytes: %d\n", num
, WSAGetLastError() );
5095 if ( sock
!= INVALID_SOCKET
)
5097 closesocket( sock
);
5101 mDNSlocal
void _cdecl
5102 SendMulticastWakeupPacket( void *arg
)
5104 MulticastWakeupStruct
*info
= ( MulticastWakeupStruct
* ) arg
;
5108 SendWakeupPacket( info
->inMDNS
, ( LPSOCKADDR
) &info
->addr
, sizeof( info
->addr
), ( const char* ) info
->data
, sizeof( info
->data
), info
->numTries
, info
->msecSleep
);
5115 mDNSexport
void FreeEtcHosts(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
5119 DEBUG_UNUSED( result
);