1 /* -*- Mode: C; tab-width: 4 -*-
3 * Copyright (c) 2002-2004 Apple Computer, 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.
17 Change History (most recent first):
20 Revision 1.129 2007/10/17 22:52:26 cheshire
21 Get rid of unused mDNS_UpdateLLQs()
23 Revision 1.128 2007/09/12 19:23:17 cheshire
24 Get rid of unnecessary mDNSPlatformTCPIsConnected() routine
26 Revision 1.127 2007/07/20 00:54:22 cheshire
27 <rdar://problem/4641118> Need separate SCPreferences for per-user .Mac settings
29 Revision 1.126 2007/07/11 02:56:20 cheshire
30 <rdar://problem/5303807> Register IPv6-only hostname and don't create port mappings for AutoTunnel services
31 Remove unused mDNSPlatformDefaultRegDomainChanged
33 Revision 1.125 2007/06/20 01:10:13 cheshire
34 <rdar://problem/5280520> Sync iPhone changes into main mDNSResponder code
36 Revision 1.124 2007/04/26 00:35:16 cheshire
37 <rdar://problem/5140339> uDNS: Domain discovery not working over VPN
38 Fixes to make sure results update correctly when connectivity changes (e.g. a DNS server
39 inside the firewall may give answers where a public one gives none, and vice versa.)
41 Revision 1.123 2007/04/18 21:00:40 cheshire
42 Use mDNS_AddSearchDomain_CString() instead of MakeDomainNameFromDNSNameString ... mDNS_AddSearchDomain
44 Revision 1.122 2007/04/17 19:21:29 cheshire
45 <rdar://problem/5140339> Domain discovery not working over VPN
47 Revision 1.121 2007/04/05 20:40:37 cheshire
48 Remove unused mDNSPlatformTCPGetFlags()
50 Revision 1.120 2007/03/28 20:59:27 cheshire
51 <rdar://problem/4743285> Remove inappropriate use of IsPrivateV4Addr()
53 Revision 1.119 2007/03/28 15:56:38 cheshire
54 <rdar://problem/5085774> Add listing of NAT port mapping and GetAddrInfo requests in SIGINFO output
56 Revision 1.118 2007/03/22 18:31:49 cheshire
57 Put dst parameter first in mDNSPlatformStrCopy/mDNSPlatformMemCopy, like conventional Posix strcpy/memcpy
59 Revision 1.117 2007/03/21 00:30:07 cheshire
60 <rdar://problem/4789455> Multiple errors in DNameList-related code
62 Revision 1.116 2007/03/20 17:07:16 cheshire
63 Rename "struct uDNS_TCPSocket_struct" to "TCPSocket", "struct uDNS_UDPSocket_struct" to "UDPSocket"
65 Revision 1.115 2007/02/08 21:12:28 cheshire
66 <rdar://problem/4386497> Stop reading /etc/mDNSResponder.conf on every sleep/wake
68 Revision 1.114 2007/01/05 08:31:01 cheshire
69 Trim excessive "$Log" checkin history from before 2006
70 (checkin history still available via "cvs log ..." of course)
72 Revision 1.113 2007/01/04 23:12:20 cheshire
73 Remove unused mDNSPlatformDefaultBrowseDomainChanged
75 Revision 1.112 2006/12/22 20:59:51 cheshire
76 <rdar://problem/4742742> Read *all* DNS keys from keychain,
77 not just key for the system-wide default registration domain
79 Revision 1.111 2006/12/19 22:43:56 cheshire
82 Revision 1.110 2006/09/27 00:47:40 herscher
83 Fix compile error caused by changes to the tcp callback api.
85 Revision 1.109 2006/08/14 23:25:21 cheshire
86 Re-licensed mDNSResponder daemon source code under Apache License, Version 2.0
88 Revision 1.108 2006/07/06 00:06:21 cheshire
89 <rdar://problem/4472014> Add Private DNS client functionality to mDNSResponder
91 Revision 1.107 2006/03/19 02:00:13 cheshire
92 <rdar://problem/4073825> Improve logic for delaying packets after repeated interface transitions
94 Revision 1.106 2006/02/26 19:31:05 herscher
95 <rdar://problem/4455038> Bonjour For Windows takes 90 seconds to start. This was caused by a bad interaction between the VirtualPC check, and the removal of the WMI dependency. The problem was fixed by: 1) checking to see if WMI is running before trying to talk to it. 2) Retrying the VirtualPC check every 10 seconds upon failure, stopping after 10 unsuccessful tries.
99 - Get unicode name of machine for nice name instead of just the host name.
100 - Use the IPv6 Internet Connection Firewall API to allow IPv6 mDNS without manually changing the firewall.
101 - Get DNS server address(es) from Windows and provide them to the uDNS layer.
102 - Implement TCP support for truncated packets (only stubs now).
112 #include "CommonServices.h"
113 #include "DebugServices.h"
114 #include "VPCDetect.h"
115 #include "RegNames.h"
118 #include <Iphlpapi.h>
119 #if( !TARGET_OS_WINDOWS_CE )
122 #include <ntsecapi.h>
125 #include "mDNSEmbeddedAPI.h"
127 #include "mDNSWin32.h"
130 #pragma mark == Constants ==
133 //===========================================================================================================================
135 //===========================================================================================================================
137 #define DEBUG_NAME "[mDNSWin32] "
139 #define MDNS_WINDOWS_USE_IPV6_IF_ADDRS 1
140 #define MDNS_WINDOWS_ENABLE_IPV4 1
141 #define MDNS_WINDOWS_ENABLE_IPV6 1
142 #define MDNS_FIX_IPHLPAPI_PREFIX_BUG 1
143 #define MDNS_SET_HINFO_STRINGS 0
145 #define kMDNSDefaultName "My Computer"
147 #define kWinSockMajorMin 2
148 #define kWinSockMinorMin 2
150 #define kWaitListCancelEvent ( WAIT_OBJECT_0 + 0 )
151 #define kWaitListInterfaceListChangedEvent ( WAIT_OBJECT_0 + 1 )
152 #define kWaitListWakeupEvent ( WAIT_OBJECT_0 + 2 )
153 #define kWaitListComputerDescriptionEvent ( WAIT_OBJECT_0 + 3 )
154 #define kWaitListTCPIPEvent ( WAIT_OBJECT_0 + 4 )
155 #define kWaitListDynDNSEvent ( WAIT_OBJECT_0 + 5 )
156 #define kWaitListFixedItemCount 6 + MDNS_WINDOWS_ENABLE_IPV4 + MDNS_WINDOWS_ENABLE_IPV6
158 #define kRegistryMaxKeyLength 255
160 #if( !TARGET_OS_WINDOWS_CE )
161 static GUID kWSARecvMsgGUID
= WSAID_WSARECVMSG
;
164 #define kIPv6IfIndexBase (10000000L)
166 #define kRetryVPCRate (-100000000)
167 #define kRetryVPCMax (10)
171 #pragma mark == Prototypes ==
174 //===========================================================================================================================
176 //===========================================================================================================================
178 mDNSlocal mStatus
SetupSynchronizationObjects( mDNS
* const inMDNS
);
179 mDNSlocal mStatus
TearDownSynchronizationObjects( mDNS
* const inMDNS
);
180 mDNSlocal mStatus
SetupNiceName( mDNS
* const inMDNS
);
181 mDNSlocal mStatus
SetupHostName( mDNS
* const inMDNS
);
182 mDNSlocal mStatus
SetupName( mDNS
* const inMDNS
);
183 mDNSlocal mStatus
SetupInterfaceList( mDNS
* const inMDNS
);
184 mDNSlocal mStatus
TearDownInterfaceList( mDNS
* const inMDNS
);
185 mDNSlocal mStatus
SetupInterface( mDNS
* const inMDNS
, const struct ifaddrs
*inIFA
, mDNSInterfaceData
**outIFD
);
186 mDNSlocal mStatus
TearDownInterface( mDNS
* const inMDNS
, mDNSInterfaceData
*inIFD
);
187 mDNSlocal mStatus
SetupSocket( mDNS
* const inMDNS
, const struct sockaddr
*inAddr
, mDNSIPPort port
, SocketRef
*outSocketRef
);
188 mDNSlocal mStatus
SockAddrToMDNSAddr( const struct sockaddr
* const inSA
, mDNSAddr
*outIP
, mDNSIPPort
*outPort
);
189 mDNSlocal mStatus
SetupNotifications( mDNS
* const inMDNS
);
190 mDNSlocal mStatus
TearDownNotifications( mDNS
* const inMDNS
);
191 mDNSlocal mStatus
SetupRetryVPCCheck( mDNS
* const inMDNS
);
192 mDNSlocal mStatus
TearDownRetryVPCCheck( mDNS
* const inMDNS
);
194 mDNSlocal mStatus
SetupThread( mDNS
* const inMDNS
);
195 mDNSlocal mStatus
TearDownThread( const mDNS
* const inMDNS
);
196 mDNSlocal
unsigned WINAPI
ProcessingThread( LPVOID inParam
);
197 mDNSlocal mStatus
ProcessingThreadInitialize( mDNS
* const inMDNS
);
198 mDNSlocal mStatus
ProcessingThreadSetupWaitList( mDNS
* const inMDNS
, HANDLE
**outWaitList
, int *outWaitListCount
);
199 mDNSlocal
void ProcessingThreadProcessPacket( mDNS
*inMDNS
, mDNSInterfaceData
*inIFD
, SocketRef inSock
);
200 mDNSlocal
void ProcessingThreadInterfaceListChanged( mDNS
*inMDNS
);
201 mDNSlocal
void ProcessingThreadComputerDescriptionChanged( mDNS
* inMDNS
);
202 mDNSlocal
void ProcessingThreadTCPIPConfigChanged( mDNS
* inMDNS
);
203 mDNSlocal
void ProcessingThreadDynDNSConfigChanged( mDNS
* inMDNS
);
204 mDNSlocal
void ProcessingThreadRetryVPCCheck( mDNS
* inMDNS
);
207 // Platform Accessors
213 typedef struct mDNSPlatformInterfaceInfo mDNSPlatformInterfaceInfo
;
214 struct mDNSPlatformInterfaceInfo
220 struct TCPSocket_struct
223 TCPSocketFlags flags
;
225 TCPConnectionCallback callback
;
232 mDNSexport mStatus
mDNSPlatformInterfaceNameToID( mDNS
* const inMDNS
, const char *inName
, mDNSInterfaceID
*outID
);
233 mDNSexport mStatus
mDNSPlatformInterfaceIDToInfo( mDNS
* const inMDNS
, mDNSInterfaceID inID
, mDNSPlatformInterfaceInfo
*outInfo
);
237 typedef struct PolyString PolyString
;
243 PLSA_UNICODE_STRING m_lsa
;
247 #if( MDNS_WINDOWS_USE_IPV6_IF_ADDRS )
248 mDNSlocal
int getifaddrs_ipv6( struct ifaddrs
**outAddrs
);
251 #if( !TARGET_OS_WINDOWS_CE )
252 mDNSlocal
int getifaddrs_ipv4( struct ifaddrs
**outAddrs
);
255 #if( TARGET_OS_WINDOWS_CE )
256 mDNSlocal
int getifaddrs_ce( struct ifaddrs
**outAddrs
);
259 mDNSlocal DWORD
GetPrimaryInterface();
260 mDNSlocal mStatus
AddressToIndexAndMask( struct sockaddr
* address
, uint32_t * index
, struct sockaddr
* mask
);
261 mDNSlocal mDNSBool
CanReceiveUnicast( void );
262 mDNSlocal mDNSBool
IsPointToPoint( IP_ADAPTER_UNICAST_ADDRESS
* addr
);
264 mDNSlocal mStatus
StringToAddress( mDNSAddr
* ip
, LPSTR string
);
265 mDNSlocal mStatus
RegQueryString( HKEY key
, LPCSTR param
, LPSTR
* string
, DWORD
* stringLen
, DWORD
* enabled
);
266 mDNSlocal
struct ifaddrs
* myGetIfAddrs(int refresh
);
267 mDNSlocal OSStatus
TCHARtoUTF8( const TCHAR
*inString
, char *inBuffer
, size_t inBufferSize
);
268 mDNSlocal OSStatus
WindowsLatin1toUTF8( const char *inString
, char *inBuffer
, size_t inBufferSize
);
269 mDNSlocal OSStatus
MakeLsaStringFromUTF8String( PLSA_UNICODE_STRING output
, const char * input
);
270 mDNSlocal OSStatus
MakeUTF8StringFromLsaString( char * output
, size_t len
, PLSA_UNICODE_STRING input
);
271 mDNSlocal
void FreeTCPSocket( TCPSocket
*sock
);
272 mDNSlocal mStatus
SetupAddr(mDNSAddr
*ip
, const struct sockaddr
*const sa
);
279 #pragma mark == Globals ==
282 //===========================================================================================================================
284 //===========================================================================================================================
286 mDNSlocal mDNS_PlatformSupport gMDNSPlatformSupport
;
287 mDNSs32 mDNSPlatformOneSecond
= 0;
288 mDNSlocal TCPSocket
* gTCPConnectionList
= NULL
;
289 mDNSlocal
int gTCPConnections
= 0;
290 mDNSlocal BOOL gWaitListChanged
= FALSE
;
292 #if( MDNS_WINDOWS_USE_IPV6_IF_ADDRS )
295 ( WINAPI
* GetAdaptersAddressesFunctionPtr
)(
299 PIP_ADAPTER_ADDRESSES inAdapter
,
300 PULONG outBufferSize
);
302 mDNSlocal HMODULE gIPHelperLibraryInstance
= NULL
;
303 mDNSlocal GetAdaptersAddressesFunctionPtr gGetAdaptersAddressesFunctionPtr
= NULL
;
309 #pragma mark == Platform Support ==
312 //===========================================================================================================================
314 //===========================================================================================================================
316 mDNSexport mStatus
mDNSPlatformInit( mDNS
* const inMDNS
)
321 struct sockaddr_in sa4
;
322 struct sockaddr_in6 sa6
;
326 dlog( kDebugLevelTrace
, DEBUG_NAME
"platform init\n" );
328 // Initialize variables. If the PlatformSupport pointer is not null then just assume that a non-Apple client is
329 // calling mDNS_Init and wants to provide its own storage for the platform-specific data so do not overwrite it.
331 memset( &gMDNSPlatformSupport
, 0, sizeof( gMDNSPlatformSupport
) );
332 if( !inMDNS
->p
) inMDNS
->p
= &gMDNSPlatformSupport
;
333 inMDNS
->p
->interfaceListChangedSocket
= kInvalidSocketRef
;
334 mDNSPlatformOneSecond
= 1000; // Use milliseconds as the quantum of time
336 // Startup WinSock 2.2 or later.
338 err
= WSAStartup( MAKEWORD( kWinSockMajorMin
, kWinSockMinorMin
), &wsaData
);
339 require_noerr( err
, exit
);
341 supported
= ( ( LOBYTE( wsaData
.wVersion
) == kWinSockMajorMin
) && ( HIBYTE( wsaData
.wVersion
) == kWinSockMinorMin
) );
342 require_action( supported
, exit
, err
= mStatus_UnsupportedErr
);
344 inMDNS
->CanReceiveUnicastOn5353
= CanReceiveUnicast();
346 // Setup the HINFO HW/SW strings.
348 #if ( MDNS_SET_HINFO_STRINGS )
349 err
= GetWindowsVersionString( (char *) &inMDNS
->HIHardware
.c
[ 1 ], sizeof( inMDNS
->HIHardware
.c
) - 2 );
351 // Note that GetWindowsVersionString guarantees that the resulting string is always null-terminated,
352 // so the following strlen call is safe
353 inMDNS
->HIHardware
.c
[ 0 ] = (mDNSu8
) mDNSPlatformStrLen( &inMDNS
->HIHardware
.c
[ 1 ] );
354 dlog( kDebugLevelInfo
, DEBUG_NAME
"HIHardware: %#s\n", inMDNS
->HIHardware
.c
);
356 mDNS_snprintf( (char *) &inMDNS
->HISoftware
.c
[ 1 ], sizeof( inMDNS
->HISoftware
.c
) - 2,
357 "mDNSResponder (%s %s)", __DATE__
, __TIME__
);
358 inMDNS
->HISoftware
.c
[ 0 ] = (mDNSu8
) mDNSPlatformStrLen( &inMDNS
->HISoftware
.c
[ 1 ] );
359 dlog( kDebugLevelInfo
, DEBUG_NAME
"HISoftware: %#s\n", inMDNS
->HISoftware
.c
);
364 inMDNS
->p
->vpcCheckCount
= 0;
365 inMDNS
->p
->vpcCheckEvent
= NULL
;
366 inMDNS
->p
->timersCount
= 0;
368 // Set up the IPv4 unicast socket
370 inMDNS
->p
->unicastSock4
= INVALID_SOCKET
;
371 inMDNS
->p
->unicastSock4ReadEvent
= NULL
;
372 inMDNS
->p
->unicastSock4RecvMsgPtr
= NULL
;
374 #if ( MDNS_WINDOWS_ENABLE_IPV4 )
376 sa4
.sin_family
= AF_INET
;
377 sa4
.sin_addr
.s_addr
= INADDR_ANY
;
378 err
= SetupSocket( inMDNS
, (const struct sockaddr
*) &sa4
, zeroIPPort
, &inMDNS
->p
->unicastSock4
);
380 sa4len
= sizeof( sa4
);
381 err
= getsockname( inMDNS
->p
->unicastSock4
, (struct sockaddr
*) &sa4
, &sa4len
);
382 require_noerr( err
, exit
);
383 inMDNS
->UnicastPort4
.NotAnInteger
= sa4
.sin_port
;
384 inMDNS
->p
->unicastSock4ReadEvent
= CreateEvent( NULL
, FALSE
, FALSE
, NULL
);
385 err
= translate_errno( inMDNS
->p
->unicastSock4ReadEvent
, (mStatus
) GetLastError(), kUnknownErr
);
386 require_noerr( err
, exit
);
387 err
= WSAEventSelect( inMDNS
->p
->unicastSock4
, inMDNS
->p
->unicastSock4ReadEvent
, FD_READ
);
388 require_noerr( err
, exit
);
389 #if( !TARGET_OS_WINDOWS_CE )
393 err
= WSAIoctl( inMDNS
->p
->unicastSock4
, SIO_GET_EXTENSION_FUNCTION_POINTER
, &kWSARecvMsgGUID
,
394 sizeof( kWSARecvMsgGUID
), &inMDNS
->p
->unicastSock4RecvMsgPtr
, sizeof( inMDNS
->p
->unicastSock4RecvMsgPtr
), &size
, NULL
, NULL
);
398 inMDNS
->p
->unicastSock4RecvMsgPtr
= NULL
;
405 // Set up the IPv6 unicast socket
407 inMDNS
->p
->unicastSock6
= INVALID_SOCKET
;
408 inMDNS
->p
->unicastSock6ReadEvent
= NULL
;
409 inMDNS
->p
->unicastSock6RecvMsgPtr
= NULL
;
411 #if ( MDNS_WINDOWS_ENABLE_IPV6 )
413 sa6
.sin6_family
= AF_INET6
;
414 sa6
.sin6_addr
= in6addr_any
;
415 sa6
.sin6_scope_id
= 0;
417 // This call will fail if the machine hasn't installed IPv6. In that case,
418 // the error will be WSAEAFNOSUPPORT.
420 err
= SetupSocket( inMDNS
, (const struct sockaddr
*) &sa6
, zeroIPPort
, &inMDNS
->p
->unicastSock6
);
421 require_action( !err
|| ( err
== WSAEAFNOSUPPORT
), exit
, err
= (mStatus
) WSAGetLastError() );
422 inMDNS
->p
->unicastSock6ReadEvent
= CreateEvent( NULL
, FALSE
, FALSE
, NULL
);
423 err
= translate_errno( inMDNS
->p
->unicastSock6ReadEvent
, (mStatus
) GetLastError(), kUnknownErr
);
424 require_noerr( err
, exit
);
426 // If we weren't able to create the socket (because IPv6 hasn't been installed) don't do this
428 if ( inMDNS
->p
->unicastSock6
!= INVALID_SOCKET
)
430 sa6len
= sizeof( sa6
);
431 err
= getsockname( inMDNS
->p
->unicastSock6
, (struct sockaddr
*) &sa6
, &sa6len
);
432 require_noerr( err
, exit
);
433 inMDNS
->UnicastPort6
.NotAnInteger
= sa6
.sin6_port
;
435 err
= WSAEventSelect( inMDNS
->p
->unicastSock6
, inMDNS
->p
->unicastSock6ReadEvent
, FD_READ
);
436 require_noerr( err
, exit
);
438 #if( !TARGET_OS_WINDOWS_CE )
442 err
= WSAIoctl( inMDNS
->p
->unicastSock6
, SIO_GET_EXTENSION_FUNCTION_POINTER
, &kWSARecvMsgGUID
,
443 sizeof( kWSARecvMsgGUID
), &inMDNS
->p
->unicastSock6RecvMsgPtr
, sizeof( inMDNS
->p
->unicastSock6RecvMsgPtr
), &size
, NULL
, NULL
);
447 inMDNS
->p
->unicastSock6RecvMsgPtr
= NULL
;
455 // Set up the mDNS thread.
457 err
= SetupSynchronizationObjects( inMDNS
);
458 require_noerr( err
, exit
);
460 err
= SetupThread( inMDNS
);
461 require_noerr( err
, exit
);
465 mDNSCoreInitComplete( inMDNS
, err
);
470 mDNSPlatformClose( inMDNS
);
472 dlog( kDebugLevelTrace
, DEBUG_NAME
"platform init done (err=%d %m)\n", err
, err
);
476 //===========================================================================================================================
478 //===========================================================================================================================
480 mDNSexport
void mDNSPlatformClose( mDNS
* const inMDNS
)
484 dlog( kDebugLevelTrace
, DEBUG_NAME
"platform close\n" );
487 // Tear everything down in reverse order to how it was set up.
489 err
= TearDownThread( inMDNS
);
492 err
= TearDownInterfaceList( inMDNS
);
494 check( !inMDNS
->p
->inactiveInterfaceList
);
496 err
= TearDownRetryVPCCheck( inMDNS
);
499 err
= TearDownSynchronizationObjects( inMDNS
);
502 #if ( MDNS_WINDOWS_ENABLE_IPV4 )
504 if ( inMDNS
->p
->unicastSock4ReadEvent
)
506 CloseHandle( inMDNS
->p
->unicastSock4ReadEvent
);
507 inMDNS
->p
->unicastSock4ReadEvent
= 0;
510 if ( IsValidSocket( inMDNS
->p
->unicastSock4
) )
512 close_compat( inMDNS
->p
->unicastSock4
);
517 #if ( MDNS_WINDOWS_ENABLE_IPV6 )
519 if ( inMDNS
->p
->unicastSock6ReadEvent
)
521 CloseHandle( inMDNS
->p
->unicastSock6ReadEvent
);
522 inMDNS
->p
->unicastSock6ReadEvent
= 0;
525 if ( IsValidSocket( inMDNS
->p
->unicastSock6
) )
527 close_compat( inMDNS
->p
->unicastSock6
);
532 // Free the DLL needed for IPv6 support.
534 #if( MDNS_WINDOWS_USE_IPV6_IF_ADDRS )
535 if( gIPHelperLibraryInstance
)
537 gGetAdaptersAddressesFunctionPtr
= NULL
;
539 FreeLibrary( gIPHelperLibraryInstance
);
540 gIPHelperLibraryInstance
= NULL
;
546 dlog( kDebugLevelTrace
, DEBUG_NAME
"platform close done\n" );
549 //===========================================================================================================================
550 // mDNSPlatformSendUDP
551 //===========================================================================================================================
555 const mDNS
* const inMDNS
,
556 const void * const inMsg
,
557 const mDNSu8
* const inMsgEnd
,
558 mDNSInterfaceID inInterfaceID
,
559 const mDNSAddr
* inDstIP
,
560 mDNSIPPort inDstPort
)
562 SOCKET sendingsocket
= INVALID_SOCKET
;
563 mStatus err
= mStatus_NoError
;
564 mDNSInterfaceData
* ifd
= (mDNSInterfaceData
*) inInterfaceID
;
565 struct sockaddr_storage addr
;
568 DEBUG_USE_ONLY( inMDNS
);
570 n
= (int)( inMsgEnd
- ( (const mDNSu8
* const) inMsg
) );
576 dlog( kDebugLevelChatty
, DEBUG_NAME
"platform send %d bytes to %#a:%u\n", n
, inDstIP
, ntohs( inDstPort
.NotAnInteger
) );
578 if( inDstIP
->type
== mDNSAddrType_IPv4
)
580 struct sockaddr_in
* sa4
;
582 sa4
= (struct sockaddr_in
*) &addr
;
583 sa4
->sin_family
= AF_INET
;
584 sa4
->sin_port
= inDstPort
.NotAnInteger
;
585 sa4
->sin_addr
.s_addr
= inDstIP
->ip
.v4
.NotAnInteger
;
586 sendingsocket
= ifd
? ifd
->sock
: inMDNS
->p
->unicastSock4
;
588 else if( inDstIP
->type
== mDNSAddrType_IPv6
)
590 struct sockaddr_in6
* sa6
;
592 sa6
= (struct sockaddr_in6
*) &addr
;
593 sa6
->sin6_family
= AF_INET6
;
594 sa6
->sin6_port
= inDstPort
.NotAnInteger
;
595 sa6
->sin6_flowinfo
= 0;
596 sa6
->sin6_addr
= *( (struct in6_addr
*) &inDstIP
->ip
.v6
);
597 sa6
->sin6_scope_id
= 0; // Windows requires the scope ID to be zero. IPV6_MULTICAST_IF specifies interface.
598 sendingsocket
= ifd
? ifd
->sock
: inMDNS
->p
->unicastSock6
;
602 dlog( kDebugLevelError
, DEBUG_NAME
"%s: dst is not an IPv4 or IPv6 address (type=%d)\n", __ROUTINE__
, inDstIP
->type
);
603 err
= mStatus_BadParamErr
;
607 if (IsValidSocket(sendingsocket
))
609 n
= sendto( sendingsocket
, (char *) inMsg
, n
, 0, (struct sockaddr
*) &addr
, sizeof( addr
) );
610 err
= translate_errno( n
> 0, errno_compat(), kWriteErr
);
614 // Don't report EHOSTDOWN (i.e. ARP failure), ENETDOWN, or no route to host for unicast destinations
616 if ( !mDNSAddressIsAllDNSLinkGroup( inDstIP
) && ( WSAGetLastError() == WSAEHOSTDOWN
|| WSAGetLastError() == WSAENETDOWN
|| WSAGetLastError() == WSAEHOSTUNREACH
|| WSAGetLastError() == WSAENETUNREACH
) )
618 err
= mStatus_TransientErr
;
622 require_noerr( err
, exit
);
631 //===========================================================================================================================
633 //===========================================================================================================================
635 mDNSexport
void mDNSPlatformLock( const mDNS
* const inMDNS
)
639 if ( inMDNS
->p
->lockInitialized
)
641 EnterCriticalSection( &inMDNS
->p
->lock
);
645 //===========================================================================================================================
646 // mDNSPlatformUnlock
647 //===========================================================================================================================
649 mDNSexport
void mDNSPlatformUnlock( const mDNS
* const inMDNS
)
654 if ( inMDNS
->p
->lockInitialized
)
656 check( inMDNS
->p
->threadID
);
658 // Signal a wakeup event if when called from a task other than the mDNS task since if we are called from mDNS task,
659 // we'll loop back and call mDNS_Execute anyway. Signaling is needed to re-evaluate the wakeup via mDNS_Execute.
661 if( GetCurrentThreadId() != inMDNS
->p
->threadID
)
665 wasSet
= SetEvent( inMDNS
->p
->wakeupEvent
);
666 check_translated_errno( wasSet
, GetLastError(), kUnknownErr
);
668 LeaveCriticalSection( &inMDNS
->p
->lock
);
672 //===========================================================================================================================
673 // mDNSPlatformStrCopy
674 //===========================================================================================================================
676 mDNSexport
void mDNSPlatformStrCopy( void *inDst
, const void *inSrc
)
681 strcpy( (char *) inDst
, (const char*) inSrc
);
684 //===========================================================================================================================
685 // mDNSPlatformStrLen
686 //===========================================================================================================================
688 mDNSexport mDNSu32
mDNSPlatformStrLen( const void *inSrc
)
692 return( (mDNSu32
) strlen( (const char *) inSrc
) );
695 //===========================================================================================================================
696 // mDNSPlatformMemCopy
697 //===========================================================================================================================
699 mDNSexport
void mDNSPlatformMemCopy( void *inDst
, const void *inSrc
, mDNSu32 inSize
)
704 memcpy( inDst
, inSrc
, inSize
);
707 //===========================================================================================================================
708 // mDNSPlatformMemSame
709 //===========================================================================================================================
711 mDNSexport mDNSBool
mDNSPlatformMemSame( const void *inDst
, const void *inSrc
, mDNSu32 inSize
)
716 return( (mDNSBool
)( memcmp( inSrc
, inDst
, inSize
) == 0 ) );
719 //===========================================================================================================================
720 // mDNSPlatformMemZero
721 //===========================================================================================================================
723 mDNSexport
void mDNSPlatformMemZero( void *inDst
, mDNSu32 inSize
)
727 memset( inDst
, 0, inSize
);
730 //===========================================================================================================================
731 // mDNSPlatformMemAllocate
732 //===========================================================================================================================
734 mDNSexport
void * mDNSPlatformMemAllocate( mDNSu32 inSize
)
740 mem
= malloc( inSize
);
746 //===========================================================================================================================
747 // mDNSPlatformMemFree
748 //===========================================================================================================================
750 mDNSexport
void mDNSPlatformMemFree( void *inMem
)
757 //===========================================================================================================================
758 // mDNSPlatformRandomSeed
759 //===========================================================================================================================
761 mDNSexport mDNSu32
mDNSPlatformRandomSeed(void)
763 return( GetTickCount() );
766 //===========================================================================================================================
767 // mDNSPlatformTimeInit
768 //===========================================================================================================================
770 mDNSexport mStatus
mDNSPlatformTimeInit( void )
772 // No special setup is required on Windows -- we just use GetTickCount().
773 return( mStatus_NoError
);
776 //===========================================================================================================================
777 // mDNSPlatformRawTime
778 //===========================================================================================================================
780 mDNSexport mDNSs32
mDNSPlatformRawTime( void )
782 return( (mDNSs32
) GetTickCount() );
785 //===========================================================================================================================
787 //===========================================================================================================================
789 mDNSexport mDNSs32
mDNSPlatformUTC( void )
791 return ( mDNSs32
) time( NULL
);
794 //===========================================================================================================================
795 // mDNSPlatformInterfaceNameToID
796 //===========================================================================================================================
798 mDNSexport mStatus
mDNSPlatformInterfaceNameToID( mDNS
* const inMDNS
, const char *inName
, mDNSInterfaceID
*outID
)
801 mDNSInterfaceData
* ifd
;
807 // Search for an interface with the specified name,
809 for( ifd
= inMDNS
->p
->interfaceList
; ifd
; ifd
= ifd
->next
)
811 if( strcmp( ifd
->name
, inName
) == 0 )
816 require_action_quiet( ifd
, exit
, err
= mStatus_NoSuchNameErr
);
822 *outID
= (mDNSInterfaceID
) ifd
;
824 err
= mStatus_NoError
;
830 //===========================================================================================================================
831 // mDNSPlatformInterfaceIDToInfo
832 //===========================================================================================================================
834 mDNSexport mStatus
mDNSPlatformInterfaceIDToInfo( mDNS
* const inMDNS
, mDNSInterfaceID inID
, mDNSPlatformInterfaceInfo
*outInfo
)
837 mDNSInterfaceData
* ifd
;
843 // Search for an interface with the specified ID,
845 for( ifd
= inMDNS
->p
->interfaceList
; ifd
; ifd
= ifd
->next
)
847 if( ifd
== (mDNSInterfaceData
*) inID
)
852 require_action_quiet( ifd
, exit
, err
= mStatus_NoSuchNameErr
);
856 outInfo
->name
= ifd
->name
;
857 outInfo
->ip
= ifd
->interfaceInfo
.ip
;
858 err
= mStatus_NoError
;
864 //===========================================================================================================================
865 // mDNSPlatformInterfaceIDfromInterfaceIndex
866 //===========================================================================================================================
868 mDNSexport mDNSInterfaceID
mDNSPlatformInterfaceIDfromInterfaceIndex( mDNS
* const inMDNS
, mDNSu32 inIndex
)
873 if( inIndex
== kDNSServiceInterfaceIndexLocalOnly
)
875 id
= mDNSInterface_LocalOnly
;
877 else if( inIndex
!= 0 )
879 mDNSInterfaceData
* ifd
;
881 for( ifd
= inMDNS
->p
->interfaceList
; ifd
; ifd
= ifd
->next
)
883 if( ( ifd
->scopeID
== inIndex
) && ifd
->interfaceInfo
.InterfaceActive
)
885 id
= ifd
->interfaceInfo
.InterfaceID
;
894 //===========================================================================================================================
895 // mDNSPlatformInterfaceIndexfromInterfaceID
896 //===========================================================================================================================
898 mDNSexport mDNSu32
mDNSPlatformInterfaceIndexfromInterfaceID( mDNS
* const inMDNS
, mDNSInterfaceID inID
)
903 if( inID
== mDNSInterface_LocalOnly
)
905 index
= (mDNSu32
) kDNSServiceInterfaceIndexLocalOnly
;
909 mDNSInterfaceData
* ifd
;
911 // Search active interfaces.
912 for( ifd
= inMDNS
->p
->interfaceList
; ifd
; ifd
= ifd
->next
)
914 if( (mDNSInterfaceID
) ifd
== inID
)
916 index
= ifd
->scopeID
;
921 // Search inactive interfaces too so remove events for inactive interfaces report the old interface index.
925 for( ifd
= inMDNS
->p
->inactiveInterfaceList
; ifd
; ifd
= ifd
->next
)
927 if( (mDNSInterfaceID
) ifd
== inID
)
929 index
= ifd
->scopeID
;
939 //===========================================================================================================================
940 // mDNSPlatformTCPSocket
941 //===========================================================================================================================
944 mDNSPlatformTCPSocket
947 TCPSocketFlags flags
,
951 TCPSocket
* sock
= NULL
;
952 u_long on
= 1; // "on" for setsockopt
953 struct sockaddr_in saddr
;
955 mStatus err
= mStatus_NoError
;
959 require_action( flags
== 0, exit
, err
= mStatus_UnsupportedErr
);
961 // Setup connection data object
963 sock
= (TCPSocket
*) malloc( sizeof( TCPSocket
) );
964 require_action( sock
, exit
, err
= mStatus_NoMemoryErr
);
965 memset( sock
, 0, sizeof( TCPSocket
) );
967 sock
->fd
= INVALID_SOCKET
;
970 bzero(&saddr
, sizeof(saddr
));
971 saddr
.sin_family
= AF_INET
;
972 saddr
.sin_addr
.s_addr
= htonl( INADDR_ANY
);
973 saddr
.sin_port
= port
->NotAnInteger
;
977 sock
->fd
= socket(AF_INET
, SOCK_STREAM
, 0);
978 err
= translate_errno( sock
->fd
!= INVALID_SOCKET
, WSAGetLastError(), mStatus_UnknownErr
);
979 require_noerr( err
, exit
);
981 // Set it to be non-blocking
983 err
= ioctlsocket( sock
->fd
, FIONBIO
, &on
);
984 err
= translate_errno( err
== 0, WSAGetLastError(), mStatus_UnknownErr
);
985 require_noerr( err
, exit
);
989 memset( &saddr
, 0, sizeof( saddr
) );
990 len
= sizeof( saddr
);
992 err
= getsockname( sock
->fd
, ( struct sockaddr
* ) &saddr
, &len
);
993 err
= translate_errno( err
== 0, WSAGetLastError(), mStatus_UnknownErr
);
994 require_noerr( err
, exit
);
996 port
->NotAnInteger
= saddr
.sin_port
;
1002 FreeTCPSocket( sock
);
1009 //===========================================================================================================================
1010 // mDNSPlatformTCPConnect
1011 //===========================================================================================================================
1014 mDNSPlatformTCPConnect
1017 const mDNSAddr
* inDstIP
,
1018 mDNSOpaque16 inDstPort
,
1019 mDNSInterfaceID inInterfaceID
,
1020 TCPConnectionCallback inCallback
,
1024 struct sockaddr_in saddr
;
1025 mStatus err
= mStatus_NoError
;
1027 DEBUG_UNUSED( inInterfaceID
);
1029 if ( inDstIP
->type
!= mDNSAddrType_IPv4
)
1031 LogMsg("ERROR: mDNSPlatformTCPConnect - attempt to connect to an IPv6 address: operation not supported");
1032 return mStatus_UnknownErr
;
1035 // Setup connection data object
1037 sock
->callback
= inCallback
;
1038 sock
->context
= inContext
;
1040 bzero(&saddr
, sizeof(saddr
));
1041 saddr
.sin_family
= AF_INET
;
1042 saddr
.sin_port
= inDstPort
.NotAnInteger
;
1043 memcpy(&saddr
.sin_addr
, &inDstIP
->ip
.v4
.NotAnInteger
, sizeof(saddr
.sin_addr
));
1045 // Try and do connect
1047 err
= connect( sock
->fd
, ( struct sockaddr
* ) &saddr
, sizeof( saddr
) );
1048 require_action( !err
|| ( WSAGetLastError() == WSAEWOULDBLOCK
), exit
, err
= mStatus_ConnFailed
);
1049 sock
->connected
= !err
? TRUE
: FALSE
;
1050 sock
->pendingEvent
= CreateEvent( NULL
, FALSE
, FALSE
, NULL
);
1051 err
= translate_errno( sock
->pendingEvent
, GetLastError(), mStatus_UnknownErr
);
1052 require_noerr( err
, exit
);
1053 err
= WSAEventSelect( sock
->fd
, sock
->pendingEvent
, FD_CONNECT
|FD_READ
|FD_CLOSE
);
1054 require_noerr( err
, exit
);
1058 sock
->next
= gTCPConnectionList
;
1059 gTCPConnectionList
= sock
;
1061 gWaitListChanged
= TRUE
;
1067 err
= sock
->connected
? mStatus_ConnEstablished
: mStatus_ConnPending
;
1073 //===========================================================================================================================
1074 // mDNSPlatformTCPAccept
1075 //===========================================================================================================================
1078 mDNSexport TCPSocket
*mDNSPlatformTCPAccept( TCPSocketFlags flags
, int fd
)
1080 TCPSocket
* sock
= NULL
;
1081 mStatus err
= mStatus_NoError
;
1083 require_action( !flags
, exit
, err
= mStatus_UnsupportedErr
);
1085 sock
= malloc( sizeof( TCPSocket
) );
1086 require_action( sock
, exit
, err
= mStatus_NoMemoryErr
);
1088 memset( sock
, 0, sizeof( *sock
) );
1091 sock
->flags
= flags
;
1105 //===========================================================================================================================
1106 // mDNSPlatformTCPCloseConnection
1107 //===========================================================================================================================
1109 mDNSexport
void mDNSPlatformTCPCloseConnection( TCPSocket
*sock
)
1111 TCPSocket
* inserted
= gTCPConnectionList
;
1112 TCPSocket
* last
= NULL
;
1116 if ( inserted
== sock
)
1120 gTCPConnectionList
= inserted
->next
;
1124 last
->next
= inserted
->next
;
1128 gWaitListChanged
= TRUE
;
1134 inserted
= inserted
->next
;
1137 FreeTCPSocket( sock
);
1140 //===========================================================================================================================
1141 // mDNSPlatformReadTCP
1142 //===========================================================================================================================
1144 mDNSexport
long mDNSPlatformReadTCP( TCPSocket
*sock
, void *inBuffer
, unsigned long inBufferSize
, mDNSBool
* closed
)
1148 nread
= recv( sock
->fd
, inBuffer
, inBufferSize
, 0);
1152 if ( WSAGetLastError() == WSAEWOULDBLOCK
)
1169 //===========================================================================================================================
1170 // mDNSPlatformWriteTCP
1171 //===========================================================================================================================
1173 mDNSexport
long mDNSPlatformWriteTCP( TCPSocket
*sock
, const char *inMsg
, unsigned long inMsgSize
)
1178 nsent
= send( sock
->fd
, inMsg
, inMsgSize
, 0 );
1180 err
= translate_errno( ( nsent
>= 0 ) || ( WSAGetLastError() == WSAEWOULDBLOCK
), WSAGetLastError(), mStatus_UnknownErr
);
1181 require_noerr( err
, exit
);
1193 //===========================================================================================================================
1194 // mDNSPlatformTCPGetFD
1195 //===========================================================================================================================
1197 mDNSexport
int mDNSPlatformTCPGetFD(TCPSocket
*sock
)
1199 return ( int ) sock
->fd
;
1202 //===========================================================================================================================
1203 // mDNSPlatformUDPSocket
1204 //===========================================================================================================================
1206 mDNSexport UDPSocket
*mDNSPlatformUDPSocket
1213 DEBUG_UNUSED( port
);
1218 //===========================================================================================================================
1219 // mDNSPlatformUDPClose
1220 //===========================================================================================================================
1222 mDNSexport
void mDNSPlatformUDPClose( UDPSocket
*sock
)
1224 DEBUG_UNUSED( sock
);
1228 //===========================================================================================================================
1229 // mDNSPlatformTLSSetupCerts
1230 //===========================================================================================================================
1233 mDNSPlatformTLSSetupCerts(void)
1235 return mStatus_UnsupportedErr
;
1238 //===========================================================================================================================
1239 // mDNSPlatformTLSTearDownCerts
1240 //===========================================================================================================================
1243 mDNSPlatformTLSTearDownCerts(void)
1247 //===========================================================================================================================
1248 // mDNSPlatformSetDNSConfig
1249 //===========================================================================================================================
1251 mDNSlocal
void SetDNSServers( mDNS
*const m
);
1252 mDNSlocal
void SetSearchDomainList( void );
1255 mDNSexport
void mDNSPlatformSetDNSConfig(mDNS
*const m
, mDNSBool setservers
, mDNSBool setsearch
, domainname
*const fqdn
, DNameListElem
**RegDomains
, DNameListElem
**browseDomains
)
1258 char subKeyName
[kRegistryMaxKeyLength
+ 1];
1270 if (setservers
) SetDNSServers(m
);
1271 if (setsearch
) SetSearchDomainList();
1277 *browseDomains
= NULL
;
1279 err
= RegCreateKey( HKEY_LOCAL_MACHINE
, kServiceParametersNode
TEXT("\\DynDNS\\Setup\\") kServiceDynDNSHostNames
, &key
);
1280 require_noerr( err
, exit
);
1282 err
= RegQueryString( key
, "", &name
, &dwSize
, &enabled
);
1283 if ( !err
&& ( name
[0] != '\0' ) && enabled
)
1285 if ( !MakeDomainNameFromDNSNameString( fqdn
, name
) || !fqdn
->c
[0] )
1287 dlog( kDebugLevelError
, "bad DDNS host name in registry: %s", name
[0] ? name
: "(unknown)");
1303 err
= RegCreateKey( HKEY_LOCAL_MACHINE
, kServiceParametersNode
TEXT("\\DynDNS\\Setup\\") kServiceDynDNSBrowseDomains
, &key
);
1304 require_noerr( err
, exit
);
1306 // Get information about this node
1308 err
= RegQueryInfoKey( key
, NULL
, NULL
, NULL
, &cSubKeys
, &cbMaxSubKey
, &cchMaxClass
, NULL
, NULL
, NULL
, NULL
, NULL
);
1309 require_noerr( err
, exit
);
1311 for ( i
= 0; i
< cSubKeys
; i
++)
1315 dwSize
= kRegistryMaxKeyLength
;
1317 err
= RegEnumKeyExA( key
, i
, subKeyName
, &dwSize
, NULL
, NULL
, NULL
, NULL
);
1321 err
= RegOpenKeyExA( key
, subKeyName
, 0, KEY_READ
, &subKey
);
1322 require_noerr( err
, exit
);
1324 dwSize
= sizeof( DWORD
);
1325 err
= RegQueryValueExA( subKey
, "Enabled", NULL
, NULL
, (LPBYTE
) &enabled
, &dwSize
);
1327 if ( !err
&& ( subKeyName
[0] != '\0' ) && enabled
)
1329 if ( !MakeDomainNameFromDNSNameString( &dname
, subKeyName
) || !dname
.c
[0] )
1331 dlog( kDebugLevelError
, "bad DDNS browse domain in registry: %s", subKeyName
[0] ? subKeyName
: "(unknown)");
1335 DNameListElem
* browseDomain
= (DNameListElem
*) malloc( sizeof( DNameListElem
) );
1336 require_action( browseDomain
, exit
, err
= mStatus_NoMemoryErr
);
1338 AssignDomainName(&browseDomain
->name
, &dname
);
1339 browseDomain
->next
= *browseDomains
;
1341 *browseDomains
= browseDomain
;
1345 RegCloseKey( subKey
);
1356 err
= RegCreateKey( HKEY_LOCAL_MACHINE
, kServiceParametersNode
TEXT("\\DynDNS\\Setup\\") kServiceDynDNSRegistrationDomains
, &key
);
1357 require_noerr( err
, exit
);
1359 err
= RegQueryString( key
, "", &name
, &dwSize
, &enabled
);
1360 if ( !err
&& ( name
[0] != '\0' ) && enabled
)
1362 *RegDomains
= (DNameListElem
*) malloc( sizeof( DNameListElem
) );
1363 if (!*RegDomains
) dlog( kDebugLevelError
, "No memory");
1366 (*RegDomains
)->next
= mDNSNULL
;
1367 if ( !MakeDomainNameFromDNSNameString( &(*RegDomains
)->name
, name
) || (*RegDomains
)->name
.c
[0] )
1369 dlog( kDebugLevelError
, "bad DDNS registration domain in registry: %s", name
[0] ? name
: "(unknown)");
1378 RegCloseKey( subKey
);
1393 //===========================================================================================================================
1394 // mDNSPlatformDynDNSHostNameStatusChanged
1395 //===========================================================================================================================
1398 mDNSPlatformDynDNSHostNameStatusChanged(domainname
*const dname
, mStatus status
)
1400 char uname
[MAX_ESCAPED_DOMAIN_NAME
];
1406 ConvertDomainNameToCString(dname
, uname
);
1412 *p
= (char) tolower(*p
);
1413 if (!(*(p
+1)) && *p
== '.') *p
= 0; // if last character, strip trailing dot
1417 check( strlen( p
) <= MAX_ESCAPED_DOMAIN_NAME
);
1418 name
= kServiceParametersNode
TEXT("\\DynDNS\\State\\HostNames");
1419 err
= RegCreateKey( HKEY_LOCAL_MACHINE
, name
, &key
);
1420 require_noerr( err
, exit
);
1422 status
= ( status
) ? 0 : 1;
1423 err
= RegSetValueEx( key
, kServiceDynDNSStatus
, 0, REG_DWORD
, (const LPBYTE
) &status
, sizeof(DWORD
) );
1424 require_noerr( err
, exit
);
1437 //===========================================================================================================================
1439 //===========================================================================================================================
1441 // This routine needs to be called whenever the system secrets database changes.
1442 // Right now I call it from ProcessingThreadDynDNSConfigChanged, which may or may not be sufficient.
1443 // Also, it needs to call mDNS_SetSecretForDomain() for *every* configured DNS domain/secret pair
1444 // in the database, not just inDomain (the inDomain parameter should be deleted).
1447 SetDomainSecrets( mDNS
* const m
, const domainname
* inDomain
)
1454 LSA_OBJECT_ATTRIBUTES attrs
;
1455 LSA_HANDLE handle
= NULL
;
1459 // Initialize PolyStrings
1461 domain
.m_lsa
= NULL
;
1463 secret
.m_lsa
= NULL
;
1465 // canonicalize name by converting to lower case (keychain and some name servers are case sensitive)
1467 ConvertDomainNameToCString( inDomain
, domain
.m_utf8
);
1468 dlen
= strlen( domain
.m_utf8
);
1469 for ( i
= 0; i
< dlen
; i
++ )
1471 domain
.m_utf8
[i
] = (char) tolower( domain
.m_utf8
[i
] ); // canonicalize -> lower case
1474 MakeDomainNameFromDNSNameString( &domain
.m_dname
, domain
.m_utf8
);
1476 // attrs are reserved, so initialize to zeroes.
1478 ZeroMemory( &attrs
, sizeof( attrs
) );
1480 // Get a handle to the Policy object on the local system
1482 res
= LsaOpenPolicy( NULL
, &attrs
, POLICY_GET_PRIVATE_INFORMATION
, &handle
);
1483 err
= translate_errno( res
== 0, LsaNtStatusToWinError( res
), kUnknownErr
);
1484 require_noerr( err
, exit
);
1486 // Get the encrypted data
1488 domain
.m_lsa
= ( PLSA_UNICODE_STRING
) malloc( sizeof( LSA_UNICODE_STRING
) );
1489 require_action( domain
.m_lsa
!= NULL
, exit
, err
= mStatus_NoMemoryErr
);
1490 err
= MakeLsaStringFromUTF8String( domain
.m_lsa
, domain
.m_utf8
);
1491 require_noerr( err
, exit
);
1495 res
= LsaRetrievePrivateData( handle
, domain
.m_lsa
, &key
.m_lsa
);
1496 err
= translate_errno( res
== 0, LsaNtStatusToWinError( res
), kUnknownErr
);
1497 require_noerr_quiet( err
, exit
);
1499 // <rdar://problem/4192119> Lsa secrets use a flat naming space. Therefore, we will prepend "$" to the keyname to
1500 // make sure it doesn't conflict with a zone name.
1502 // Convert the key to a domainname. Strip off the "$" prefix.
1504 err
= MakeUTF8StringFromLsaString( key
.m_utf8
, sizeof( key
.m_utf8
), key
.m_lsa
);
1505 require_noerr( err
, exit
);
1506 require_action( key
.m_utf8
[0] == '$', exit
, err
= kUnknownErr
);
1507 MakeDomainNameFromDNSNameString( &key
.m_dname
, key
.m_utf8
+ 1 );
1509 // Retrieve the secret
1511 res
= LsaRetrievePrivateData( handle
, key
.m_lsa
, &secret
.m_lsa
);
1512 err
= translate_errno( res
== 0, LsaNtStatusToWinError( res
), kUnknownErr
);
1513 require_noerr_quiet( err
, exit
);
1515 // Convert the secret to UTF8 string
1517 err
= MakeUTF8StringFromLsaString( secret
.m_utf8
, sizeof( secret
.m_utf8
), secret
.m_lsa
);
1518 require_noerr( err
, exit
);
1520 // And finally, tell the core about this secret
1522 debugf("Setting shared secret for zone %s with key %##s", domain
.m_utf8
, key
.m_dname
.c
);
1523 mDNS_SetSecretForDomain( m
, &domain
.m_dname
, &key
.m_dname
, secret
.m_utf8
, mDNSfalse
);
1527 if ( domain
.m_lsa
!= NULL
)
1529 if ( domain
.m_lsa
->Buffer
!= NULL
)
1531 free( domain
.m_lsa
->Buffer
);
1534 free( domain
.m_lsa
);
1537 if ( key
.m_lsa
!= NULL
)
1539 LsaFreeMemory( key
.m_lsa
);
1542 if ( secret
.m_lsa
!= NULL
)
1544 LsaFreeMemory( secret
.m_lsa
);
1555 //===========================================================================================================================
1556 // SetSearchDomainList
1557 //===========================================================================================================================
1559 mDNSlocal
void SetDomainFromDHCP( void );
1560 mDNSlocal
void SetReverseMapSearchDomainList( void );
1563 SetSearchDomainList( void )
1565 char * searchList
= NULL
;
1566 DWORD searchListLen
;
1567 DNameListElem
* head
= NULL
;
1568 DNameListElem
* current
= NULL
;
1573 err
= RegCreateKey( HKEY_LOCAL_MACHINE
, TEXT("SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters"), &key
);
1574 require_noerr( err
, exit
);
1576 err
= RegQueryString( key
, "SearchList", &searchList
, &searchListLen
, NULL
);
1577 require_noerr( err
, exit
);
1579 // Windows separates the search domains with ','
1581 tok
= strtok( searchList
, "," );
1584 if ( ( strcmp( tok
, "" ) != 0 ) && ( strcmp( tok
, "." ) != 0 ) )
1585 mDNS_AddSearchDomain_CString(tok
);
1586 tok
= strtok( NULL
, "," );
1601 SetDomainFromDHCP();
1602 SetReverseMapSearchDomainList();
1606 //===========================================================================================================================
1607 // SetReverseMapSearchDomainList
1608 //===========================================================================================================================
1611 SetReverseMapSearchDomainList( void )
1613 struct ifaddrs
* ifa
;
1615 ifa
= myGetIfAddrs( 1 );
1620 if (ifa
->ifa_addr
->sa_family
== AF_INET
&& !SetupAddr(&addr
, ifa
->ifa_addr
) && !(ifa
->ifa_flags
& IFF_LOOPBACK
) && ifa
->ifa_netmask
)
1625 if (!SetupAddr(&netmask
, ifa
->ifa_netmask
))
1627 sprintf(buffer
, "%d.%d.%d.%d.in-addr.arpa.", addr
.ip
.v4
.b
[3] & netmask
.ip
.v4
.b
[3],
1628 addr
.ip
.v4
.b
[2] & netmask
.ip
.v4
.b
[2],
1629 addr
.ip
.v4
.b
[1] & netmask
.ip
.v4
.b
[1],
1630 addr
.ip
.v4
.b
[0] & netmask
.ip
.v4
.b
[0]);
1631 mDNS_AddSearchDomain_CString(buffer
);
1635 ifa
= ifa
->ifa_next
;
1642 //===========================================================================================================================
1644 //===========================================================================================================================
1647 SetDNSServers( mDNS
*const m
)
1649 PIP_PER_ADAPTER_INFO pAdapterInfo
= NULL
;
1650 FIXED_INFO
* fixedInfo
= NULL
;
1652 IP_ADDR_STRING
* dnsServerList
;
1653 IP_ADDR_STRING
* ipAddr
;
1656 mStatus err
= kUnknownErr
;
1658 // Get the primary interface.
1660 index
= GetPrimaryInterface();
1662 // This should have the interface index of the primary index. Fall back in cases where
1663 // it can't be determined.
1669 for ( i
= 0; i
< 100; i
++ )
1671 err
= GetPerAdapterInfo( index
, pAdapterInfo
, &bufLen
);
1673 if ( err
!= ERROR_BUFFER_OVERFLOW
)
1678 pAdapterInfo
= (PIP_PER_ADAPTER_INFO
) realloc( pAdapterInfo
, bufLen
);
1679 require_action( pAdapterInfo
, exit
, err
= mStatus_NoMemoryErr
);
1682 require_noerr( err
, exit
);
1684 dnsServerList
= &pAdapterInfo
->DnsServerList
;
1688 bufLen
= sizeof( FIXED_INFO
);
1690 for ( i
= 0; i
< 100; i
++ )
1694 GlobalFree( fixedInfo
);
1698 fixedInfo
= (FIXED_INFO
*) GlobalAlloc( GPTR
, bufLen
);
1699 require_action( fixedInfo
, exit
, err
= mStatus_NoMemoryErr
);
1701 err
= GetNetworkParams( fixedInfo
, &bufLen
);
1703 if ( err
!= ERROR_BUFFER_OVERFLOW
)
1709 require_noerr( err
, exit
);
1711 dnsServerList
= &fixedInfo
->DnsServerList
;
1714 for ( ipAddr
= dnsServerList
; ipAddr
; ipAddr
= ipAddr
->Next
)
1717 err
= StringToAddress( &addr
, ipAddr
->IpAddress
.String
);
1718 if ( !err
) mDNS_AddDNSServer(m
, mDNSNULL
, mDNSInterface_Any
, addr
, UnicastDNSPort
);
1725 free( pAdapterInfo
);
1730 GlobalFree( fixedInfo
);
1735 //===========================================================================================================================
1736 // SetDomainFromDHCP
1737 //===========================================================================================================================
1740 SetDomainFromDHCP( void )
1742 DNameListElem
* head
= NULL
;
1744 IP_ADAPTER_INFO
* pAdapterInfo
;
1745 IP_ADAPTER_INFO
* pAdapter
;
1749 LPSTR domain
= NULL
;
1752 mStatus err
= mStatus_NoError
;
1754 pAdapterInfo
= NULL
;
1756 for ( i
= 0; i
< 100; i
++ )
1758 err
= GetAdaptersInfo( pAdapterInfo
, &bufLen
);
1760 if ( err
!= ERROR_BUFFER_OVERFLOW
)
1765 pAdapterInfo
= (IP_ADAPTER_INFO
*) realloc( pAdapterInfo
, bufLen
);
1766 require_action( pAdapterInfo
, exit
, err
= kNoMemoryErr
);
1769 require_noerr( err
, exit
);
1771 index
= GetPrimaryInterface();
1773 for ( pAdapter
= pAdapterInfo
; pAdapter
; pAdapter
= pAdapter
->Next
)
1775 if ( pAdapter
->IpAddressList
.IpAddress
.String
&&
1776 pAdapter
->IpAddressList
.IpAddress
.String
[0] &&
1777 pAdapter
->GatewayList
.IpAddress
.String
&&
1778 pAdapter
->GatewayList
.IpAddress
.String
[0] &&
1779 ( !index
|| ( pAdapter
->Index
== index
) ) )
1781 // Found one that will work
1785 _snprintf( keyName
, 1024, "%s%s", "SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Interfaces\\", pAdapter
->AdapterName
);
1787 err
= RegCreateKeyA( HKEY_LOCAL_MACHINE
, keyName
, &key
);
1788 require_noerr( err
, exit
);
1790 err
= RegQueryString( key
, "Domain", &domain
, &dwSize
, NULL
);
1793 if ( !domain
|| !domain
[0] )
1801 err
= RegQueryString( key
, "DhcpDomain", &domain
, &dwSize
, NULL
);
1805 if ( domain
&& domain
[0] ) mDNS_AddSearchDomain_CString(domain
);
1815 free( pAdapterInfo
);
1830 //===========================================================================================================================
1831 // mDNSPlatformGetPrimaryInterface
1832 //===========================================================================================================================
1835 mDNSPlatformGetPrimaryInterface( mDNS
* const m
, mDNSAddr
* v4
, mDNSAddr
* v6
, mDNSAddr
* router
)
1837 IP_ADAPTER_INFO
* pAdapterInfo
;
1838 IP_ADAPTER_INFO
* pAdapter
;
1843 mStatus err
= mStatus_NoError
;
1849 pAdapterInfo
= NULL
;
1853 for ( i
= 0; i
< 100; i
++ )
1855 err
= GetAdaptersInfo( pAdapterInfo
, &bufLen
);
1857 if ( err
!= ERROR_BUFFER_OVERFLOW
)
1862 pAdapterInfo
= (IP_ADAPTER_INFO
*) realloc( pAdapterInfo
, bufLen
);
1863 require_action( pAdapterInfo
, exit
, err
= kNoMemoryErr
);
1866 require_noerr( err
, exit
);
1868 index
= GetPrimaryInterface();
1870 for ( pAdapter
= pAdapterInfo
; pAdapter
; pAdapter
= pAdapter
->Next
)
1872 if ( pAdapter
->IpAddressList
.IpAddress
.String
&&
1873 pAdapter
->IpAddressList
.IpAddress
.String
[0] &&
1874 pAdapter
->GatewayList
.IpAddress
.String
&&
1875 pAdapter
->GatewayList
.IpAddress
.String
[0] &&
1876 ( StringToAddress( v4
, pAdapter
->IpAddressList
.IpAddress
.String
) == mStatus_NoError
) &&
1877 ( StringToAddress( router
, pAdapter
->GatewayList
.IpAddress
.String
) == mStatus_NoError
) &&
1878 ( !index
|| ( pAdapter
->Index
== index
) ) )
1880 // Found one that will work
1891 free( pAdapterInfo
);
1902 //===========================================================================================================================
1904 //===========================================================================================================================
1906 #if( MDNS_DEBUGMSGS )
1907 mDNSexport
void debugf_( const char *inFormat
, ... )
1913 va_start( args
, inFormat
);
1914 length
= mDNS_vsnprintf( buffer
, sizeof( buffer
), inFormat
, args
);
1917 dlog( kDebugLevelInfo
, "%s\n", buffer
);
1921 //===========================================================================================================================
1923 //===========================================================================================================================
1925 #if( MDNS_DEBUGMSGS > 1 )
1926 mDNSexport
void verbosedebugf_( const char *inFormat
, ... )
1932 va_start( args
, inFormat
);
1933 length
= mDNS_vsnprintf( buffer
, sizeof( buffer
), inFormat
, args
);
1936 dlog( kDebugLevelVerbose
, "%s\n", buffer
);
1940 //===========================================================================================================================
1942 //===========================================================================================================================
1945 mDNSexport void LogMsg( const char *inFormat, ... )
1951 va_start( args, inFormat );
1952 length = mDNS_vsnprintf( buffer, sizeof( buffer ), inFormat, args );
1955 dlog( kDebugLevelWarning, "%s\n", buffer );
1961 #pragma mark == Platform Internals ==
1964 //===========================================================================================================================
1965 // SetupSynchronizationObjects
1966 //===========================================================================================================================
1968 mDNSlocal mStatus
SetupSynchronizationObjects( mDNS
* const inMDNS
)
1972 InitializeCriticalSection( &inMDNS
->p
->lock
);
1973 inMDNS
->p
->lockInitialized
= mDNStrue
;
1975 inMDNS
->p
->cancelEvent
= CreateEvent( NULL
, FALSE
, FALSE
, NULL
);
1976 err
= translate_errno( inMDNS
->p
->cancelEvent
, (mStatus
) GetLastError(), kUnknownErr
);
1977 require_noerr( err
, exit
);
1979 inMDNS
->p
->quitEvent
= CreateEvent( NULL
, FALSE
, FALSE
, NULL
);
1980 err
= translate_errno( inMDNS
->p
->quitEvent
, (mStatus
) GetLastError(), kUnknownErr
);
1981 require_noerr( err
, exit
);
1983 inMDNS
->p
->interfaceListChangedEvent
= CreateEvent( NULL
, FALSE
, FALSE
, NULL
);
1984 err
= translate_errno( inMDNS
->p
->interfaceListChangedEvent
, (mStatus
) GetLastError(), kUnknownErr
);
1985 require_noerr( err
, exit
);
1987 inMDNS
->p
->wakeupEvent
= CreateEvent( NULL
, FALSE
, FALSE
, NULL
);
1988 err
= translate_errno( inMDNS
->p
->wakeupEvent
, (mStatus
) GetLastError(), kUnknownErr
);
1989 require_noerr( err
, exit
);
1994 TearDownSynchronizationObjects( inMDNS
);
1999 //===========================================================================================================================
2000 // TearDownSynchronizationObjects
2001 //===========================================================================================================================
2003 mDNSlocal mStatus
TearDownSynchronizationObjects( mDNS
* const inMDNS
)
2005 if( inMDNS
->p
->quitEvent
)
2007 CloseHandle( inMDNS
->p
->quitEvent
);
2008 inMDNS
->p
->quitEvent
= 0;
2010 if( inMDNS
->p
->cancelEvent
)
2012 CloseHandle( inMDNS
->p
->cancelEvent
);
2013 inMDNS
->p
->cancelEvent
= 0;
2015 if( inMDNS
->p
->interfaceListChangedEvent
)
2017 CloseHandle( inMDNS
->p
->interfaceListChangedEvent
);
2018 inMDNS
->p
->interfaceListChangedEvent
= 0;
2020 if( inMDNS
->p
->wakeupEvent
)
2022 CloseHandle( inMDNS
->p
->wakeupEvent
);
2023 inMDNS
->p
->wakeupEvent
= 0;
2025 if( inMDNS
->p
->lockInitialized
)
2027 DeleteCriticalSection( &inMDNS
->p
->lock
);
2028 inMDNS
->p
->lockInitialized
= mDNSfalse
;
2030 return( mStatus_NoError
);
2034 //===========================================================================================================================
2036 //===========================================================================================================================
2038 mDNSlocal mStatus
SetupNiceName( mDNS
* const inMDNS
)
2041 char tempString
[ 256 ];
2046 // Set up the nice name.
2047 tempString
[ 0 ] = '\0';
2050 // First try and open the registry key that contains the computer description value
2051 if (inMDNS
->p
->descKey
== NULL
)
2053 LPCTSTR s
= TEXT("SYSTEM\\CurrentControlSet\\Services\\lanmanserver\\parameters");
2054 err
= RegOpenKeyEx( HKEY_LOCAL_MACHINE
, s
, 0, KEY_READ
, &inMDNS
->p
->descKey
);
2055 check_translated_errno( err
== 0, errno_compat(), kNameErr
);
2059 inMDNS
->p
->descKey
= NULL
;
2063 // if we opened it...
2064 if (inMDNS
->p
->descKey
!= NULL
)
2067 DWORD descSize
= sizeof( desc
);
2069 // look for the computer description
2070 err
= RegQueryValueEx(inMDNS
->p
->descKey
, TEXT("srvcomment"), 0, NULL
, (LPBYTE
) &desc
, &descSize
);
2074 err
= TCHARtoUTF8( desc
, utf8
, sizeof( utf8
) );
2083 // if we can't find it in the registry, then use the hostname of the machine
2084 if ( err
|| ( utf8
[ 0 ] == '\0' ) )
2086 DWORD tempStringLen
= sizeof( tempString
);
2089 ok
= GetComputerNameExA( ComputerNamePhysicalDnsHostname
, tempString
, &tempStringLen
);
2090 err
= translate_errno( ok
, (mStatus
) GetLastError(), kNameErr
);
2095 err
= WindowsLatin1toUTF8( tempString
, utf8
, sizeof( utf8
) );
2104 // if we can't get the hostname
2105 if ( err
|| ( utf8
[ 0 ] == '\0' ) )
2107 // Invalidate name so fall back to a default name.
2109 strcpy( utf8
, kMDNSDefaultName
);
2112 utf8
[ sizeof( utf8
) - 1 ] = '\0';
2113 inMDNS
->nicelabel
.c
[ 0 ] = (mDNSu8
) (strlen( utf8
) < MAX_DOMAIN_LABEL
? strlen( utf8
) : MAX_DOMAIN_LABEL
);
2114 memcpy( &inMDNS
->nicelabel
.c
[ 1 ], utf8
, inMDNS
->nicelabel
.c
[ 0 ] );
2116 dlog( kDebugLevelInfo
, DEBUG_NAME
"nice name \"%.*s\"\n", inMDNS
->nicelabel
.c
[ 0 ], &inMDNS
->nicelabel
.c
[ 1 ] );
2122 //===========================================================================================================================
2124 //===========================================================================================================================
2126 mDNSlocal mStatus
SetupHostName( mDNS
* const inMDNS
)
2129 char tempString
[ 256 ];
2130 DWORD tempStringLen
;
2131 domainlabel tempLabel
;
2136 // Set up the nice name.
2137 tempString
[ 0 ] = '\0';
2139 // use the hostname of the machine
2140 tempStringLen
= sizeof( tempString
);
2141 ok
= GetComputerNameExA( ComputerNamePhysicalDnsHostname
, tempString
, &tempStringLen
);
2142 err
= translate_errno( ok
, (mStatus
) GetLastError(), kNameErr
);
2145 // if we can't get the hostname
2146 if( err
|| ( tempString
[ 0 ] == '\0' ) )
2148 // Invalidate name so fall back to a default name.
2150 strcpy( tempString
, kMDNSDefaultName
);
2153 tempString
[ sizeof( tempString
) - 1 ] = '\0';
2154 tempLabel
.c
[ 0 ] = (mDNSu8
) (strlen( tempString
) < MAX_DOMAIN_LABEL
? strlen( tempString
) : MAX_DOMAIN_LABEL
);
2155 memcpy( &tempLabel
.c
[ 1 ], tempString
, tempLabel
.c
[ 0 ] );
2157 // Set up the host name.
2159 ConvertUTF8PstringToRFC1034HostLabel( tempLabel
.c
, &inMDNS
->hostlabel
);
2160 if( inMDNS
->hostlabel
.c
[ 0 ] == 0 )
2162 // Nice name has no characters that are representable as an RFC1034 name (e.g. Japanese) so use the default.
2164 MakeDomainLabelFromLiteralString( &inMDNS
->hostlabel
, kMDNSDefaultName
);
2167 check( inMDNS
->hostlabel
.c
[ 0 ] != 0 );
2169 mDNS_SetFQDN( inMDNS
);
2171 dlog( kDebugLevelInfo
, DEBUG_NAME
"host name \"%.*s\"\n", inMDNS
->hostlabel
.c
[ 0 ], &inMDNS
->hostlabel
.c
[ 1 ] );
2176 //===========================================================================================================================
2178 //===========================================================================================================================
2180 mDNSlocal mStatus
SetupName( mDNS
* const inMDNS
)
2186 err
= SetupNiceName( inMDNS
);
2189 err
= SetupHostName( inMDNS
);
2196 //===========================================================================================================================
2197 // SetupInterfaceList
2198 //===========================================================================================================================
2200 mDNSlocal mStatus
SetupInterfaceList( mDNS
* const inMDNS
)
2203 mDNSInterfaceData
** next
;
2204 mDNSInterfaceData
* ifd
;
2205 struct ifaddrs
* addrs
;
2207 struct ifaddrs
* loopbackv4
;
2208 struct ifaddrs
* loopbackv6
;
2213 mDNSBool foundUnicastSock4DestAddr
;
2214 mDNSBool foundUnicastSock6DestAddr
;
2216 dlog( kDebugLevelTrace
, DEBUG_NAME
"setting up interface list\n" );
2220 inMDNS
->p
->registeredLoopback4
= mDNSfalse
;
2222 foundv4
= mDNSfalse
;
2223 foundv6
= mDNSfalse
;
2224 foundUnicastSock4DestAddr
= mDNSfalse
;
2225 foundUnicastSock6DestAddr
= mDNSfalse
;
2227 // Tear down any existing interfaces that may be set up.
2229 TearDownInterfaceList( inMDNS
);
2231 // Set up the name of this machine.
2233 err
= SetupName( inMDNS
);
2236 // Set up the interface list change notification.
2238 err
= SetupNotifications( inMDNS
);
2241 // Set up IPv4 interface(s). We have to set up IPv4 first so any IPv6 interface with an IPv4-routable address
2242 // can refer to the IPv4 interface when it registers to allow DNS AAAA records over the IPv4 interface.
2244 err
= getifaddrs( &addrs
);
2245 require_noerr( err
, exit
);
2249 next
= &inMDNS
->p
->interfaceList
;
2251 flagMask
= IFF_UP
| IFF_MULTICAST
;
2252 flagTest
= IFF_UP
| IFF_MULTICAST
;
2254 #if( MDNS_WINDOWS_ENABLE_IPV4 )
2255 for( p
= addrs
; p
; p
= p
->ifa_next
)
2257 if( !p
->ifa_addr
|| ( p
->ifa_addr
->sa_family
!= AF_INET
) || ( ( p
->ifa_flags
& flagMask
) != flagTest
) )
2261 if( p
->ifa_flags
& IFF_LOOPBACK
)
2269 dlog( kDebugLevelVerbose
, DEBUG_NAME
"Interface %40s (0x%08X) %##a\n",
2270 p
->ifa_name
? p
->ifa_name
: "<null>", p
->ifa_extra
.index
, p
->ifa_addr
);
2272 err
= SetupInterface( inMDNS
, p
, &ifd
);
2273 require_noerr( err
, exit
);
2275 // If this guy is point-to-point (ifd->interfaceInfo.McastTxRx == 0 ) we still want to
2276 // register him, but we also want to note that we haven't found a v4 interface
2277 // so that we register loopback so same host operations work
2279 if ( ifd
->interfaceInfo
.McastTxRx
== mDNStrue
)
2284 // If we're on a platform that doesn't have WSARecvMsg(), there's no way
2285 // of determing the destination address of a packet that is sent to us.
2286 // For multicast packets, that's easy to determine. But for the unicast
2287 // sockets, we'll fake it by taking the address of the first interface
2288 // that is successfully setup.
2290 if ( !foundUnicastSock4DestAddr
)
2292 inMDNS
->p
->unicastSock4DestAddr
= ifd
->interfaceInfo
.ip
;
2293 foundUnicastSock4DestAddr
= TRUE
;
2298 ++inMDNS
->p
->interfaceCount
;
2302 // Set up IPv6 interface(s) after IPv4 is set up (see IPv4 notes above for reasoning).
2304 #if( MDNS_WINDOWS_ENABLE_IPV6 )
2305 for( p
= addrs
; p
; p
= p
->ifa_next
)
2307 if( !p
->ifa_addr
|| ( p
->ifa_addr
->sa_family
!= AF_INET6
) || ( ( p
->ifa_flags
& flagMask
) != flagTest
) )
2311 if( p
->ifa_flags
& IFF_LOOPBACK
)
2319 dlog( kDebugLevelVerbose
, DEBUG_NAME
"Interface %40s (0x%08X) %##a\n",
2320 p
->ifa_name
? p
->ifa_name
: "<null>", p
->ifa_extra
.index
, p
->ifa_addr
);
2322 err
= SetupInterface( inMDNS
, p
, &ifd
);
2323 require_noerr( err
, exit
);
2325 // If this guy is point-to-point (ifd->interfaceInfo.McastTxRx == 0 ) we still want to
2326 // register him, but we also want to note that we haven't found a v4 interface
2327 // so that we register loopback so same host operations work
2329 if ( ifd
->interfaceInfo
.McastTxRx
== mDNStrue
)
2334 // If we're on a platform that doesn't have WSARecvMsg(), there's no way
2335 // of determing the destination address of a packet that is sent to us.
2336 // For multicast packets, that's easy to determine. But for the unicast
2337 // sockets, we'll fake it by taking the address of the first interface
2338 // that is successfully setup.
2340 if ( !foundUnicastSock6DestAddr
)
2342 inMDNS
->p
->unicastSock6DestAddr
= ifd
->interfaceInfo
.ip
;
2343 foundUnicastSock6DestAddr
= TRUE
;
2348 ++inMDNS
->p
->interfaceCount
;
2352 // If there are no real interfaces, but there is a loopback interface, use that so same-machine operations work.
2354 #if( !MDNS_WINDOWS_ENABLE_IPV4 && !MDNS_WINDOWS_ENABLE_IPV6 )
2356 flagMask
|= IFF_LOOPBACK
;
2357 flagTest
|= IFF_LOOPBACK
;
2359 for( p
= addrs
; p
; p
= p
->ifa_next
)
2361 if( !p
->ifa_addr
|| ( ( p
->ifa_flags
& flagMask
) != flagTest
) )
2365 if( ( p
->ifa_addr
->sa_family
!= AF_INET
) && ( p
->ifa_addr
->sa_family
!= AF_INET6
) )
2376 if ( !foundv4
&& loopbackv4
)
2378 dlog( kDebugLevelVerbose
, DEBUG_NAME
"Interface %40s (0x%08X) %##a\n",
2379 loopbackv4
->ifa_name
? loopbackv4
->ifa_name
: "<null>", loopbackv4
->ifa_extra
.index
, loopbackv4
->ifa_addr
);
2381 err
= SetupInterface( inMDNS
, loopbackv4
, &ifd
);
2382 require_noerr( err
, exit
);
2384 inMDNS
->p
->registeredLoopback4
= mDNStrue
;
2386 #if( MDNS_WINDOWS_ENABLE_IPV4 )
2388 // If we're on a platform that doesn't have WSARecvMsg(), there's no way
2389 // of determing the destination address of a packet that is sent to us.
2390 // For multicast packets, that's easy to determine. But for the unicast
2391 // sockets, we'll fake it by taking the address of the first interface
2392 // that is successfully setup.
2394 if ( !foundUnicastSock4DestAddr
)
2396 inMDNS
->p
->unicastSock4DestAddr
= ifd
->defaultAddr
;
2397 foundUnicastSock4DestAddr
= TRUE
;
2403 ++inMDNS
->p
->interfaceCount
;
2409 TearDownInterfaceList( inMDNS
);
2413 freeifaddrs( addrs
);
2415 dlog( kDebugLevelTrace
, DEBUG_NAME
"setting up interface list done (err=%d %m)\n", err
, err
);
2419 //===========================================================================================================================
2420 // TearDownInterfaceList
2421 //===========================================================================================================================
2423 mDNSlocal mStatus
TearDownInterfaceList( mDNS
* const inMDNS
)
2426 mDNSInterfaceData
** p
;
2427 mDNSInterfaceData
* ifd
;
2429 dlog( kDebugLevelTrace
, DEBUG_NAME
"tearing down interface list\n" );
2433 // Free any interfaces that were previously marked inactive and are no longer referenced by the mDNS cache.
2434 // Interfaces are marked inactive, but not deleted immediately if they were still referenced by the mDNS cache
2435 // so that remove events that occur after an interface goes away can still report the correct interface.
2437 p
= &inMDNS
->p
->inactiveInterfaceList
;
2441 if( NumCacheRecordsForInterfaceID( inMDNS
, (mDNSInterfaceID
) ifd
) > 0 )
2447 dlog( kDebugLevelInfo
, DEBUG_NAME
"freeing unreferenced, inactive interface %#p %#a\n", ifd
, &ifd
->interfaceInfo
.ip
);
2452 // Tear down interface list change notifications.
2454 err
= TearDownNotifications( inMDNS
);
2457 // Tear down all the interfaces.
2459 while( inMDNS
->p
->interfaceList
)
2461 ifd
= inMDNS
->p
->interfaceList
;
2462 inMDNS
->p
->interfaceList
= ifd
->next
;
2464 TearDownInterface( inMDNS
, ifd
);
2466 inMDNS
->p
->interfaceCount
= 0;
2468 dlog( kDebugLevelTrace
, DEBUG_NAME
"tearing down interface list done\n" );
2469 return( mStatus_NoError
);
2472 //===========================================================================================================================
2474 //===========================================================================================================================
2476 mDNSlocal mStatus
SetupInterface( mDNS
* const inMDNS
, const struct ifaddrs
*inIFA
, mDNSInterfaceData
**outIFD
)
2478 mDNSInterfaceData
* ifd
;
2479 mDNSInterfaceData
* p
;
2484 dlog( kDebugLevelTrace
, DEBUG_NAME
"setting up interface\n" );
2488 check( inIFA
->ifa_addr
);
2491 // Allocate memory for the interface and initialize it.
2493 ifd
= (mDNSInterfaceData
*) calloc( 1, sizeof( *ifd
) );
2494 require_action( ifd
, exit
, err
= mStatus_NoMemoryErr
);
2495 ifd
->sock
= kInvalidSocketRef
;
2496 ifd
->index
= inIFA
->ifa_extra
.index
;
2497 ifd
->scopeID
= inIFA
->ifa_extra
.index
;
2498 check( strlen( inIFA
->ifa_name
) < sizeof( ifd
->name
) );
2499 strncpy( ifd
->name
, inIFA
->ifa_name
, sizeof( ifd
->name
) - 1 );
2500 ifd
->name
[ sizeof( ifd
->name
) - 1 ] = '\0';
2502 strncpy(ifd
->interfaceInfo
.ifname
, inIFA
->ifa_name
, sizeof(ifd
->interfaceInfo
.ifname
));
2503 ifd
->interfaceInfo
.ifname
[sizeof(ifd
->interfaceInfo
.ifname
)-1] = 0;
2505 // We always send and receive using IPv4, but to reduce traffic, we send and receive using IPv6 only on interfaces
2506 // that have no routable IPv4 address. Having a routable IPv4 address assigned is a reasonable indicator of being
2507 // on a large configured network, which means there's a good chance that most or all the other devices on that
2508 // network should also have v4. By doing this we lose the ability to talk to true v6-only devices on that link,
2509 // but we cut the packet rate in half. At this time, reducing the packet rate is more important than v6-only
2510 // devices on a large configured network, so we are willing to make that sacrifice.
2512 ifd
->interfaceInfo
.McastTxRx
= ( ( inIFA
->ifa_flags
& IFF_MULTICAST
) && !( inIFA
->ifa_flags
& IFF_POINTTOPOINT
) ) ? mDNStrue
: mDNSfalse
;
2513 ifd
->interfaceInfo
.InterfaceID
= NULL
;
2515 for( p
= inMDNS
->p
->interfaceList
; p
; p
= p
->next
)
2517 if ( strcmp( p
->name
, ifd
->name
) == 0 )
2519 if (!ifd
->interfaceInfo
.InterfaceID
)
2521 ifd
->interfaceInfo
.InterfaceID
= (mDNSInterfaceID
) p
;
2524 if ( ( inIFA
->ifa_addr
->sa_family
!= AF_INET
) &&
2525 ( p
->interfaceInfo
.ip
.type
== mDNSAddrType_IPv4
) &&
2526 ( p
->interfaceInfo
.ip
.ip
.v4
.b
[ 0 ] != 169 || p
->interfaceInfo
.ip
.ip
.v4
.b
[ 1 ] != 254 ) )
2528 ifd
->interfaceInfo
.McastTxRx
= mDNSfalse
;
2535 if ( !ifd
->interfaceInfo
.InterfaceID
)
2537 ifd
->interfaceInfo
.InterfaceID
= (mDNSInterfaceID
) ifd
;
2540 // Set up a socket for this interface (if needed).
2542 if( ifd
->interfaceInfo
.McastTxRx
)
2544 err
= SetupSocket( inMDNS
, inIFA
->ifa_addr
, MulticastDNSPort
, &sock
);
2545 require_noerr( err
, exit
);
2547 ifd
->defaultAddr
= ( inIFA
->ifa_addr
->sa_family
== AF_INET6
) ? AllDNSLinkGroup_v6
: AllDNSLinkGroup_v4
;
2549 // Get a ptr to the WSARecvMsg function, if supported. Otherwise, we'll fallback to recvfrom.
2551 #if( !TARGET_OS_WINDOWS_CE )
2555 // If we are running inside VPC, then we won't use WSARecvMsg because it will give us bogus information due to
2556 // a bug in VPC itself.
2558 err
= inMDNS
->p
->inVirtualPC
;
2562 err
= WSAIoctl( sock
, SIO_GET_EXTENSION_FUNCTION_POINTER
, &kWSARecvMsgGUID
, sizeof( kWSARecvMsgGUID
),
2563 &ifd
->wsaRecvMsgFunctionPtr
, sizeof( ifd
->wsaRecvMsgFunctionPtr
), &size
, NULL
, NULL
);
2568 ifd
->wsaRecvMsgFunctionPtr
= NULL
;
2573 // Set up the read pending event and associate it so we can block until data is available for this socket.
2575 ifd
->readPendingEvent
= CreateEvent( NULL
, FALSE
, FALSE
, NULL
);
2576 err
= translate_errno( ifd
->readPendingEvent
, (mStatus
) GetLastError(), kUnknownErr
);
2577 require_noerr( err
, exit
);
2579 err
= WSAEventSelect( ifd
->sock
, ifd
->readPendingEvent
, FD_READ
);
2580 require_noerr( err
, exit
);
2584 // Create a placeholder event so WaitForMultipleObjects Handle slot for this interface is valid.
2586 ifd
->readPendingEvent
= CreateEvent( NULL
, FALSE
, FALSE
, NULL
);
2587 err
= translate_errno( ifd
->readPendingEvent
, (mStatus
) GetLastError(), kUnknownErr
);
2588 require_noerr( err
, exit
);
2591 // Register this interface with mDNS.
2593 err
= SockAddrToMDNSAddr( inIFA
->ifa_addr
, &ifd
->interfaceInfo
.ip
, NULL
);
2594 require_noerr( err
, exit
);
2596 err
= SockAddrToMDNSAddr( inIFA
->ifa_netmask
, &ifd
->interfaceInfo
.mask
, NULL
);
2597 require_noerr( err
, exit
);
2599 ifd
->interfaceInfo
.Advertise
= inMDNS
->AdvertiseLocalAddresses
;
2601 err
= mDNS_RegisterInterface( inMDNS
, &ifd
->interfaceInfo
, mDNSfalse
);
2602 require_noerr( err
, exit
);
2603 ifd
->hostRegistered
= mDNStrue
;
2605 dlog( kDebugLevelInfo
, DEBUG_NAME
"Registered interface %##a with mDNS\n", inIFA
->ifa_addr
);
2615 TearDownInterface( inMDNS
, ifd
);
2617 dlog( kDebugLevelTrace
, DEBUG_NAME
"setting up interface done (err=%d %m)\n", err
, err
);
2621 //===========================================================================================================================
2622 // TearDownInterface
2623 //===========================================================================================================================
2625 mDNSlocal mStatus
TearDownInterface( mDNS
* const inMDNS
, mDNSInterfaceData
*inIFD
)
2632 // Deregister this interface with mDNS.
2634 dlog( kDebugLevelInfo
, DEBUG_NAME
"Deregistering interface %#a with mDNS\n", &inIFD
->interfaceInfo
.ip
);
2636 if( inIFD
->hostRegistered
)
2638 inIFD
->hostRegistered
= mDNSfalse
;
2639 mDNS_DeregisterInterface( inMDNS
, &inIFD
->interfaceInfo
, mDNSfalse
);
2642 // Tear down the multicast socket.
2644 if( inIFD
->readPendingEvent
)
2646 CloseHandle( inIFD
->readPendingEvent
);
2647 inIFD
->readPendingEvent
= 0;
2651 inIFD
->sock
= kInvalidSocketRef
;
2652 if( IsValidSocket( sock
) )
2654 close_compat( sock
);
2657 // If the interface is still referenced by items in the mDNS cache then put it on the inactive list. This keeps
2658 // the InterfaceID valid so remove events report the correct interface. If it is no longer referenced, free it.
2660 if( NumCacheRecordsForInterfaceID( inMDNS
, (mDNSInterfaceID
) inIFD
) > 0 )
2662 inIFD
->next
= inMDNS
->p
->inactiveInterfaceList
;
2663 inMDNS
->p
->inactiveInterfaceList
= inIFD
;
2664 dlog( kDebugLevelInfo
, DEBUG_NAME
"deferring free of interface %#p %#a\n", inIFD
, &inIFD
->interfaceInfo
.ip
);
2668 dlog( kDebugLevelInfo
, DEBUG_NAME
"freeing interface %#p %#a immediately\n", inIFD
, &inIFD
->interfaceInfo
.ip
);
2671 return( mStatus_NoError
);
2674 //===========================================================================================================================
2676 //===========================================================================================================================
2678 mDNSlocal mStatus
SetupSocket( mDNS
* const inMDNS
, const struct sockaddr
*inAddr
, mDNSIPPort port
, SocketRef
*outSocketRef
)
2684 DEBUG_UNUSED( inMDNS
);
2686 dlog( kDebugLevelTrace
, DEBUG_NAME
"setting up socket %##a\n", inAddr
);
2688 check( outSocketRef
);
2690 // Set up an IPv4 or IPv6 UDP socket.
2692 sock
= socket( inAddr
->sa_family
, SOCK_DGRAM
, IPPROTO_UDP
);
2693 err
= translate_errno( IsValidSocket( sock
), errno_compat(), kUnknownErr
);
2694 require_noerr( err
, exit
);
2696 // Turn on reuse address option so multiple servers can listen for Multicast DNS packets,
2697 // if we're creating a multicast socket
2699 if ( port
.NotAnInteger
)
2702 err
= setsockopt( sock
, SOL_SOCKET
, SO_REUSEADDR
, (char *) &option
, sizeof( option
) );
2703 check_translated_errno( err
== 0, errno_compat(), kOptionErr
);
2706 if( inAddr
->sa_family
== AF_INET
)
2709 struct sockaddr_in sa4
;
2710 struct ip_mreq mreqv4
;
2712 // Bind the socket to the desired port
2714 ipv4
.NotAnInteger
= ( (const struct sockaddr_in
*) inAddr
)->sin_addr
.s_addr
;
2715 memset( &sa4
, 0, sizeof( sa4
) );
2716 sa4
.sin_family
= AF_INET
;
2717 sa4
.sin_port
= port
.NotAnInteger
;
2718 sa4
.sin_addr
.s_addr
= ipv4
.NotAnInteger
;
2720 err
= bind( sock
, (struct sockaddr
*) &sa4
, sizeof( sa4
) );
2721 check_translated_errno( err
== 0, errno_compat(), kUnknownErr
);
2723 // Turn on option to receive destination addresses and receiving interface.
2726 err
= setsockopt( sock
, IPPROTO_IP
, IP_PKTINFO
, (char *) &option
, sizeof( option
) );
2727 check_translated_errno( err
== 0, errno_compat(), kOptionErr
);
2729 if (port
.NotAnInteger
)
2731 // Join the all-DNS multicast group so we receive Multicast DNS packets
2733 mreqv4
.imr_multiaddr
.s_addr
= AllDNSLinkGroup_v4
.ip
.v4
.NotAnInteger
;
2734 mreqv4
.imr_interface
.s_addr
= ipv4
.NotAnInteger
;
2735 err
= setsockopt( sock
, IPPROTO_IP
, IP_ADD_MEMBERSHIP
, (char *) &mreqv4
, sizeof( mreqv4
) );
2736 check_translated_errno( err
== 0, errno_compat(), kOptionErr
);
2738 // Specify the interface to send multicast packets on this socket.
2740 sa4
.sin_addr
.s_addr
= ipv4
.NotAnInteger
;
2741 err
= setsockopt( sock
, IPPROTO_IP
, IP_MULTICAST_IF
, (char *) &sa4
.sin_addr
, sizeof( sa4
.sin_addr
) );
2742 check_translated_errno( err
== 0, errno_compat(), kOptionErr
);
2744 // Enable multicast loopback so we receive multicast packets we send (for same-machine operations).
2747 err
= setsockopt( sock
, IPPROTO_IP
, IP_MULTICAST_LOOP
, (char *) &option
, sizeof( option
) );
2748 check_translated_errno( err
== 0, errno_compat(), kOptionErr
);
2751 // Send unicast packets with TTL 255 (helps against spoofing).
2754 err
= setsockopt( sock
, IPPROTO_IP
, IP_TTL
, (char *) &option
, sizeof( option
) );
2755 check_translated_errno( err
== 0, errno_compat(), kOptionErr
);
2757 // Send multicast packets with TTL 255 (helps against spoofing).
2760 err
= setsockopt( sock
, IPPROTO_IP
, IP_MULTICAST_TTL
, (char *) &option
, sizeof( option
) );
2761 check_translated_errno( err
== 0, errno_compat(), kOptionErr
);
2764 else if( inAddr
->sa_family
== AF_INET6
)
2766 struct sockaddr_in6
* sa6p
;
2767 struct sockaddr_in6 sa6
;
2768 struct ipv6_mreq mreqv6
;
2770 sa6p
= (struct sockaddr_in6
*) inAddr
;
2772 // Bind the socket to the desired port
2774 memset( &sa6
, 0, sizeof( sa6
) );
2775 sa6
.sin6_family
= AF_INET6
;
2776 sa6
.sin6_port
= port
.NotAnInteger
;
2777 sa6
.sin6_flowinfo
= 0;
2778 sa6
.sin6_addr
= sa6p
->sin6_addr
;
2779 sa6
.sin6_scope_id
= sa6p
->sin6_scope_id
;
2781 err
= bind( sock
, (struct sockaddr
*) &sa6
, sizeof( sa6
) );
2782 check_translated_errno( err
== 0, errno_compat(), kUnknownErr
);
2784 // Turn on option to receive destination addresses and receiving interface.
2787 err
= setsockopt( sock
, IPPROTO_IPV6
, IPV6_PKTINFO
, (char *) &option
, sizeof( option
) );
2788 check_translated_errno( err
== 0, errno_compat(), kOptionErr
);
2790 // We only want to receive IPv6 packets (not IPv4-mapped IPv6 addresses) because we have a separate socket
2791 // for IPv4, but the IPv6 stack in Windows currently doesn't support IPv4-mapped IPv6 addresses and doesn't
2792 // support the IPV6_V6ONLY socket option so the following code would typically not be executed (or needed).
2794 #if( defined( IPV6_V6ONLY ) )
2796 err
= setsockopt( sock
, IPPROTO_IPV6
, IPV6_V6ONLY
, (char *) &option
, sizeof( option
) );
2797 check_translated_errno( err
== 0, errno_compat(), kOptionErr
);
2800 if ( port
.NotAnInteger
)
2802 // Join the all-DNS multicast group so we receive Multicast DNS packets.
2804 mreqv6
.ipv6mr_multiaddr
= *( (struct in6_addr
*) &AllDNSLinkGroup_v6
.ip
.v6
);
2805 mreqv6
.ipv6mr_interface
= sa6p
->sin6_scope_id
;
2806 err
= setsockopt( sock
, IPPROTO_IPV6
, IPV6_JOIN_GROUP
, (char *) &mreqv6
, sizeof( mreqv6
) );
2807 check_translated_errno( err
== 0, errno_compat(), kOptionErr
);
2809 // Specify the interface to send multicast packets on this socket.
2811 option
= (int) sa6p
->sin6_scope_id
;
2812 err
= setsockopt( sock
, IPPROTO_IPV6
, IPV6_MULTICAST_IF
, (char *) &option
, sizeof( option
) );
2813 check_translated_errno( err
== 0, errno_compat(), kOptionErr
);
2815 // Enable multicast loopback so we receive multicast packets we send (for same-machine operations).
2818 err
= setsockopt( sock
, IPPROTO_IPV6
, IPV6_MULTICAST_LOOP
, (char *) &option
, sizeof( option
) );
2819 check_translated_errno( err
== 0, errno_compat(), kOptionErr
);
2822 // Send unicast packets with TTL 255 (helps against spoofing).
2825 err
= setsockopt( sock
, IPPROTO_IPV6
, IPV6_UNICAST_HOPS
, (char *) &option
, sizeof( option
) );
2826 check_translated_errno( err
== 0, errno_compat(), kOptionErr
);
2828 // Send multicast packets with TTL 255 (helps against spoofing).
2831 err
= setsockopt( sock
, IPPROTO_IPV6
, IPV6_MULTICAST_HOPS
, (char *) &option
, sizeof( option
) );
2832 check_translated_errno( err
== 0, errno_compat(), kOptionErr
);
2836 dlog( kDebugLevelError
, DEBUG_NAME
"%s: unsupport socket family (%d)\n", __ROUTINE__
, inAddr
->sa_family
);
2837 err
= kUnsupportedErr
;
2843 *outSocketRef
= sock
;
2844 sock
= kInvalidSocketRef
;
2845 err
= mStatus_NoError
;
2848 if( IsValidSocket( sock
) )
2850 close_compat( sock
);
2855 //===========================================================================================================================
2857 //===========================================================================================================================
2859 mDNSlocal mStatus
SockAddrToMDNSAddr( const struct sockaddr
* const inSA
, mDNSAddr
*outIP
, mDNSIPPort
*outPort
)
2866 if( inSA
->sa_family
== AF_INET
)
2868 struct sockaddr_in
* sa4
;
2870 sa4
= (struct sockaddr_in
*) inSA
;
2871 outIP
->type
= mDNSAddrType_IPv4
;
2872 outIP
->ip
.v4
.NotAnInteger
= sa4
->sin_addr
.s_addr
;
2875 outPort
->NotAnInteger
= sa4
->sin_port
;
2877 err
= mStatus_NoError
;
2879 else if( inSA
->sa_family
== AF_INET6
)
2881 struct sockaddr_in6
* sa6
;
2883 sa6
= (struct sockaddr_in6
*) inSA
;
2884 outIP
->type
= mDNSAddrType_IPv6
;
2885 outIP
->ip
.v6
= *( (mDNSv6Addr
*) &sa6
->sin6_addr
);
2886 if( IN6_IS_ADDR_LINKLOCAL( &sa6
->sin6_addr
) )
2888 outIP
->ip
.v6
.w
[ 1 ] = 0;
2892 outPort
->NotAnInteger
= sa6
->sin6_port
;
2894 err
= mStatus_NoError
;
2898 dlog( kDebugLevelError
, DEBUG_NAME
"%s: invalid sa_family %d", __ROUTINE__
, inSA
->sa_family
);
2899 err
= mStatus_BadParamErr
;
2904 //===========================================================================================================================
2905 // SetupNotifications
2906 //===========================================================================================================================
2908 mDNSlocal mStatus
SetupNotifications( mDNS
* const inMDNS
)
2912 unsigned long param
;
2917 // Register to listen for address list changes.
2919 sock
= socket( AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
2920 err
= translate_errno( IsValidSocket( sock
), errno_compat(), kUnknownErr
);
2921 require_noerr( err
, exit
);
2922 inMDNS
->p
->interfaceListChangedSocket
= sock
;
2924 // Make the socket non-blocking so the WSAIoctl returns immediately with WSAEWOULDBLOCK. It will set the event
2925 // when a change to the interface list is detected.
2928 err
= ioctlsocket( sock
, FIONBIO
, ¶m
);
2929 err
= translate_errno( err
== 0, errno_compat(), kUnknownErr
);
2930 require_noerr( err
, exit
);
2934 err
= WSAIoctl( sock
, SIO_ADDRESS_LIST_CHANGE
, &inBuffer
, 0, &outBuffer
, 0, &outSize
, NULL
, NULL
);
2937 check( errno_compat() == WSAEWOULDBLOCK
);
2940 err
= WSAEventSelect( sock
, inMDNS
->p
->interfaceListChangedEvent
, FD_ADDRESS_LIST_CHANGE
);
2941 err
= translate_errno( err
== 0, errno_compat(), kUnknownErr
);
2942 require_noerr( err
, exit
);
2944 inMDNS
->p
->descChangedEvent
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2945 err
= translate_errno( inMDNS
->p
->descChangedEvent
, (mStatus
) GetLastError(), kUnknownErr
);
2946 require_noerr( err
, exit
);
2948 if (inMDNS
->p
->descKey
!= NULL
)
2950 err
= RegNotifyChangeKeyValue(inMDNS
->p
->descKey
, TRUE
, REG_NOTIFY_CHANGE_LAST_SET
, inMDNS
->p
->descChangedEvent
, TRUE
);
2951 require_noerr( err
, exit
);
2954 // This will catch all changes to tcp/ip networking, including changes to the domain search list
2956 inMDNS
->p
->tcpipChangedEvent
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
2957 err
= translate_errno( inMDNS
->p
->tcpipChangedEvent
, (mStatus
) GetLastError(), kUnknownErr
);
2958 require_noerr( err
, exit
);
2960 err
= RegCreateKey( HKEY_LOCAL_MACHINE
, TEXT("SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters"), &inMDNS
->p
->tcpipKey
);
2961 require_noerr( err
, exit
);
2963 err
= RegNotifyChangeKeyValue(inMDNS
->p
->tcpipKey
, TRUE
, REG_NOTIFY_CHANGE_NAME
|REG_NOTIFY_CHANGE_LAST_SET
, inMDNS
->p
->tcpipChangedEvent
, TRUE
);
2964 require_noerr( err
, exit
);
2966 // This will catch all changes to ddns configuration
2968 inMDNS
->p
->ddnsChangedEvent
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
2969 err
= translate_errno( inMDNS
->p
->ddnsChangedEvent
, (mStatus
) GetLastError(), kUnknownErr
);
2970 require_noerr( err
, exit
);
2972 err
= RegCreateKey( HKEY_LOCAL_MACHINE
, kServiceParametersNode
TEXT("\\DynDNS\\Setup"), &inMDNS
->p
->ddnsKey
);
2973 require_noerr( err
, exit
);
2975 err
= RegNotifyChangeKeyValue(inMDNS
->p
->ddnsKey
, TRUE
, REG_NOTIFY_CHANGE_NAME
|REG_NOTIFY_CHANGE_LAST_SET
, inMDNS
->p
->ddnsChangedEvent
, TRUE
);
2976 require_noerr( err
, exit
);
2981 TearDownNotifications( inMDNS
);
2986 //===========================================================================================================================
2987 // TearDownNotifications
2988 //===========================================================================================================================
2990 mDNSlocal mStatus
TearDownNotifications( mDNS
* const inMDNS
)
2992 if( IsValidSocket( inMDNS
->p
->interfaceListChangedSocket
) )
2994 close_compat( inMDNS
->p
->interfaceListChangedSocket
);
2995 inMDNS
->p
->interfaceListChangedSocket
= kInvalidSocketRef
;
2998 if ( inMDNS
->p
->descChangedEvent
!= NULL
)
3000 CloseHandle( inMDNS
->p
->descChangedEvent
);
3001 inMDNS
->p
->descChangedEvent
= NULL
;
3004 if ( inMDNS
->p
->descKey
!= NULL
)
3006 RegCloseKey( inMDNS
->p
->descKey
);
3007 inMDNS
->p
->descKey
= NULL
;
3010 if ( inMDNS
->p
->tcpipChangedEvent
!= NULL
)
3012 CloseHandle( inMDNS
->p
->tcpipChangedEvent
);
3013 inMDNS
->p
->tcpipChangedEvent
= NULL
;
3016 if ( inMDNS
->p
->ddnsChangedEvent
!= NULL
)
3018 CloseHandle( inMDNS
->p
->ddnsChangedEvent
);
3019 inMDNS
->p
->ddnsChangedEvent
= NULL
;
3022 if ( inMDNS
->p
->ddnsKey
!= NULL
)
3024 RegCloseKey( inMDNS
->p
->ddnsKey
);
3025 inMDNS
->p
->ddnsKey
= NULL
;
3028 return( mStatus_NoError
);
3032 //===========================================================================================================================
3033 // SetupRetryVPCCheck
3034 //===========================================================================================================================
3037 SetupRetryVPCCheck( mDNS
* const inMDNS
)
3039 LARGE_INTEGER liDueTime
;
3043 dlog( kDebugLevelTrace
, DEBUG_NAME
"setting up retry VirtualPC check\n" );
3045 liDueTime
.QuadPart
= kRetryVPCRate
;
3047 // Create a waitable timer.
3049 inMDNS
->p
->vpcCheckEvent
= CreateWaitableTimer( NULL
, TRUE
, TEXT( "VPCCheckTimer" ) );
3050 err
= translate_errno( inMDNS
->p
->vpcCheckEvent
, (mStatus
) GetLastError(), kUnknownErr
);
3051 require_noerr( err
, exit
);
3053 // Set a timer to wait for 10 seconds.
3055 ok
= SetWaitableTimer( inMDNS
->p
->vpcCheckEvent
, &liDueTime
, 0, NULL
, NULL
, 0 );
3056 err
= translate_errno( ok
, (OSStatus
) GetLastError(), kUnknownErr
);
3057 require_noerr( err
, exit
);
3059 inMDNS
->p
->timersCount
++;
3067 //===========================================================================================================================
3068 // TearDownRetryVPCCheck
3069 //===========================================================================================================================
3072 TearDownRetryVPCCheck( mDNS
* const inMDNS
)
3074 dlog( kDebugLevelTrace
, DEBUG_NAME
"tearing down retry VirtualPC check\n" );
3076 if ( inMDNS
->p
->vpcCheckEvent
)
3078 CancelWaitableTimer( inMDNS
->p
->vpcCheckEvent
);
3079 CloseHandle( inMDNS
->p
->vpcCheckEvent
);
3081 inMDNS
->p
->vpcCheckEvent
= NULL
;
3082 inMDNS
->p
->timersCount
--;
3085 return ( mStatus_NoError
);
3093 //===========================================================================================================================
3095 //===========================================================================================================================
3097 mDNSlocal mStatus
SetupThread( mDNS
* const inMDNS
)
3100 HANDLE threadHandle
;
3104 dlog( kDebugLevelTrace
, DEBUG_NAME
"setting up thread\n" );
3106 // To avoid a race condition with the thread ID needed by the unlocking code, we need to make sure the
3107 // thread has fully initialized. To do this, we create the thread then wait for it to signal it is ready.
3109 inMDNS
->p
->initEvent
= CreateEvent( NULL
, FALSE
, FALSE
, NULL
);
3110 err
= translate_errno( inMDNS
->p
->initEvent
, (mStatus
) GetLastError(), kUnknownErr
);
3111 require_noerr( err
, exit
);
3113 inMDNS
->p
->initStatus
= mStatus_Invalid
;
3115 // Create thread with _beginthreadex() instead of CreateThread() to avoid memory leaks when using static run-time
3116 // libraries. See <http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/createthread.asp>.
3118 threadHandle
= (HANDLE
) _beginthreadex_compat( NULL
, 0, ProcessingThread
, inMDNS
, 0, &threadID
);
3119 err
= translate_errno( threadHandle
, (mStatus
) GetLastError(), kUnknownErr
);
3120 require_noerr( err
, exit
);
3122 result
= WaitForSingleObject( inMDNS
->p
->initEvent
, INFINITE
);
3123 err
= translate_errno( result
== WAIT_OBJECT_0
, (mStatus
) GetLastError(), kUnknownErr
);
3124 require_noerr( err
, exit
);
3125 err
= inMDNS
->p
->initStatus
;
3126 require_noerr( err
, exit
);
3129 if( inMDNS
->p
->initEvent
)
3131 CloseHandle( inMDNS
->p
->initEvent
);
3132 inMDNS
->p
->initEvent
= 0;
3134 dlog( kDebugLevelTrace
, DEBUG_NAME
"setting up thread done (err=%d %m)\n", err
, err
);
3138 //===========================================================================================================================
3140 //===========================================================================================================================
3142 mDNSlocal mStatus
TearDownThread( const mDNS
* const inMDNS
)
3144 // Signal the cancel event to cause the thread to exit. Then wait for the quit event to be signal indicating it did
3145 // exit. If the quit event is not signal in 5 seconds, just give up and close anyway sinec the thread is probably hung.
3147 if( inMDNS
->p
->cancelEvent
)
3152 wasSet
= SetEvent( inMDNS
->p
->cancelEvent
);
3153 check_translated_errno( wasSet
, GetLastError(), kUnknownErr
);
3155 if( inMDNS
->p
->quitEvent
)
3157 result
= WaitForSingleObject( inMDNS
->p
->quitEvent
, 5 * 1000 );
3158 check_translated_errno( result
== WAIT_OBJECT_0
, GetLastError(), kUnknownErr
);
3161 return( mStatus_NoError
);
3164 //===========================================================================================================================
3166 //===========================================================================================================================
3168 mDNSlocal
unsigned WINAPI
ProcessingThread( LPVOID inParam
)
3180 m
= (mDNS
*) inParam
;
3181 err
= ProcessingThreadInitialize( m
);
3187 // Set up the list of objects we'll be waiting on.
3191 err
= ProcessingThreadSetupWaitList( m
, &waitList
, &waitListCount
);
3192 require_noerr( err
, exit
);
3194 // Main processing loop.
3196 gWaitListChanged
= FALSE
;
3200 // Give the mDNS core a chance to do its work and determine next event time.
3202 mDNSs32 interval
= mDNS_Execute(m
) - mDNS_TimeNow(m
);
3204 if ( gWaitListChanged
)
3209 if (m
->p
->idleThreadCallback
)
3211 interval
= m
->p
->idleThreadCallback(m
, interval
);
3213 if (interval
< 0) interval
= 0;
3214 else if (interval
> (0x7FFFFFFF / 1000)) interval
= 0x7FFFFFFF / mDNSPlatformOneSecond
;
3215 else interval
= (interval
* 1000) / mDNSPlatformOneSecond
;
3217 // Wait until something occurs (e.g. cancel, incoming packet, or timeout).
3219 result
= WaitForMultipleObjects( (DWORD
) waitListCount
, waitList
, FALSE
, (DWORD
) interval
);
3220 check( result
!= WAIT_FAILED
);
3222 if ( result
!= WAIT_FAILED
)
3224 if( result
== WAIT_TIMEOUT
)
3226 // Next task timeout occurred. Loop back up to give mDNS core a chance to work.
3228 dlog( kDebugLevelChatty
- 1, DEBUG_NAME
"timeout\n" );
3231 else if( result
== kWaitListCancelEvent
)
3233 // Cancel event. Set the done flag and break to exit.
3235 dlog( kDebugLevelVerbose
, DEBUG_NAME
"canceling...\n" );
3239 else if( result
== kWaitListInterfaceListChangedEvent
)
3241 // Interface list changed event. Break out of the inner loop to re-setup the wait list.
3243 ProcessingThreadInterfaceListChanged( m
);
3246 else if( result
== kWaitListWakeupEvent
)
3248 // Wakeup event due to an mDNS API call. Loop back to call mDNS_Execute.
3250 dlog( kDebugLevelChatty
- 1, DEBUG_NAME
"wakeup for mDNS_Execute\n" );
3253 else if ( result
== kWaitListComputerDescriptionEvent
)
3256 // The computer description might have changed
3258 ProcessingThreadComputerDescriptionChanged( m
);
3261 else if ( result
== kWaitListTCPIPEvent
)
3264 // The TCP/IP might have changed
3266 ProcessingThreadTCPIPConfigChanged( m
);
3269 else if ( result
== kWaitListDynDNSEvent
)
3272 // The DynDNS config might have changed
3274 ProcessingThreadDynDNSConfigChanged( m
);
3281 // Socket data available event. Determine which socket and process the packet.
3283 waitItemIndex
= (int)( ( (int) result
) - WAIT_OBJECT_0
);
3284 dlog( kDebugLevelChatty
, DEBUG_NAME
"socket data available on socket index %d\n", waitItemIndex
);
3285 check( ( waitItemIndex
>= 0 ) && ( waitItemIndex
< waitListCount
) );
3286 if( ( waitItemIndex
>= 0 ) && ( waitItemIndex
< waitListCount
) )
3288 HANDLE signaledObject
;
3290 mDNSInterfaceData
* ifd
;
3293 signaledObject
= waitList
[ waitItemIndex
];
3295 if ( m
->p
->vpcCheckEvent
== signaledObject
)
3297 ProcessingThreadRetryVPCCheck( m
);
3302 #if ( MDNS_WINDOWS_ENABLE_IPV4 )
3303 if ( m
->p
->unicastSock4ReadEvent
== signaledObject
)
3305 ProcessingThreadProcessPacket( m
, NULL
, m
->p
->unicastSock4
);
3310 #if ( MDNS_WINDOWS_ENABLE_IPV6 )
3311 if ( m
->p
->unicastSock6ReadEvent
== signaledObject
)
3313 ProcessingThreadProcessPacket( m
, NULL
, m
->p
->unicastSock6
);
3318 for( ifd
= m
->p
->interfaceList
; ifd
; ifd
= ifd
->next
)
3320 if( ifd
->readPendingEvent
== signaledObject
)
3322 ProcessingThreadProcessPacket( m
, ifd
, ifd
->sock
);
3327 for ( tcd
= gTCPConnectionList
; tcd
; tcd
= tcd
->next
)
3329 if ( tcd
->pendingEvent
== signaledObject
)
3331 mDNSBool connect
= FALSE
;
3333 if ( !tcd
->connected
)
3335 tcd
->connected
= mDNStrue
;
3339 tcd
->callback( tcd
, tcd
->context
, connect
, 0 );
3351 // Unexpected wait result.
3353 dlog( kDebugLevelWarning
, DEBUG_NAME
"%s: unexpected wait result (result=0x%08X)\n", __ROUTINE__
, result
);
3360 err
= ProcessingThreadInitialize( m
);
3366 // Release the wait list.
3376 // Signal the quit event to indicate that the thread is finished.
3379 wasSet
= SetEvent( m
->p
->quitEvent
);
3380 check_translated_errno( wasSet
, GetLastError(), kUnknownErr
);
3382 // Call _endthreadex() explicitly instead of just exiting normally to avoid memory leaks when using static run-time
3383 // libraries. See <http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/createthread.asp>.
3385 _endthreadex_compat( 0 );
3389 //===========================================================================================================================
3390 // ProcessingThreadInitialize
3391 //===========================================================================================================================
3393 mDNSlocal mStatus
ProcessingThreadInitialize( mDNS
* const inMDNS
)
3398 inMDNS
->p
->threadID
= GetCurrentThreadId();
3400 err
= IsVPCRunning( &inMDNS
->p
->inVirtualPC
);
3404 TearDownRetryVPCCheck( inMDNS
);
3405 SetupRetryVPCCheck( inMDNS
);
3408 err
= SetupInterfaceList( inMDNS
);
3409 require_noerr( err
, exit
);
3411 err
= uDNS_SetupDNSConfig( inMDNS
);
3412 require_noerr( err
, exit
);
3418 TearDownInterfaceList( inMDNS
);
3419 TearDownRetryVPCCheck( inMDNS
);
3421 inMDNS
->p
->initStatus
= err
;
3423 wasSet
= SetEvent( inMDNS
->p
->initEvent
);
3424 check_translated_errno( wasSet
, GetLastError(), kUnknownErr
);
3428 //===========================================================================================================================
3429 // ProcessingThreadSetupWaitList
3430 //===========================================================================================================================
3432 mDNSlocal mStatus
ProcessingThreadSetupWaitList( mDNS
* const inMDNS
, HANDLE
**outWaitList
, int *outWaitListCount
)
3437 HANDLE
* waitItemPtr
;
3438 mDNSInterfaceData
* ifd
;
3441 dlog( kDebugLevelTrace
, DEBUG_NAME
"thread setting up wait list\n" );
3444 check( outWaitList
);
3445 check( outWaitListCount
);
3447 // Allocate an array to hold all the objects to wait on.
3449 waitListCount
= kWaitListFixedItemCount
+ inMDNS
->p
->timersCount
+ inMDNS
->p
->interfaceCount
+ gTCPConnections
;
3450 waitList
= (HANDLE
*) malloc( waitListCount
* sizeof( *waitList
) );
3451 require_action( waitList
, exit
, err
= mStatus_NoMemoryErr
);
3452 waitItemPtr
= waitList
;
3454 // Add the fixed wait items to the beginning of the list.
3456 *waitItemPtr
++ = inMDNS
->p
->cancelEvent
;
3457 *waitItemPtr
++ = inMDNS
->p
->interfaceListChangedEvent
;
3458 *waitItemPtr
++ = inMDNS
->p
->wakeupEvent
;
3459 *waitItemPtr
++ = inMDNS
->p
->descChangedEvent
;
3460 *waitItemPtr
++ = inMDNS
->p
->tcpipChangedEvent
;
3461 *waitItemPtr
++ = inMDNS
->p
->ddnsChangedEvent
;
3465 if ( inMDNS
->p
->vpcCheckEvent
)
3467 *waitItemPtr
++ = inMDNS
->p
->vpcCheckEvent
;
3470 // Append all the dynamic wait items to the list.
3471 #if ( MDNS_WINDOWS_ENABLE_IPV4 )
3472 *waitItemPtr
++ = inMDNS
->p
->unicastSock4ReadEvent
;
3475 #if ( MDNS_WINDOWS_ENABLE_IPV6 )
3476 *waitItemPtr
++ = inMDNS
->p
->unicastSock6ReadEvent
;
3479 for( ifd
= inMDNS
->p
->interfaceList
; ifd
; ifd
= ifd
->next
)
3481 *waitItemPtr
++ = ifd
->readPendingEvent
;
3484 for ( tcd
= gTCPConnectionList
; tcd
; tcd
= tcd
->next
)
3486 *waitItemPtr
++ = tcd
->pendingEvent
;
3489 check( (int)( waitItemPtr
- waitList
) == waitListCount
);
3491 *outWaitList
= waitList
;
3492 *outWaitListCount
= waitListCount
;
3494 err
= mStatus_NoError
;
3501 dlog( kDebugLevelTrace
, DEBUG_NAME
"thread setting up wait list done (err=%d %m)\n", err
, err
);
3505 //===========================================================================================================================
3506 // ProcessingThreadProcessPacket
3507 //===========================================================================================================================
3509 mDNSlocal
void ProcessingThreadProcessPacket( mDNS
*inMDNS
, mDNSInterfaceData
*inIFD
, SocketRef inSock
)
3512 const mDNSInterfaceID iid
= inIFD
? inIFD
->interfaceInfo
.InterfaceID
: NULL
;
3513 LPFN_WSARECVMSG recvMsgPtr
;
3519 struct sockaddr_storage addr
;
3525 check( IsValidSocket( inSock
) );
3527 // Set up the default in case the packet info options are not supported or reported correctly.
3531 recvMsgPtr
= inIFD
->wsaRecvMsgFunctionPtr
;
3532 dstAddr
= inIFD
->defaultAddr
;
3533 dstPort
= MulticastDNSPort
;
3536 else if ( inSock
== inMDNS
->p
->unicastSock4
)
3538 recvMsgPtr
= inMDNS
->p
->unicastSock4RecvMsgPtr
;
3539 dstAddr
= inMDNS
->p
->unicastSock4DestAddr
;
3540 dstPort
= zeroIPPort
;
3543 else if ( inSock
== inMDNS
->p
->unicastSock6
)
3545 recvMsgPtr
= inMDNS
->p
->unicastSock6RecvMsgPtr
;
3546 dstAddr
= inMDNS
->p
->unicastSock6DestAddr
;
3547 dstPort
= zeroIPPort
;
3552 dlog( kDebugLevelError
, DEBUG_NAME
"packet received on unknown socket\n" );
3556 #if( !TARGET_OS_WINDOWS_CE )
3561 uint8_t controlBuffer
[ 128 ];
3563 LPWSACMSGHDR header
;
3565 // Set up the buffer and read the packet.
3567 msg
.name
= (LPSOCKADDR
) &addr
;
3568 msg
.namelen
= (INT
) sizeof( addr
);
3569 buf
.buf
= (char *) &packet
;
3570 buf
.len
= (u_long
) sizeof( packet
);
3571 msg
.lpBuffers
= &buf
;
3572 msg
.dwBufferCount
= 1;
3573 msg
.Control
.buf
= (char *) controlBuffer
;
3574 msg
.Control
.len
= (u_long
) sizeof( controlBuffer
);
3577 err
= recvMsgPtr( inSock
, &msg
, &size
, NULL
, NULL
);
3578 err
= translate_errno( err
== 0, (OSStatus
) GetLastError(), kUnknownErr
);
3579 require_noerr( err
, exit
);
3582 // Parse the control information. Reject packets received on the wrong interface.
3584 for( header
= WSA_CMSG_FIRSTHDR( &msg
); header
; header
= WSA_CMSG_NXTHDR( &msg
, header
) )
3586 if( ( header
->cmsg_level
== IPPROTO_IP
) && ( header
->cmsg_type
== IP_PKTINFO
) )
3588 IN_PKTINFO
* ipv4PacketInfo
;
3590 ipv4PacketInfo
= (IN_PKTINFO
*) WSA_CMSG_DATA( header
);
3594 require_action( ipv4PacketInfo
->ipi_ifindex
== inIFD
->index
, exit
, err
= kMismatchErr
);
3597 dstAddr
.type
= mDNSAddrType_IPv4
;
3598 dstAddr
.ip
.v4
.NotAnInteger
= ipv4PacketInfo
->ipi_addr
.s_addr
;
3600 else if( ( header
->cmsg_level
== IPPROTO_IPV6
) && ( header
->cmsg_type
== IPV6_PKTINFO
) )
3602 IN6_PKTINFO
* ipv6PacketInfo
;
3604 ipv6PacketInfo
= (IN6_PKTINFO
*) WSA_CMSG_DATA( header
);
3608 require_action( ipv6PacketInfo
->ipi6_ifindex
== ( inIFD
->index
- kIPv6IfIndexBase
), exit
, err
= kMismatchErr
);
3611 dstAddr
.type
= mDNSAddrType_IPv6
;
3612 dstAddr
.ip
.v6
= *( (mDNSv6Addr
*) &ipv6PacketInfo
->ipi6_addr
);
3621 addrSize
= sizeof( addr
);
3622 n
= recvfrom( inSock
, (char *) &packet
, sizeof( packet
), 0, (struct sockaddr
*) &addr
, &addrSize
);
3623 err
= translate_errno( n
> 0, errno_compat(), kUnknownErr
);
3624 require_noerr( err
, exit
);
3626 SockAddrToMDNSAddr( (struct sockaddr
*) &addr
, &srcAddr
, &srcPort
);
3628 // Dispatch the packet to mDNS.
3630 dlog( kDebugLevelChatty
, DEBUG_NAME
"packet received\n" );
3631 dlog( kDebugLevelChatty
, DEBUG_NAME
" size = %d\n", n
);
3632 dlog( kDebugLevelChatty
, DEBUG_NAME
" src = %#a:%u\n", &srcAddr
, ntohs( srcPort
.NotAnInteger
) );
3633 dlog( kDebugLevelChatty
, DEBUG_NAME
" dst = %#a:%u\n", &dstAddr
, ntohs( dstPort
.NotAnInteger
) );
3637 dlog( kDebugLevelChatty
, DEBUG_NAME
" interface = %#a (index=0x%08X)\n", &inIFD
->interfaceInfo
.ip
, (int) inIFD
->index
);
3640 dlog( kDebugLevelChatty
, DEBUG_NAME
"\n" );
3642 end
= ( (mDNSu8
*) &packet
) + n
;
3643 mDNSCoreReceive( inMDNS
, &packet
, end
, &srcAddr
, srcPort
, &dstAddr
, dstPort
, iid
);
3649 //===========================================================================================================================
3650 // ProcessingThreadInterfaceListChanged
3651 //===========================================================================================================================
3653 mDNSlocal
void ProcessingThreadInterfaceListChanged( mDNS
*inMDNS
)
3657 dlog( kDebugLevelInfo
, DEBUG_NAME
"interface list changed\n" );
3660 if (inMDNS
->p
->interfaceListChangedCallback
)
3662 inMDNS
->p
->interfaceListChangedCallback(inMDNS
);
3665 mDNSPlatformLock( inMDNS
);
3667 // Tear down the existing interfaces and set up new ones using the new IP info.
3669 err
= TearDownInterfaceList( inMDNS
);
3672 err
= SetupInterfaceList( inMDNS
);
3675 err
= uDNS_SetupDNSConfig( inMDNS
);
3678 mDNSPlatformUnlock( inMDNS
);
3680 // Inform clients of the change.
3682 if( inMDNS
->MainCallback
)
3684 inMDNS
->MainCallback( inMDNS
, mStatus_ConfigChanged
);
3687 // Force mDNS to update.
3689 mDNSCoreMachineSleep( inMDNS
, mDNSfalse
);
3693 //===========================================================================================================================
3694 // ProcessingThreadComputerDescriptionChanged
3695 //===========================================================================================================================
3696 mDNSlocal
void ProcessingThreadComputerDescriptionChanged( mDNS
*inMDNS
)
3700 dlog( kDebugLevelInfo
, DEBUG_NAME
"computer description has changed\n" );
3703 mDNSPlatformLock( inMDNS
);
3706 SetupNiceName( inMDNS
);
3708 if (inMDNS
->p
->hostDescriptionChangedCallback
)
3710 inMDNS
->p
->hostDescriptionChangedCallback(inMDNS
);
3713 // and reset the event handler
3714 if ((inMDNS
->p
->descKey
!= NULL
) && (inMDNS
->p
->descChangedEvent
))
3716 err
= RegNotifyChangeKeyValue(inMDNS
->p
->descKey
, TRUE
, REG_NOTIFY_CHANGE_LAST_SET
, inMDNS
->p
->descChangedEvent
, TRUE
);
3720 mDNSPlatformUnlock( inMDNS
);
3724 //===========================================================================================================================
3725 // ProcessingThreadTCPIPConfigChanged
3726 //===========================================================================================================================
3727 mDNSlocal
void ProcessingThreadTCPIPConfigChanged( mDNS
* inMDNS
)
3731 dlog( kDebugLevelInfo
, DEBUG_NAME
"TCP/IP config has changed\n" );
3734 mDNSPlatformLock( inMDNS
);
3736 err
= uDNS_SetupDNSConfig( inMDNS
);
3739 // and reset the event handler
3741 if ( ( inMDNS
->p
->tcpipKey
!= NULL
) && ( inMDNS
->p
->tcpipChangedEvent
) )
3743 err
= RegNotifyChangeKeyValue( inMDNS
->p
->tcpipKey
, TRUE
, REG_NOTIFY_CHANGE_NAME
|REG_NOTIFY_CHANGE_LAST_SET
, inMDNS
->p
->tcpipChangedEvent
, TRUE
);
3747 mDNSPlatformUnlock( inMDNS
);
3751 //===========================================================================================================================
3752 // ProcessingThreadDynDNSConfigChanged
3753 //===========================================================================================================================
3754 mDNSlocal
void ProcessingThreadDynDNSConfigChanged( mDNS
*inMDNS
)
3758 dlog( kDebugLevelInfo
, DEBUG_NAME
"DynDNS config has changed\n" );
3761 SetDomainSecrets( inMDNS
);
3763 mDNSPlatformLock( inMDNS
);
3765 err
= uDNS_SetupDNSConfig( inMDNS
);
3768 // and reset the event handler
3770 if ((inMDNS
->p
->ddnsKey
!= NULL
) && (inMDNS
->p
->ddnsChangedEvent
))
3772 err
= RegNotifyChangeKeyValue(inMDNS
->p
->ddnsKey
, TRUE
, REG_NOTIFY_CHANGE_NAME
|REG_NOTIFY_CHANGE_LAST_SET
, inMDNS
->p
->ddnsChangedEvent
, TRUE
);
3776 mDNSPlatformUnlock( inMDNS
);
3780 //===========================================================================================================================
3781 // ProcessingThreadRetryVPCCheck
3782 //===========================================================================================================================
3785 ProcessingThreadRetryVPCCheck( mDNS
* inMDNS
)
3787 mStatus err
= mStatus_NoError
;
3789 dlog( kDebugLevelTrace
, DEBUG_NAME
"in ProcessingThreadRetryVPCCheck\n" );
3791 TearDownRetryVPCCheck( inMDNS
);
3793 if ( inMDNS
->p
->vpcCheckCount
< kRetryVPCMax
)
3795 inMDNS
->p
->vpcCheckCount
++;
3797 err
= IsVPCRunning( &inMDNS
->p
->inVirtualPC
);
3798 require_noerr( err
, exit
);
3800 if ( inMDNS
->p
->inVirtualPC
)
3802 ProcessingThreadInterfaceListChanged( inMDNS
);
3810 SetupRetryVPCCheck( inMDNS
);
3820 #pragma mark == Utilities ==
3823 //===========================================================================================================================
3825 //===========================================================================================================================
3827 mDNSlocal
int getifaddrs( struct ifaddrs
**outAddrs
)
3831 #if( MDNS_WINDOWS_USE_IPV6_IF_ADDRS && !TARGET_OS_WINDOWS_CE )
3833 // Try to the load the GetAdaptersAddresses function from the IP Helpers DLL. This API is only available on Windows
3834 // XP or later. Looking up the symbol at runtime allows the code to still work on older systems without that API.
3836 if( !gIPHelperLibraryInstance
)
3838 gIPHelperLibraryInstance
= LoadLibrary( TEXT( "Iphlpapi" ) );
3839 if( gIPHelperLibraryInstance
)
3841 gGetAdaptersAddressesFunctionPtr
=
3842 (GetAdaptersAddressesFunctionPtr
) GetProcAddress( gIPHelperLibraryInstance
, "GetAdaptersAddresses" );
3843 if( !gGetAdaptersAddressesFunctionPtr
)
3847 ok
= FreeLibrary( gIPHelperLibraryInstance
);
3848 check_translated_errno( ok
, GetLastError(), kUnknownErr
);
3849 gIPHelperLibraryInstance
= NULL
;
3854 // Use the new IPv6-capable routine if supported. Otherwise, fall back to the old and compatible IPv4-only code.
3855 // <rdar://problem/4278934> Fall back to using getifaddrs_ipv4 if getifaddrs_ipv6 fails
3857 if( !gGetAdaptersAddressesFunctionPtr
|| ( ( err
= getifaddrs_ipv6( outAddrs
) ) != mStatus_NoError
) )
3859 err
= getifaddrs_ipv4( outAddrs
);
3860 require_noerr( err
, exit
);
3863 #elif( !TARGET_OS_WINDOWS_CE )
3865 err
= getifaddrs_ipv4( outAddrs
);
3866 require_noerr( err
, exit
);
3870 err
= getifaddrs_ce( outAddrs
);
3871 require_noerr( err
, exit
);
3879 #if( MDNS_WINDOWS_USE_IPV6_IF_ADDRS )
3880 //===========================================================================================================================
3882 //===========================================================================================================================
3884 mDNSlocal
int getifaddrs_ipv6( struct ifaddrs
**outAddrs
)
3889 struct ifaddrs
* head
;
3890 struct ifaddrs
** next
;
3891 IP_ADAPTER_ADDRESSES
* iaaList
;
3893 IP_ADAPTER_ADDRESSES
* iaa
;
3895 struct ifaddrs
* ifa
;
3897 check( gGetAdaptersAddressesFunctionPtr
);
3903 // Get the list of interfaces. The first call gets the size and the second call gets the actual data.
3904 // This loops to handle the case where the interface changes in the window after getting the size, but before the
3905 // second call completes. A limit of 100 retries is enforced to prevent infinite loops if something else is wrong.
3907 flags
= GAA_FLAG_INCLUDE_PREFIX
| GAA_FLAG_SKIP_ANYCAST
| GAA_FLAG_SKIP_MULTICAST
| GAA_FLAG_SKIP_DNS_SERVER
| GAA_FLAG_SKIP_FRIENDLY_NAME
;
3912 err
= gGetAdaptersAddressesFunctionPtr( AF_UNSPEC
, flags
, NULL
, NULL
, &iaaListSize
);
3913 check( err
== ERROR_BUFFER_OVERFLOW
);
3914 check( iaaListSize
>= sizeof( IP_ADAPTER_ADDRESSES
) );
3916 iaaList
= (IP_ADAPTER_ADDRESSES
*) malloc( iaaListSize
);
3917 require_action( iaaList
, exit
, err
= ERROR_NOT_ENOUGH_MEMORY
);
3919 err
= gGetAdaptersAddressesFunctionPtr( AF_UNSPEC
, flags
, NULL
, iaaList
, &iaaListSize
);
3920 if( err
== ERROR_SUCCESS
) break;
3925 require( i
< 100, exit
);
3926 dlog( kDebugLevelWarning
, "%s: retrying GetAdaptersAddresses after %d failure(s) (%d %m)\n", __ROUTINE__
, i
, err
, err
);
3929 for( iaa
= iaaList
; iaa
; iaa
= iaa
->Next
)
3932 IP_ADAPTER_UNICAST_ADDRESS
* addr
;
3934 IP_ADAPTER_PREFIX
* firstPrefix
;
3936 if( iaa
->IfIndex
> 0xFFFFFF )
3938 dlog( kDebugLevelAlert
, DEBUG_NAME
"%s: IPv4 ifindex out-of-range (0x%08X)\n", __ROUTINE__
, iaa
->IfIndex
);
3940 if( iaa
->Ipv6IfIndex
> 0xFF )
3942 dlog( kDebugLevelAlert
, DEBUG_NAME
"%s: IPv6 ifindex out-of-range (0x%08X)\n", __ROUTINE__
, iaa
->Ipv6IfIndex
);
3945 // For IPv4 interfaces, there seems to be a bug in iphlpapi.dll that causes the
3946 // following code to crash when iterating through the prefix list. This seems
3947 // to occur when iaa->Ipv6IfIndex != 0 when IPv6 is not installed on the host.
3948 // This shouldn't happen according to Microsoft docs which states:
3950 // "Ipv6IfIndex contains 0 if IPv6 is not available on the interface."
3952 // So the data structure seems to be corrupted when we return from
3953 // GetAdaptersAddresses(). The bug seems to occur when iaa->Length <
3954 // sizeof(IP_ADAPTER_ADDRESSES), so when that happens, we'll manually
3955 // modify iaa to have the correct values.
3957 if ( iaa
->Length
>= sizeof( IP_ADAPTER_ADDRESSES
) )
3959 ipv6IfIndex
= iaa
->Ipv6IfIndex
;
3960 firstPrefix
= iaa
->FirstPrefix
;
3968 // Skip psuedo and tunnel interfaces.
3970 if( ( ipv6IfIndex
== 1 ) || ( iaa
->IfType
== IF_TYPE_TUNNEL
) )
3975 // Add each address as a separate interface to emulate the way getifaddrs works.
3977 for( addrIndex
= 0, addr
= iaa
->FirstUnicastAddress
; addr
; ++addrIndex
, addr
= addr
->Next
)
3981 IP_ADAPTER_PREFIX
* prefix
;
3984 family
= addr
->Address
.lpSockaddr
->sa_family
;
3985 if( ( family
!= AF_INET
) && ( family
!= AF_INET6
) ) continue;
3987 ifa
= (struct ifaddrs
*) calloc( 1, sizeof( struct ifaddrs
) );
3988 require_action( ifa
, exit
, err
= WSAENOBUFS
);
3991 next
= &ifa
->ifa_next
;
3995 size
= strlen( iaa
->AdapterName
) + 1;
3996 ifa
->ifa_name
= (char *) malloc( size
);
3997 require_action( ifa
->ifa_name
, exit
, err
= WSAENOBUFS
);
3998 memcpy( ifa
->ifa_name
, iaa
->AdapterName
, size
);
4000 // Get interface flags.
4003 if( iaa
->OperStatus
== IfOperStatusUp
) ifa
->ifa_flags
|= IFF_UP
;
4004 if( iaa
->IfType
== IF_TYPE_SOFTWARE_LOOPBACK
) ifa
->ifa_flags
|= IFF_LOOPBACK
;
4005 else if ( IsPointToPoint( addr
) ) ifa
->ifa_flags
|= IFF_POINTTOPOINT
;
4006 if( !( iaa
->Flags
& IP_ADAPTER_NO_MULTICAST
) ) ifa
->ifa_flags
|= IFF_MULTICAST
;
4009 // <rdar://problem/4045657> Interface index being returned is 512
4011 // Windows does not have a uniform scheme for IPv4 and IPv6 interface indexes.
4012 // This code used to shift the IPv4 index up to ensure uniqueness between
4013 // it and IPv6 indexes. Although this worked, it was somewhat confusing to developers, who
4014 // then see interface indexes passed back that don't correspond to anything
4015 // that is seen in Win32 APIs or command line tools like "route". As a relatively
4016 // small percentage of developers are actively using IPv6, it seems to
4017 // make sense to make our use of IPv4 as confusion free as possible.
4018 // So now, IPv6 interface indexes will be shifted up by a
4019 // constant value which will serve to uniquely identify them, and we will
4020 // leave IPv4 interface indexes unmodified.
4024 case AF_INET
: ifa
->ifa_extra
.index
= iaa
->IfIndex
; break;
4025 case AF_INET6
: ifa
->ifa_extra
.index
= ipv6IfIndex
+ kIPv6IfIndexBase
; break;
4035 ifa
->ifa_addr
= (struct sockaddr
*) calloc( 1, (size_t) addr
->Address
.iSockaddrLength
);
4036 require_action( ifa
->ifa_addr
, exit
, err
= WSAENOBUFS
);
4037 memcpy( ifa
->ifa_addr
, addr
->Address
.lpSockaddr
, (size_t) addr
->Address
.iSockaddrLength
);
4043 check( ifa
->ifa_addr
);
4045 // Get subnet mask (IPv4)/link prefix (IPv6). It is specified as a bit length (e.g. 24 for 255.255.255.0).
4048 for( prefixIndex
= 0, prefix
= firstPrefix
; prefix
; ++prefixIndex
, prefix
= prefix
->Next
)
4050 if( prefixIndex
== addrIndex
)
4052 check_string( prefix
->Address
.lpSockaddr
->sa_family
== family
, "addr family != netmask family" );
4053 prefixLength
= prefix
->PrefixLength
;
4061 struct sockaddr_in
* sa4
;
4063 require_action( prefixLength
<= 32, exit
, err
= ERROR_INVALID_DATA
);
4065 sa4
= (struct sockaddr_in
*) calloc( 1, sizeof( *sa4
) );
4066 require_action( sa4
, exit
, err
= WSAENOBUFS
);
4068 sa4
->sin_family
= AF_INET
;
4070 if ( prefixLength
!= 0 )
4072 sa4
->sin_addr
.s_addr
= htonl( 0xFFFFFFFFU
<< ( 32 - prefixLength
) );
4078 dlog( kDebugLevelWarning
, DEBUG_NAME
"%s: IPv4 prefixLength is 0\n", __ROUTINE__
);
4079 err
= AddressToIndexAndMask( ifa
->ifa_addr
, &index
, (struct sockaddr
*) sa4
);
4080 require_noerr( err
, exit
);
4083 dlog( kDebugLevelInfo
, DEBUG_NAME
"%s: IPv4 mask = %s\n", __ROUTINE__
, inet_ntoa( sa4
->sin_addr
) );
4084 ifa
->ifa_netmask
= (struct sockaddr
*) sa4
;
4090 struct sockaddr_in6
* sa6
;
4095 require_action( prefixLength
<= 128, exit
, err
= ERROR_INVALID_DATA
);
4097 sa6
= (struct sockaddr_in6
*) calloc( 1, sizeof( *sa6
) );
4098 require_action( sa6
, exit
, err
= WSAENOBUFS
);
4099 sa6
->sin6_family
= AF_INET6
;
4101 if( prefixLength
== 0 )
4103 dlog( kDebugLevelWarning
, DEBUG_NAME
"%s: IPv6 link prefix 0, defaulting to /128\n", __ROUTINE__
);
4107 for( len
= (int) prefixLength
; len
> 0; len
-= 8 )
4109 if( len
>= 8 ) maskByte
= 0xFF;
4110 else maskByte
= (uint8_t)( ( 0xFFU
<< ( 8 - len
) ) & 0xFFU
);
4111 sa6
->sin6_addr
.s6_addr
[ maskIndex
++ ] = maskByte
;
4113 ifa
->ifa_netmask
= (struct sockaddr
*) sa6
;
4130 err
= ERROR_SUCCESS
;
4135 freeifaddrs( head
);
4141 return( (int) err
);
4144 #endif // MDNS_WINDOWS_USE_IPV6_IF_ADDRS
4146 #if( !TARGET_OS_WINDOWS_CE )
4147 //===========================================================================================================================
4149 //===========================================================================================================================
4151 mDNSlocal
int getifaddrs_ipv4( struct ifaddrs
**outAddrs
)
4157 INTERFACE_INFO
* buffer
;
4158 INTERFACE_INFO
* tempBuffer
;
4159 INTERFACE_INFO
* ifInfo
;
4162 struct ifaddrs
* head
;
4163 struct ifaddrs
** next
;
4164 struct ifaddrs
* ifa
;
4166 sock
= INVALID_SOCKET
;
4171 // Get the interface list. WSAIoctl is called with SIO_GET_INTERFACE_LIST, but since this does not provide a
4172 // way to determine the size of the interface list beforehand, we have to start with an initial size guess and
4173 // call WSAIoctl repeatedly with increasing buffer sizes until it succeeds. Limit this to 100 tries for safety.
4175 sock
= socket( AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
4176 err
= translate_errno( IsValidSocket( sock
), errno_compat(), kUnknownErr
);
4177 require_noerr( err
, exit
);
4180 size
= 16 * sizeof( INTERFACE_INFO
);
4183 tempBuffer
= (INTERFACE_INFO
*) realloc( buffer
, size
);
4184 require_action( tempBuffer
, exit
, err
= WSAENOBUFS
);
4185 buffer
= tempBuffer
;
4187 err
= WSAIoctl( sock
, SIO_GET_INTERFACE_LIST
, NULL
, 0, buffer
, size
, &actualSize
, NULL
, NULL
);
4194 require_action( n
< 100, exit
, err
= WSAEADDRNOTAVAIL
);
4196 size
+= ( 16 * sizeof( INTERFACE_INFO
) );
4198 check( actualSize
<= size
);
4199 check( ( actualSize
% sizeof( INTERFACE_INFO
) ) == 0 );
4200 n
= (int)( actualSize
/ sizeof( INTERFACE_INFO
) );
4202 // Process the raw interface list and build a linked list of IPv4 interfaces.
4204 for( i
= 0; i
< n
; ++i
)
4206 ifInfo
= &buffer
[ i
];
4207 if( ifInfo
->iiAddress
.Address
.sa_family
!= AF_INET
)
4212 ifa
= (struct ifaddrs
*) calloc( 1, sizeof( struct ifaddrs
) );
4213 require_action( ifa
, exit
, err
= WSAENOBUFS
);
4216 next
= &ifa
->ifa_next
;
4220 ifa
->ifa_name
= (char *) malloc( 16 );
4221 require_action( ifa
->ifa_name
, exit
, err
= WSAENOBUFS
);
4222 sprintf( ifa
->ifa_name
, "%d", i
+ 1 );
4224 // Get interface flags.
4226 ifa
->ifa_flags
= (u_int
) ifInfo
->iiFlags
;
4230 if ( ifInfo
->iiAddress
.Address
.sa_family
== AF_INET
)
4232 struct sockaddr_in
* sa4
;
4234 sa4
= &ifInfo
->iiAddress
.AddressIn
;
4235 ifa
->ifa_addr
= (struct sockaddr
*) calloc( 1, sizeof( *sa4
) );
4236 require_action( ifa
->ifa_addr
, exit
, err
= WSAENOBUFS
);
4237 memcpy( ifa
->ifa_addr
, sa4
, sizeof( *sa4
) );
4239 ifa
->ifa_netmask
= (struct sockaddr
*) calloc(1, sizeof( *sa4
) );
4241 // <rdar://problem/4076478> Service won't start on Win2K. The address
4242 // family field was not being initialized.
4244 ifa
->ifa_netmask
->sa_family
= AF_INET
;
4245 require_action( ifa
->ifa_netmask
, exit
, err
= WSAENOBUFS
);
4246 err
= AddressToIndexAndMask( ifa
->ifa_addr
, &ifa
->ifa_extra
.index
, ifa
->ifa_netmask
);
4247 require_noerr( err
, exit
);
4251 // Emulate an interface index.
4253 ifa
->ifa_extra
.index
= (uint32_t)( i
+ 1 );
4269 freeifaddrs( head
);
4275 if( sock
!= INVALID_SOCKET
)
4277 closesocket( sock
);
4281 #endif // !TARGET_OS_WINDOWS_CE )
4283 #if( TARGET_OS_WINDOWS_CE )
4284 //===========================================================================================================================
4286 //===========================================================================================================================
4288 mDNSlocal
int getifaddrs_ce( struct ifaddrs
**outAddrs
)
4294 SOCKET_ADDRESS_LIST
* addressList
;
4295 struct ifaddrs
* head
;
4296 struct ifaddrs
** next
;
4297 struct ifaddrs
* ifa
;
4301 sock
= kInvalidSocketRef
;
4306 // Open a temporary socket because one is needed to use WSAIoctl (we'll close it before exiting this function).
4308 sock
= socket( AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
4309 err
= translate_errno( IsValidSocket( sock
), errno_compat(), kUnknownErr
);
4310 require_noerr( err
, exit
);
4312 // Call WSAIoctl with SIO_ADDRESS_LIST_QUERY and pass a null buffer. This call will fail, but the size needed to
4313 // for the request will be filled in. Once we know the size, allocate a buffer to hold the entire list.
4315 // NOTE: Due to a bug in Windows CE, the size returned by WSAIoctl is not enough so double it as a workaround.
4318 WSAIoctl( sock
, SIO_ADDRESS_LIST_QUERY
, NULL
, 0, NULL
, 0, &size
, NULL
, NULL
);
4319 require_action( size
> 0, exit
, err
= -1 );
4322 buffer
= calloc( 1, size
);
4323 require_action( buffer
, exit
, err
= -1 );
4325 // We now know the size of the list and have a buffer to hold so call WSAIoctl again to get it.
4327 err
= WSAIoctl( sock
, SIO_ADDRESS_LIST_QUERY
, NULL
, 0, buffer
, size
, &size
, NULL
, NULL
);
4328 require_noerr( err
, exit
);
4329 addressList
= (SOCKET_ADDRESS_LIST
*) buffer
;
4331 // Process the raw interface list and build a linked list of interfaces.
4333 // NOTE: Due to a bug in Windows CE, the iAddressCount field is always 0 so use 1 in that case.
4335 n
= addressList
->iAddressCount
;
4340 for( i
= 0; i
< n
; ++i
)
4342 ifa
= (struct ifaddrs
*) calloc( 1, sizeof( struct ifaddrs
) );
4343 require_action( ifa
, exit
, err
= WSAENOBUFS
);
4346 next
= &ifa
->ifa_next
;
4350 ifa
->ifa_name
= (char *) malloc( 16 );
4351 require_action( ifa
->ifa_name
, exit
, err
= WSAENOBUFS
);
4352 sprintf( ifa
->ifa_name
, "%d", i
+ 1 );
4354 // Get flags. Note: SIO_ADDRESS_LIST_QUERY does not report flags so just fake IFF_UP and IFF_MULTICAST.
4356 ifa
->ifa_flags
= IFF_UP
| IFF_MULTICAST
;
4360 switch( addressList
->Address
[ i
].lpSockaddr
->sa_family
)
4364 struct sockaddr_in
* sa4
;
4366 sa4
= (struct sockaddr_in
*) addressList
->Address
[ i
].lpSockaddr
;
4367 ifa
->ifa_addr
= (struct sockaddr
*) calloc( 1, sizeof( *sa4
) );
4368 require_action( ifa
->ifa_addr
, exit
, err
= WSAENOBUFS
);
4369 memcpy( ifa
->ifa_addr
, sa4
, sizeof( *sa4
) );
4390 freeifaddrs( head
);
4396 if( sock
!= INVALID_SOCKET
)
4398 closesocket( sock
);
4402 #endif // TARGET_OS_WINDOWS_CE )
4404 //===========================================================================================================================
4406 //===========================================================================================================================
4408 mDNSlocal
void freeifaddrs( struct ifaddrs
*inIFAs
)
4413 // Free each piece of the structure. Set to null after freeing to handle macro-aliased fields.
4415 for( p
= inIFAs
; p
; p
= q
)
4421 free( p
->ifa_name
);
4426 free( p
->ifa_addr
);
4429 if( p
->ifa_netmask
)
4431 free( p
->ifa_netmask
);
4432 p
->ifa_netmask
= NULL
;
4434 if( p
->ifa_broadaddr
)
4436 free( p
->ifa_broadaddr
);
4437 p
->ifa_broadaddr
= NULL
;
4439 if( p
->ifa_dstaddr
)
4441 free( p
->ifa_dstaddr
);
4442 p
->ifa_dstaddr
= NULL
;
4446 free( p
->ifa_data
);
4454 //===========================================================================================================================
4455 // GetPrimaryInterface
4456 //===========================================================================================================================
4459 GetPrimaryInterface()
4461 PMIB_IPFORWARDTABLE pIpForwardTable
= NULL
;
4463 BOOL bOrder
= FALSE
;
4467 unsigned long int i
;
4469 // Find out how big our buffer needs to be.
4471 err
= GetIpForwardTable(NULL
, &dwSize
, bOrder
);
4472 require_action( err
== ERROR_INSUFFICIENT_BUFFER
, exit
, err
= kUnknownErr
);
4474 // Allocate the memory for the table
4476 pIpForwardTable
= (PMIB_IPFORWARDTABLE
) malloc( dwSize
);
4477 require_action( pIpForwardTable
, exit
, err
= kNoMemoryErr
);
4479 // Now get the table.
4481 err
= GetIpForwardTable(pIpForwardTable
, &dwSize
, bOrder
);
4482 require_noerr( err
, exit
);
4485 // Search for the row in the table we want.
4487 for ( i
= 0; i
< pIpForwardTable
->dwNumEntries
; i
++)
4489 // Look for a default route
4491 if ( pIpForwardTable
->table
[i
].dwForwardDest
== 0 )
4493 if ( index
&& ( pIpForwardTable
->table
[i
].dwForwardMetric1
>= metric
) )
4498 index
= pIpForwardTable
->table
[i
].dwForwardIfIndex
;
4499 metric
= pIpForwardTable
->table
[i
].dwForwardMetric1
;
4505 if ( pIpForwardTable
!= NULL
)
4507 free( pIpForwardTable
);
4514 //===========================================================================================================================
4515 // AddressToIndexAndMask
4516 //===========================================================================================================================
4519 AddressToIndexAndMask( struct sockaddr
* addr
, uint32_t * ifIndex
, struct sockaddr
* mask
)
4521 // Before calling AddIPAddress we use GetIpAddrTable to get
4522 // an adapter to which we can add the IP.
4524 PMIB_IPADDRTABLE pIPAddrTable
= NULL
;
4526 mStatus err
= mStatus_UnknownErr
;
4529 // For now, this is only for IPv4 addresses. That is why we can safely cast
4530 // addr's to sockaddr_in.
4532 require_action( addr
->sa_family
== AF_INET
, exit
, err
= mStatus_UnknownErr
);
4534 // Make an initial call to GetIpAddrTable to get the
4535 // necessary size into the dwSize variable
4537 for ( i
= 0; i
< 100; i
++ )
4539 err
= GetIpAddrTable( pIPAddrTable
, &dwSize
, 0 );
4541 if ( err
!= ERROR_INSUFFICIENT_BUFFER
)
4546 pIPAddrTable
= (MIB_IPADDRTABLE
*) realloc( pIPAddrTable
, dwSize
);
4547 require_action( pIPAddrTable
, exit
, err
= WSAENOBUFS
);
4550 require_noerr( err
, exit
);
4552 for ( i
= 0; i
< pIPAddrTable
->dwNumEntries
; i
++ )
4554 if ( ( ( struct sockaddr_in
* ) addr
)->sin_addr
.s_addr
== pIPAddrTable
->table
[i
].dwAddr
)
4556 *ifIndex
= pIPAddrTable
->table
[i
].dwIndex
;
4557 ( ( struct sockaddr_in
*) mask
)->sin_addr
.s_addr
= pIPAddrTable
->table
[i
].dwMask
;
4558 err
= mStatus_NoError
;
4567 free( pIPAddrTable
);
4574 //===========================================================================================================================
4575 // CanReceiveUnicast
4576 //===========================================================================================================================
4578 mDNSlocal mDNSBool
CanReceiveUnicast( void )
4582 struct sockaddr_in addr
;
4584 // Try to bind to the port without the SO_REUSEADDR option to test if someone else has already bound to it.
4586 sock
= socket( AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
4587 check_translated_errno( IsValidSocket( sock
), errno_compat(), kUnknownErr
);
4588 ok
= IsValidSocket( sock
);
4591 memset( &addr
, 0, sizeof( addr
) );
4592 addr
.sin_family
= AF_INET
;
4593 addr
.sin_port
= MulticastDNSPort
.NotAnInteger
;
4594 addr
.sin_addr
.s_addr
= htonl( INADDR_ANY
);
4596 ok
= ( bind( sock
, (struct sockaddr
*) &addr
, sizeof( addr
) ) == 0 );
4597 close_compat( sock
);
4600 dlog( kDebugLevelInfo
, DEBUG_NAME
"Unicast UDP responses %s\n", ok
? "okay" : "*not allowed*" );
4605 //===========================================================================================================================
4607 //===========================================================================================================================
4609 mDNSlocal mDNSBool
IsPointToPoint( IP_ADAPTER_UNICAST_ADDRESS
* addr
)
4611 struct ifaddrs
* addrs
= NULL
;
4612 struct ifaddrs
* p
= NULL
;
4614 mDNSBool ret
= mDNSfalse
;
4616 // For now, only works for IPv4 interfaces
4618 if ( addr
->Address
.lpSockaddr
->sa_family
== AF_INET
)
4620 // The getifaddrs_ipv4 call will give us correct information regarding IFF_POINTTOPOINT flags.
4622 err
= getifaddrs_ipv4( &addrs
);
4623 require_noerr( err
, exit
);
4625 for ( p
= addrs
; p
; p
= p
->ifa_next
)
4627 if ( ( addr
->Address
.lpSockaddr
->sa_family
== p
->ifa_addr
->sa_family
) &&
4628 ( ( ( struct sockaddr_in
* ) addr
->Address
.lpSockaddr
)->sin_addr
.s_addr
== ( ( struct sockaddr_in
* ) p
->ifa_addr
)->sin_addr
.s_addr
) )
4630 ret
= ( p
->ifa_flags
& IFF_POINTTOPOINT
) ? mDNStrue
: mDNSfalse
;
4640 freeifaddrs( addrs
);
4647 //===========================================================================================================================
4648 // GetWindowsVersionString
4649 //===========================================================================================================================
4651 mDNSlocal OSStatus
GetWindowsVersionString( char *inBuffer
, size_t inBufferSize
)
4653 #if( !defined( VER_PLATFORM_WIN32_CE ) )
4654 #define VER_PLATFORM_WIN32_CE 3
4658 OSVERSIONINFO osInfo
;
4660 const char * versionString
;
4666 versionString
= "unknown Windows version";
4668 osInfo
.dwOSVersionInfoSize
= sizeof( OSVERSIONINFO
);
4669 ok
= GetVersionEx( &osInfo
);
4670 err
= translate_errno( ok
, (OSStatus
) GetLastError(), kUnknownErr
);
4671 require_noerr( err
, exit
);
4673 platformID
= osInfo
.dwPlatformId
;
4674 majorVersion
= osInfo
.dwMajorVersion
;
4675 minorVersion
= osInfo
.dwMinorVersion
;
4676 buildNumber
= osInfo
.dwBuildNumber
& 0xFFFF;
4678 if( ( platformID
== VER_PLATFORM_WIN32_WINDOWS
) && ( majorVersion
== 4 ) )
4680 if( ( minorVersion
< 10 ) && ( buildNumber
== 950 ) )
4682 versionString
= "Windows 95";
4684 else if( ( minorVersion
< 10 ) && ( ( buildNumber
> 950 ) && ( buildNumber
<= 1080 ) ) )
4686 versionString
= "Windows 95 SP1";
4688 else if( ( minorVersion
< 10 ) && ( buildNumber
> 1080 ) )
4690 versionString
= "Windows 95 OSR2";
4692 else if( ( minorVersion
== 10 ) && ( buildNumber
== 1998 ) )
4694 versionString
= "Windows 98";
4696 else if( ( minorVersion
== 10 ) && ( ( buildNumber
> 1998 ) && ( buildNumber
< 2183 ) ) )
4698 versionString
= "Windows 98 SP1";
4700 else if( ( minorVersion
== 10 ) && ( buildNumber
>= 2183 ) )
4702 versionString
= "Windows 98 SE";
4704 else if( minorVersion
== 90 )
4706 versionString
= "Windows ME";
4709 else if( platformID
== VER_PLATFORM_WIN32_NT
)
4711 if( ( majorVersion
== 3 ) && ( minorVersion
== 51 ) )
4713 versionString
= "Windows NT 3.51";
4715 else if( ( majorVersion
== 4 ) && ( minorVersion
== 0 ) )
4717 versionString
= "Windows NT 4";
4719 else if( ( majorVersion
== 5 ) && ( minorVersion
== 0 ) )
4721 versionString
= "Windows 2000";
4723 else if( ( majorVersion
== 5 ) && ( minorVersion
== 1 ) )
4725 versionString
= "Windows XP";
4727 else if( ( majorVersion
== 5 ) && ( minorVersion
== 2 ) )
4729 versionString
= "Windows Server 2003";
4732 else if( platformID
== VER_PLATFORM_WIN32_CE
)
4734 versionString
= "Windows CE";
4738 if( inBuffer
&& ( inBufferSize
> 0 ) )
4741 strncpy( inBuffer
, versionString
, inBufferSize
);
4742 inBuffer
[ inBufferSize
] = '\0';
4748 //===========================================================================================================================
4750 //===========================================================================================================================
4753 RegQueryString( HKEY key
, LPCSTR valueName
, LPSTR
* string
, DWORD
* stringLen
, DWORD
* enabled
)
4759 *stringLen
= MAX_ESCAPED_DOMAIN_NAME
;
4770 *string
= (char*) malloc( *stringLen
);
4771 require_action( *string
, exit
, err
= mStatus_NoMemoryErr
);
4773 err
= RegQueryValueExA( key
, valueName
, 0, &type
, (LPBYTE
) *string
, stringLen
);
4777 while ( ( err
== ERROR_MORE_DATA
) && ( i
< 100 ) );
4779 require_noerr_quiet( err
, exit
);
4783 DWORD dwSize
= sizeof( DWORD
);
4785 err
= RegQueryValueEx( key
, TEXT("Enabled"), NULL
, NULL
, (LPBYTE
) enabled
, &dwSize
);
4797 //===========================================================================================================================
4799 //===========================================================================================================================
4801 mDNSlocal mStatus
StringToAddress( mDNSAddr
* ip
, LPSTR string
)
4803 struct sockaddr_in6 sa6
;
4804 struct sockaddr_in sa4
;
4808 sa6
.sin6_family
= AF_INET6
;
4809 dwSize
= sizeof( sa6
);
4811 err
= WSAStringToAddressA( string
, AF_INET6
, NULL
, (struct sockaddr
*) &sa6
, &dwSize
);
4813 if ( err
== mStatus_NoError
)
4815 err
= SetupAddr( ip
, (struct sockaddr
*) &sa6
);
4816 require_noerr( err
, exit
);
4820 sa4
.sin_family
= AF_INET
;
4821 dwSize
= sizeof( sa4
);
4823 err
= WSAStringToAddressA( string
, AF_INET
, NULL
, (struct sockaddr
*) &sa4
, &dwSize
);
4824 err
= translate_errno( err
== 0, WSAGetLastError(), kUnknownErr
);
4825 require_noerr( err
, exit
);
4827 err
= SetupAddr( ip
, (struct sockaddr
*) &sa4
);
4828 require_noerr( err
, exit
);
4837 //===========================================================================================================================
4839 //===========================================================================================================================
4841 mDNSlocal
struct ifaddrs
*
4842 myGetIfAddrs(int refresh
)
4844 static struct ifaddrs
*ifa
= NULL
;
4861 //===========================================================================================================================
4863 //===========================================================================================================================
4866 TCHARtoUTF8( const TCHAR
*inString
, char *inBuffer
, size_t inBufferSize
)
4868 #if( defined( UNICODE ) || defined( _UNICODE ) )
4872 len
= WideCharToMultiByte( CP_UTF8
, 0, inString
, -1, inBuffer
, (int) inBufferSize
, NULL
, NULL
);
4873 err
= translate_errno( len
> 0, errno_compat(), kUnknownErr
);
4874 require_noerr( err
, exit
);
4879 return( WindowsLatin1toUTF8( inString
, inBuffer
, inBufferSize
) );
4884 //===========================================================================================================================
4885 // WindowsLatin1toUTF8
4886 //===========================================================================================================================
4889 WindowsLatin1toUTF8( const char *inString
, char *inBuffer
, size_t inBufferSize
)
4897 // Windows doesn't support going directly from Latin-1 to UTF-8 so we have to go from Latin-1 to UTF-16 first.
4899 len
= MultiByteToWideChar( CP_ACP
, 0, inString
, -1, NULL
, 0 );
4900 err
= translate_errno( len
> 0, errno_compat(), kUnknownErr
);
4901 require_noerr( err
, exit
);
4903 utf16
= (WCHAR
*) malloc( len
* sizeof( *utf16
) );
4904 require_action( utf16
, exit
, err
= kNoMemoryErr
);
4906 len
= MultiByteToWideChar( CP_ACP
, 0, inString
, -1, utf16
, len
);
4907 err
= translate_errno( len
> 0, errno_compat(), kUnknownErr
);
4908 require_noerr( err
, exit
);
4910 // Now convert the temporary UTF-16 to UTF-8.
4912 len
= WideCharToMultiByte( CP_UTF8
, 0, utf16
, -1, inBuffer
, (int) inBufferSize
, NULL
, NULL
);
4913 err
= translate_errno( len
> 0, errno_compat(), kUnknownErr
);
4914 require_noerr( err
, exit
);
4917 if( utf16
) free( utf16
);
4922 //===========================================================================================================================
4923 // ConvertUTF8ToLsaString
4924 //===========================================================================================================================
4927 MakeLsaStringFromUTF8String( PLSA_UNICODE_STRING output
, const char * input
)
4935 output
->Buffer
= NULL
;
4937 size
= MultiByteToWideChar( CP_UTF8
, 0, input
, -1, NULL
, 0 );
4938 err
= translate_errno( size
> 0, GetLastError(), kUnknownErr
);
4939 require_noerr( err
, exit
);
4941 output
->Length
= (USHORT
)( size
* sizeof( wchar_t ) );
4942 output
->Buffer
= (PWCHAR
) malloc( output
->Length
);
4943 require_action( output
->Buffer
, exit
, err
= mStatus_NoMemoryErr
);
4944 size
= MultiByteToWideChar( CP_UTF8
, 0, input
, -1, output
->Buffer
, size
);
4945 err
= translate_errno( size
> 0, GetLastError(), kUnknownErr
);
4946 require_noerr( err
, exit
);
4948 // We're going to subtrace one wchar_t from the size, because we didn't
4949 // include it when we encoded the string
4951 output
->MaximumLength
= output
->Length
;
4952 output
->Length
-= sizeof( wchar_t );
4956 if ( err
&& output
->Buffer
)
4958 free( output
->Buffer
);
4959 output
->Buffer
= NULL
;
4966 //===========================================================================================================================
4967 // ConvertLsaStringToUTF8
4968 //===========================================================================================================================
4971 MakeUTF8StringFromLsaString( char * output
, size_t len
, PLSA_UNICODE_STRING input
)
4974 OSStatus err
= kNoErr
;
4976 // The Length field of this structure holds the number of bytes,
4977 // but WideCharToMultiByte expects the number of wchar_t's. So
4978 // we divide by sizeof(wchar_t) to get the correct number.
4980 size
= (size_t) WideCharToMultiByte(CP_UTF8
, 0, input
->Buffer
, ( input
->Length
/ sizeof( wchar_t ) ), NULL
, 0, NULL
, NULL
);
4981 err
= translate_errno( size
!= 0, GetLastError(), kUnknownErr
);
4982 require_noerr( err
, exit
);
4984 // Ensure that we have enough space (Add one for trailing '\0')
4986 require_action( ( size
+ 1 ) <= len
, exit
, err
= mStatus_NoMemoryErr
);
4988 // Convert the string
4990 size
= (size_t) WideCharToMultiByte( CP_UTF8
, 0, input
->Buffer
, ( input
->Length
/ sizeof( wchar_t ) ), output
, (int) size
, NULL
, NULL
);
4991 err
= translate_errno( size
!= 0, GetLastError(), kUnknownErr
);
4992 require_noerr( err
, exit
);
4994 // have to add the trailing 0 because WideCharToMultiByte doesn't do it,
4995 // although it does return the correct size
4997 output
[size
] = '\0';
5005 //===========================================================================================================================
5006 // FreeTCPConnectionData
5007 //===========================================================================================================================
5010 FreeTCPSocket( TCPSocket
*sock
)
5014 if ( sock
->pendingEvent
)
5016 CloseHandle( sock
->pendingEvent
);
5019 if ( sock
->fd
!= INVALID_SOCKET
)
5021 closesocket( sock
->fd
);
5027 //===========================================================================================================================
5029 //===========================================================================================================================
5031 mDNSlocal mStatus
SetupAddr(mDNSAddr
*ip
, const struct sockaddr
*const sa
)
5033 if (!sa
) { LogMsg("SetupAddr ERROR: NULL sockaddr"); return(mStatus_Invalid
); }
5035 if (sa
->sa_family
== AF_INET
)
5037 struct sockaddr_in
*ifa_addr
= (struct sockaddr_in
*)sa
;
5038 ip
->type
= mDNSAddrType_IPv4
;
5039 ip
->ip
.v4
.NotAnInteger
= ifa_addr
->sin_addr
.s_addr
;
5040 return(mStatus_NoError
);
5043 if (sa
->sa_family
== AF_INET6
)
5045 struct sockaddr_in6
*ifa_addr
= (struct sockaddr_in6
*)sa
;
5046 ip
->type
= mDNSAddrType_IPv6
;
5047 if (IN6_IS_ADDR_LINKLOCAL(&ifa_addr
->sin6_addr
)) ifa_addr
->sin6_addr
.u
.Word
[1] = 0;
5048 ip
->ip
.v6
= *(mDNSv6Addr
*)&ifa_addr
->sin6_addr
;
5049 return(mStatus_NoError
);
5052 LogMsg("SetupAddr invalid sa_family %d", sa
->sa_family
);
5053 return(mStatus_Invalid
);