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.130 2007/11/16 18:53:56 cheshire
21 TCPSocketFlags needs to be first field of TCPSocket_struct
23 Revision 1.129 2007/10/17 22:52:26 cheshire
24 Get rid of unused mDNS_UpdateLLQs()
26 Revision 1.128 2007/09/12 19:23:17 cheshire
27 Get rid of unnecessary mDNSPlatformTCPIsConnected() routine
29 Revision 1.127 2007/07/20 00:54:22 cheshire
30 <rdar://problem/4641118> Need separate SCPreferences for per-user .Mac settings
32 Revision 1.126 2007/07/11 02:56:20 cheshire
33 <rdar://problem/5303807> Register IPv6-only hostname and don't create port mappings for AutoTunnel services
34 Remove unused mDNSPlatformDefaultRegDomainChanged
36 Revision 1.125 2007/06/20 01:10:13 cheshire
37 <rdar://problem/5280520> Sync iPhone changes into main mDNSResponder code
39 Revision 1.124 2007/04/26 00:35:16 cheshire
40 <rdar://problem/5140339> uDNS: Domain discovery not working over VPN
41 Fixes to make sure results update correctly when connectivity changes (e.g. a DNS server
42 inside the firewall may give answers where a public one gives none, and vice versa.)
44 Revision 1.123 2007/04/18 21:00:40 cheshire
45 Use mDNS_AddSearchDomain_CString() instead of MakeDomainNameFromDNSNameString ... mDNS_AddSearchDomain
47 Revision 1.122 2007/04/17 19:21:29 cheshire
48 <rdar://problem/5140339> Domain discovery not working over VPN
50 Revision 1.121 2007/04/05 20:40:37 cheshire
51 Remove unused mDNSPlatformTCPGetFlags()
53 Revision 1.120 2007/03/28 20:59:27 cheshire
54 <rdar://problem/4743285> Remove inappropriate use of IsPrivateV4Addr()
56 Revision 1.119 2007/03/28 15:56:38 cheshire
57 <rdar://problem/5085774> Add listing of NAT port mapping and GetAddrInfo requests in SIGINFO output
59 Revision 1.118 2007/03/22 18:31:49 cheshire
60 Put dst parameter first in mDNSPlatformStrCopy/mDNSPlatformMemCopy, like conventional Posix strcpy/memcpy
62 Revision 1.117 2007/03/21 00:30:07 cheshire
63 <rdar://problem/4789455> Multiple errors in DNameList-related code
65 Revision 1.116 2007/03/20 17:07:16 cheshire
66 Rename "struct uDNS_TCPSocket_struct" to "TCPSocket", "struct uDNS_UDPSocket_struct" to "UDPSocket"
68 Revision 1.115 2007/02/08 21:12:28 cheshire
69 <rdar://problem/4386497> Stop reading /etc/mDNSResponder.conf on every sleep/wake
71 Revision 1.114 2007/01/05 08:31:01 cheshire
72 Trim excessive "$Log" checkin history from before 2006
73 (checkin history still available via "cvs log ..." of course)
75 Revision 1.113 2007/01/04 23:12:20 cheshire
76 Remove unused mDNSPlatformDefaultBrowseDomainChanged
78 Revision 1.112 2006/12/22 20:59:51 cheshire
79 <rdar://problem/4742742> Read *all* DNS keys from keychain,
80 not just key for the system-wide default registration domain
82 Revision 1.111 2006/12/19 22:43:56 cheshire
85 Revision 1.110 2006/09/27 00:47:40 herscher
86 Fix compile error caused by changes to the tcp callback api.
88 Revision 1.109 2006/08/14 23:25:21 cheshire
89 Re-licensed mDNSResponder daemon source code under Apache License, Version 2.0
91 Revision 1.108 2006/07/06 00:06:21 cheshire
92 <rdar://problem/4472014> Add Private DNS client functionality to mDNSResponder
94 Revision 1.107 2006/03/19 02:00:13 cheshire
95 <rdar://problem/4073825> Improve logic for delaying packets after repeated interface transitions
97 Revision 1.106 2006/02/26 19:31:05 herscher
98 <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.
102 - Get unicode name of machine for nice name instead of just the host name.
103 - Use the IPv6 Internet Connection Firewall API to allow IPv6 mDNS without manually changing the firewall.
104 - Get DNS server address(es) from Windows and provide them to the uDNS layer.
105 - Implement TCP support for truncated packets (only stubs now).
115 #include "CommonServices.h"
116 #include "DebugServices.h"
117 #include "VPCDetect.h"
118 #include "RegNames.h"
121 #include <Iphlpapi.h>
122 #if( !TARGET_OS_WINDOWS_CE )
125 #include <ntsecapi.h>
128 #include "mDNSEmbeddedAPI.h"
130 #include "mDNSWin32.h"
133 #pragma mark == Constants ==
136 //===========================================================================================================================
138 //===========================================================================================================================
140 #define DEBUG_NAME "[mDNSWin32] "
142 #define MDNS_WINDOWS_USE_IPV6_IF_ADDRS 1
143 #define MDNS_WINDOWS_ENABLE_IPV4 1
144 #define MDNS_WINDOWS_ENABLE_IPV6 1
145 #define MDNS_FIX_IPHLPAPI_PREFIX_BUG 1
146 #define MDNS_SET_HINFO_STRINGS 0
148 #define kMDNSDefaultName "My Computer"
150 #define kWinSockMajorMin 2
151 #define kWinSockMinorMin 2
153 #define kWaitListCancelEvent ( WAIT_OBJECT_0 + 0 )
154 #define kWaitListInterfaceListChangedEvent ( WAIT_OBJECT_0 + 1 )
155 #define kWaitListWakeupEvent ( WAIT_OBJECT_0 + 2 )
156 #define kWaitListComputerDescriptionEvent ( WAIT_OBJECT_0 + 3 )
157 #define kWaitListTCPIPEvent ( WAIT_OBJECT_0 + 4 )
158 #define kWaitListDynDNSEvent ( WAIT_OBJECT_0 + 5 )
159 #define kWaitListFixedItemCount 6 + MDNS_WINDOWS_ENABLE_IPV4 + MDNS_WINDOWS_ENABLE_IPV6
161 #define kRegistryMaxKeyLength 255
163 #if( !TARGET_OS_WINDOWS_CE )
164 static GUID kWSARecvMsgGUID
= WSAID_WSARECVMSG
;
167 #define kIPv6IfIndexBase (10000000L)
169 #define kRetryVPCRate (-100000000)
170 #define kRetryVPCMax (10)
174 #pragma mark == Prototypes ==
177 //===========================================================================================================================
179 //===========================================================================================================================
181 mDNSlocal mStatus
SetupSynchronizationObjects( mDNS
* const inMDNS
);
182 mDNSlocal mStatus
TearDownSynchronizationObjects( mDNS
* const inMDNS
);
183 mDNSlocal mStatus
SetupNiceName( mDNS
* const inMDNS
);
184 mDNSlocal mStatus
SetupHostName( mDNS
* const inMDNS
);
185 mDNSlocal mStatus
SetupName( mDNS
* const inMDNS
);
186 mDNSlocal mStatus
SetupInterfaceList( mDNS
* const inMDNS
);
187 mDNSlocal mStatus
TearDownInterfaceList( mDNS
* const inMDNS
);
188 mDNSlocal mStatus
SetupInterface( mDNS
* const inMDNS
, const struct ifaddrs
*inIFA
, mDNSInterfaceData
**outIFD
);
189 mDNSlocal mStatus
TearDownInterface( mDNS
* const inMDNS
, mDNSInterfaceData
*inIFD
);
190 mDNSlocal mStatus
SetupSocket( mDNS
* const inMDNS
, const struct sockaddr
*inAddr
, mDNSIPPort port
, SocketRef
*outSocketRef
);
191 mDNSlocal mStatus
SockAddrToMDNSAddr( const struct sockaddr
* const inSA
, mDNSAddr
*outIP
, mDNSIPPort
*outPort
);
192 mDNSlocal mStatus
SetupNotifications( mDNS
* const inMDNS
);
193 mDNSlocal mStatus
TearDownNotifications( mDNS
* const inMDNS
);
194 mDNSlocal mStatus
SetupRetryVPCCheck( mDNS
* const inMDNS
);
195 mDNSlocal mStatus
TearDownRetryVPCCheck( mDNS
* const inMDNS
);
197 mDNSlocal mStatus
SetupThread( mDNS
* const inMDNS
);
198 mDNSlocal mStatus
TearDownThread( const mDNS
* const inMDNS
);
199 mDNSlocal
unsigned WINAPI
ProcessingThread( LPVOID inParam
);
200 mDNSlocal mStatus
ProcessingThreadInitialize( mDNS
* const inMDNS
);
201 mDNSlocal mStatus
ProcessingThreadSetupWaitList( mDNS
* const inMDNS
, HANDLE
**outWaitList
, int *outWaitListCount
);
202 mDNSlocal
void ProcessingThreadProcessPacket( mDNS
*inMDNS
, mDNSInterfaceData
*inIFD
, SocketRef inSock
);
203 mDNSlocal
void ProcessingThreadInterfaceListChanged( mDNS
*inMDNS
);
204 mDNSlocal
void ProcessingThreadComputerDescriptionChanged( mDNS
* inMDNS
);
205 mDNSlocal
void ProcessingThreadTCPIPConfigChanged( mDNS
* inMDNS
);
206 mDNSlocal
void ProcessingThreadDynDNSConfigChanged( mDNS
* inMDNS
);
207 mDNSlocal
void ProcessingThreadRetryVPCCheck( mDNS
* inMDNS
);
210 // Platform Accessors
216 typedef struct mDNSPlatformInterfaceInfo mDNSPlatformInterfaceInfo
;
217 struct mDNSPlatformInterfaceInfo
223 struct TCPSocket_struct
225 TCPSocketFlags flags
; // MUST BE FIRST FIELD -- mDNSCore expects every TCPSocket_struct to begin with TCPSocketFlags flags
228 TCPConnectionCallback callback
;
235 mDNSexport mStatus
mDNSPlatformInterfaceNameToID( mDNS
* const inMDNS
, const char *inName
, mDNSInterfaceID
*outID
);
236 mDNSexport mStatus
mDNSPlatformInterfaceIDToInfo( mDNS
* const inMDNS
, mDNSInterfaceID inID
, mDNSPlatformInterfaceInfo
*outInfo
);
240 typedef struct PolyString PolyString
;
246 PLSA_UNICODE_STRING m_lsa
;
250 #if( MDNS_WINDOWS_USE_IPV6_IF_ADDRS )
251 mDNSlocal
int getifaddrs_ipv6( struct ifaddrs
**outAddrs
);
254 #if( !TARGET_OS_WINDOWS_CE )
255 mDNSlocal
int getifaddrs_ipv4( struct ifaddrs
**outAddrs
);
258 #if( TARGET_OS_WINDOWS_CE )
259 mDNSlocal
int getifaddrs_ce( struct ifaddrs
**outAddrs
);
262 mDNSlocal DWORD
GetPrimaryInterface();
263 mDNSlocal mStatus
AddressToIndexAndMask( struct sockaddr
* address
, uint32_t * index
, struct sockaddr
* mask
);
264 mDNSlocal mDNSBool
CanReceiveUnicast( void );
265 mDNSlocal mDNSBool
IsPointToPoint( IP_ADAPTER_UNICAST_ADDRESS
* addr
);
267 mDNSlocal mStatus
StringToAddress( mDNSAddr
* ip
, LPSTR string
);
268 mDNSlocal mStatus
RegQueryString( HKEY key
, LPCSTR param
, LPSTR
* string
, DWORD
* stringLen
, DWORD
* enabled
);
269 mDNSlocal
struct ifaddrs
* myGetIfAddrs(int refresh
);
270 mDNSlocal OSStatus
TCHARtoUTF8( const TCHAR
*inString
, char *inBuffer
, size_t inBufferSize
);
271 mDNSlocal OSStatus
WindowsLatin1toUTF8( const char *inString
, char *inBuffer
, size_t inBufferSize
);
272 mDNSlocal OSStatus
MakeLsaStringFromUTF8String( PLSA_UNICODE_STRING output
, const char * input
);
273 mDNSlocal OSStatus
MakeUTF8StringFromLsaString( char * output
, size_t len
, PLSA_UNICODE_STRING input
);
274 mDNSlocal
void FreeTCPSocket( TCPSocket
*sock
);
275 mDNSlocal mStatus
SetupAddr(mDNSAddr
*ip
, const struct sockaddr
*const sa
);
282 #pragma mark == Globals ==
285 //===========================================================================================================================
287 //===========================================================================================================================
289 mDNSlocal mDNS_PlatformSupport gMDNSPlatformSupport
;
290 mDNSs32 mDNSPlatformOneSecond
= 0;
291 mDNSlocal TCPSocket
* gTCPConnectionList
= NULL
;
292 mDNSlocal
int gTCPConnections
= 0;
293 mDNSlocal BOOL gWaitListChanged
= FALSE
;
295 #if( MDNS_WINDOWS_USE_IPV6_IF_ADDRS )
298 ( WINAPI
* GetAdaptersAddressesFunctionPtr
)(
302 PIP_ADAPTER_ADDRESSES inAdapter
,
303 PULONG outBufferSize
);
305 mDNSlocal HMODULE gIPHelperLibraryInstance
= NULL
;
306 mDNSlocal GetAdaptersAddressesFunctionPtr gGetAdaptersAddressesFunctionPtr
= NULL
;
312 #pragma mark == Platform Support ==
315 //===========================================================================================================================
317 //===========================================================================================================================
319 mDNSexport mStatus
mDNSPlatformInit( mDNS
* const inMDNS
)
324 struct sockaddr_in sa4
;
325 struct sockaddr_in6 sa6
;
329 dlog( kDebugLevelTrace
, DEBUG_NAME
"platform init\n" );
331 // Initialize variables. If the PlatformSupport pointer is not null then just assume that a non-Apple client is
332 // calling mDNS_Init and wants to provide its own storage for the platform-specific data so do not overwrite it.
334 memset( &gMDNSPlatformSupport
, 0, sizeof( gMDNSPlatformSupport
) );
335 if( !inMDNS
->p
) inMDNS
->p
= &gMDNSPlatformSupport
;
336 inMDNS
->p
->interfaceListChangedSocket
= kInvalidSocketRef
;
337 mDNSPlatformOneSecond
= 1000; // Use milliseconds as the quantum of time
339 // Startup WinSock 2.2 or later.
341 err
= WSAStartup( MAKEWORD( kWinSockMajorMin
, kWinSockMinorMin
), &wsaData
);
342 require_noerr( err
, exit
);
344 supported
= ( ( LOBYTE( wsaData
.wVersion
) == kWinSockMajorMin
) && ( HIBYTE( wsaData
.wVersion
) == kWinSockMinorMin
) );
345 require_action( supported
, exit
, err
= mStatus_UnsupportedErr
);
347 inMDNS
->CanReceiveUnicastOn5353
= CanReceiveUnicast();
349 // Setup the HINFO HW/SW strings.
351 #if ( MDNS_SET_HINFO_STRINGS )
352 err
= GetWindowsVersionString( (char *) &inMDNS
->HIHardware
.c
[ 1 ], sizeof( inMDNS
->HIHardware
.c
) - 2 );
354 // Note that GetWindowsVersionString guarantees that the resulting string is always null-terminated,
355 // so the following strlen call is safe
356 inMDNS
->HIHardware
.c
[ 0 ] = (mDNSu8
) mDNSPlatformStrLen( &inMDNS
->HIHardware
.c
[ 1 ] );
357 dlog( kDebugLevelInfo
, DEBUG_NAME
"HIHardware: %#s\n", inMDNS
->HIHardware
.c
);
359 mDNS_snprintf( (char *) &inMDNS
->HISoftware
.c
[ 1 ], sizeof( inMDNS
->HISoftware
.c
) - 2,
360 "mDNSResponder (%s %s)", __DATE__
, __TIME__
);
361 inMDNS
->HISoftware
.c
[ 0 ] = (mDNSu8
) mDNSPlatformStrLen( &inMDNS
->HISoftware
.c
[ 1 ] );
362 dlog( kDebugLevelInfo
, DEBUG_NAME
"HISoftware: %#s\n", inMDNS
->HISoftware
.c
);
367 inMDNS
->p
->vpcCheckCount
= 0;
368 inMDNS
->p
->vpcCheckEvent
= NULL
;
369 inMDNS
->p
->timersCount
= 0;
371 // Set up the IPv4 unicast socket
373 inMDNS
->p
->unicastSock4
= INVALID_SOCKET
;
374 inMDNS
->p
->unicastSock4ReadEvent
= NULL
;
375 inMDNS
->p
->unicastSock4RecvMsgPtr
= NULL
;
377 #if ( MDNS_WINDOWS_ENABLE_IPV4 )
379 sa4
.sin_family
= AF_INET
;
380 sa4
.sin_addr
.s_addr
= INADDR_ANY
;
381 err
= SetupSocket( inMDNS
, (const struct sockaddr
*) &sa4
, zeroIPPort
, &inMDNS
->p
->unicastSock4
);
383 sa4len
= sizeof( sa4
);
384 err
= getsockname( inMDNS
->p
->unicastSock4
, (struct sockaddr
*) &sa4
, &sa4len
);
385 require_noerr( err
, exit
);
386 inMDNS
->UnicastPort4
.NotAnInteger
= sa4
.sin_port
;
387 inMDNS
->p
->unicastSock4ReadEvent
= CreateEvent( NULL
, FALSE
, FALSE
, NULL
);
388 err
= translate_errno( inMDNS
->p
->unicastSock4ReadEvent
, (mStatus
) GetLastError(), kUnknownErr
);
389 require_noerr( err
, exit
);
390 err
= WSAEventSelect( inMDNS
->p
->unicastSock4
, inMDNS
->p
->unicastSock4ReadEvent
, FD_READ
);
391 require_noerr( err
, exit
);
392 #if( !TARGET_OS_WINDOWS_CE )
396 err
= WSAIoctl( inMDNS
->p
->unicastSock4
, SIO_GET_EXTENSION_FUNCTION_POINTER
, &kWSARecvMsgGUID
,
397 sizeof( kWSARecvMsgGUID
), &inMDNS
->p
->unicastSock4RecvMsgPtr
, sizeof( inMDNS
->p
->unicastSock4RecvMsgPtr
), &size
, NULL
, NULL
);
401 inMDNS
->p
->unicastSock4RecvMsgPtr
= NULL
;
408 // Set up the IPv6 unicast socket
410 inMDNS
->p
->unicastSock6
= INVALID_SOCKET
;
411 inMDNS
->p
->unicastSock6ReadEvent
= NULL
;
412 inMDNS
->p
->unicastSock6RecvMsgPtr
= NULL
;
414 #if ( MDNS_WINDOWS_ENABLE_IPV6 )
416 sa6
.sin6_family
= AF_INET6
;
417 sa6
.sin6_addr
= in6addr_any
;
418 sa6
.sin6_scope_id
= 0;
420 // This call will fail if the machine hasn't installed IPv6. In that case,
421 // the error will be WSAEAFNOSUPPORT.
423 err
= SetupSocket( inMDNS
, (const struct sockaddr
*) &sa6
, zeroIPPort
, &inMDNS
->p
->unicastSock6
);
424 require_action( !err
|| ( err
== WSAEAFNOSUPPORT
), exit
, err
= (mStatus
) WSAGetLastError() );
425 inMDNS
->p
->unicastSock6ReadEvent
= CreateEvent( NULL
, FALSE
, FALSE
, NULL
);
426 err
= translate_errno( inMDNS
->p
->unicastSock6ReadEvent
, (mStatus
) GetLastError(), kUnknownErr
);
427 require_noerr( err
, exit
);
429 // If we weren't able to create the socket (because IPv6 hasn't been installed) don't do this
431 if ( inMDNS
->p
->unicastSock6
!= INVALID_SOCKET
)
433 sa6len
= sizeof( sa6
);
434 err
= getsockname( inMDNS
->p
->unicastSock6
, (struct sockaddr
*) &sa6
, &sa6len
);
435 require_noerr( err
, exit
);
436 inMDNS
->UnicastPort6
.NotAnInteger
= sa6
.sin6_port
;
438 err
= WSAEventSelect( inMDNS
->p
->unicastSock6
, inMDNS
->p
->unicastSock6ReadEvent
, FD_READ
);
439 require_noerr( err
, exit
);
441 #if( !TARGET_OS_WINDOWS_CE )
445 err
= WSAIoctl( inMDNS
->p
->unicastSock6
, SIO_GET_EXTENSION_FUNCTION_POINTER
, &kWSARecvMsgGUID
,
446 sizeof( kWSARecvMsgGUID
), &inMDNS
->p
->unicastSock6RecvMsgPtr
, sizeof( inMDNS
->p
->unicastSock6RecvMsgPtr
), &size
, NULL
, NULL
);
450 inMDNS
->p
->unicastSock6RecvMsgPtr
= NULL
;
458 // Set up the mDNS thread.
460 err
= SetupSynchronizationObjects( inMDNS
);
461 require_noerr( err
, exit
);
463 err
= SetupThread( inMDNS
);
464 require_noerr( err
, exit
);
468 mDNSCoreInitComplete( inMDNS
, err
);
473 mDNSPlatformClose( inMDNS
);
475 dlog( kDebugLevelTrace
, DEBUG_NAME
"platform init done (err=%d %m)\n", err
, err
);
479 //===========================================================================================================================
481 //===========================================================================================================================
483 mDNSexport
void mDNSPlatformClose( mDNS
* const inMDNS
)
487 dlog( kDebugLevelTrace
, DEBUG_NAME
"platform close\n" );
490 // Tear everything down in reverse order to how it was set up.
492 err
= TearDownThread( inMDNS
);
495 err
= TearDownInterfaceList( inMDNS
);
497 check( !inMDNS
->p
->inactiveInterfaceList
);
499 err
= TearDownRetryVPCCheck( inMDNS
);
502 err
= TearDownSynchronizationObjects( inMDNS
);
505 #if ( MDNS_WINDOWS_ENABLE_IPV4 )
507 if ( inMDNS
->p
->unicastSock4ReadEvent
)
509 CloseHandle( inMDNS
->p
->unicastSock4ReadEvent
);
510 inMDNS
->p
->unicastSock4ReadEvent
= 0;
513 if ( IsValidSocket( inMDNS
->p
->unicastSock4
) )
515 close_compat( inMDNS
->p
->unicastSock4
);
520 #if ( MDNS_WINDOWS_ENABLE_IPV6 )
522 if ( inMDNS
->p
->unicastSock6ReadEvent
)
524 CloseHandle( inMDNS
->p
->unicastSock6ReadEvent
);
525 inMDNS
->p
->unicastSock6ReadEvent
= 0;
528 if ( IsValidSocket( inMDNS
->p
->unicastSock6
) )
530 close_compat( inMDNS
->p
->unicastSock6
);
535 // Free the DLL needed for IPv6 support.
537 #if( MDNS_WINDOWS_USE_IPV6_IF_ADDRS )
538 if( gIPHelperLibraryInstance
)
540 gGetAdaptersAddressesFunctionPtr
= NULL
;
542 FreeLibrary( gIPHelperLibraryInstance
);
543 gIPHelperLibraryInstance
= NULL
;
549 dlog( kDebugLevelTrace
, DEBUG_NAME
"platform close done\n" );
552 //===========================================================================================================================
553 // mDNSPlatformSendUDP
554 //===========================================================================================================================
558 const mDNS
* const inMDNS
,
559 const void * const inMsg
,
560 const mDNSu8
* const inMsgEnd
,
561 mDNSInterfaceID inInterfaceID
,
562 const mDNSAddr
* inDstIP
,
563 mDNSIPPort inDstPort
)
565 SOCKET sendingsocket
= INVALID_SOCKET
;
566 mStatus err
= mStatus_NoError
;
567 mDNSInterfaceData
* ifd
= (mDNSInterfaceData
*) inInterfaceID
;
568 struct sockaddr_storage addr
;
571 DEBUG_USE_ONLY( inMDNS
);
573 n
= (int)( inMsgEnd
- ( (const mDNSu8
* const) inMsg
) );
579 dlog( kDebugLevelChatty
, DEBUG_NAME
"platform send %d bytes to %#a:%u\n", n
, inDstIP
, ntohs( inDstPort
.NotAnInteger
) );
581 if( inDstIP
->type
== mDNSAddrType_IPv4
)
583 struct sockaddr_in
* sa4
;
585 sa4
= (struct sockaddr_in
*) &addr
;
586 sa4
->sin_family
= AF_INET
;
587 sa4
->sin_port
= inDstPort
.NotAnInteger
;
588 sa4
->sin_addr
.s_addr
= inDstIP
->ip
.v4
.NotAnInteger
;
589 sendingsocket
= ifd
? ifd
->sock
: inMDNS
->p
->unicastSock4
;
591 else if( inDstIP
->type
== mDNSAddrType_IPv6
)
593 struct sockaddr_in6
* sa6
;
595 sa6
= (struct sockaddr_in6
*) &addr
;
596 sa6
->sin6_family
= AF_INET6
;
597 sa6
->sin6_port
= inDstPort
.NotAnInteger
;
598 sa6
->sin6_flowinfo
= 0;
599 sa6
->sin6_addr
= *( (struct in6_addr
*) &inDstIP
->ip
.v6
);
600 sa6
->sin6_scope_id
= 0; // Windows requires the scope ID to be zero. IPV6_MULTICAST_IF specifies interface.
601 sendingsocket
= ifd
? ifd
->sock
: inMDNS
->p
->unicastSock6
;
605 dlog( kDebugLevelError
, DEBUG_NAME
"%s: dst is not an IPv4 or IPv6 address (type=%d)\n", __ROUTINE__
, inDstIP
->type
);
606 err
= mStatus_BadParamErr
;
610 if (IsValidSocket(sendingsocket
))
612 n
= sendto( sendingsocket
, (char *) inMsg
, n
, 0, (struct sockaddr
*) &addr
, sizeof( addr
) );
613 err
= translate_errno( n
> 0, errno_compat(), kWriteErr
);
617 // Don't report EHOSTDOWN (i.e. ARP failure), ENETDOWN, or no route to host for unicast destinations
619 if ( !mDNSAddressIsAllDNSLinkGroup( inDstIP
) && ( WSAGetLastError() == WSAEHOSTDOWN
|| WSAGetLastError() == WSAENETDOWN
|| WSAGetLastError() == WSAEHOSTUNREACH
|| WSAGetLastError() == WSAENETUNREACH
) )
621 err
= mStatus_TransientErr
;
625 require_noerr( err
, exit
);
634 //===========================================================================================================================
636 //===========================================================================================================================
638 mDNSexport
void mDNSPlatformLock( const mDNS
* const inMDNS
)
642 if ( inMDNS
->p
->lockInitialized
)
644 EnterCriticalSection( &inMDNS
->p
->lock
);
648 //===========================================================================================================================
649 // mDNSPlatformUnlock
650 //===========================================================================================================================
652 mDNSexport
void mDNSPlatformUnlock( const mDNS
* const inMDNS
)
657 if ( inMDNS
->p
->lockInitialized
)
659 check( inMDNS
->p
->threadID
);
661 // Signal a wakeup event if when called from a task other than the mDNS task since if we are called from mDNS task,
662 // we'll loop back and call mDNS_Execute anyway. Signaling is needed to re-evaluate the wakeup via mDNS_Execute.
664 if( GetCurrentThreadId() != inMDNS
->p
->threadID
)
668 wasSet
= SetEvent( inMDNS
->p
->wakeupEvent
);
669 check_translated_errno( wasSet
, GetLastError(), kUnknownErr
);
671 LeaveCriticalSection( &inMDNS
->p
->lock
);
675 //===========================================================================================================================
676 // mDNSPlatformStrCopy
677 //===========================================================================================================================
679 mDNSexport
void mDNSPlatformStrCopy( void *inDst
, const void *inSrc
)
684 strcpy( (char *) inDst
, (const char*) inSrc
);
687 //===========================================================================================================================
688 // mDNSPlatformStrLen
689 //===========================================================================================================================
691 mDNSexport mDNSu32
mDNSPlatformStrLen( const void *inSrc
)
695 return( (mDNSu32
) strlen( (const char *) inSrc
) );
698 //===========================================================================================================================
699 // mDNSPlatformMemCopy
700 //===========================================================================================================================
702 mDNSexport
void mDNSPlatformMemCopy( void *inDst
, const void *inSrc
, mDNSu32 inSize
)
707 memcpy( inDst
, inSrc
, inSize
);
710 //===========================================================================================================================
711 // mDNSPlatformMemSame
712 //===========================================================================================================================
714 mDNSexport mDNSBool
mDNSPlatformMemSame( const void *inDst
, const void *inSrc
, mDNSu32 inSize
)
719 return( (mDNSBool
)( memcmp( inSrc
, inDst
, inSize
) == 0 ) );
722 //===========================================================================================================================
723 // mDNSPlatformMemZero
724 //===========================================================================================================================
726 mDNSexport
void mDNSPlatformMemZero( void *inDst
, mDNSu32 inSize
)
730 memset( inDst
, 0, inSize
);
733 //===========================================================================================================================
734 // mDNSPlatformMemAllocate
735 //===========================================================================================================================
737 mDNSexport
void * mDNSPlatformMemAllocate( mDNSu32 inSize
)
743 mem
= malloc( inSize
);
749 //===========================================================================================================================
750 // mDNSPlatformMemFree
751 //===========================================================================================================================
753 mDNSexport
void mDNSPlatformMemFree( void *inMem
)
760 //===========================================================================================================================
761 // mDNSPlatformRandomSeed
762 //===========================================================================================================================
764 mDNSexport mDNSu32
mDNSPlatformRandomSeed(void)
766 return( GetTickCount() );
769 //===========================================================================================================================
770 // mDNSPlatformTimeInit
771 //===========================================================================================================================
773 mDNSexport mStatus
mDNSPlatformTimeInit( void )
775 // No special setup is required on Windows -- we just use GetTickCount().
776 return( mStatus_NoError
);
779 //===========================================================================================================================
780 // mDNSPlatformRawTime
781 //===========================================================================================================================
783 mDNSexport mDNSs32
mDNSPlatformRawTime( void )
785 return( (mDNSs32
) GetTickCount() );
788 //===========================================================================================================================
790 //===========================================================================================================================
792 mDNSexport mDNSs32
mDNSPlatformUTC( void )
794 return ( mDNSs32
) time( NULL
);
797 //===========================================================================================================================
798 // mDNSPlatformInterfaceNameToID
799 //===========================================================================================================================
801 mDNSexport mStatus
mDNSPlatformInterfaceNameToID( mDNS
* const inMDNS
, const char *inName
, mDNSInterfaceID
*outID
)
804 mDNSInterfaceData
* ifd
;
810 // Search for an interface with the specified name,
812 for( ifd
= inMDNS
->p
->interfaceList
; ifd
; ifd
= ifd
->next
)
814 if( strcmp( ifd
->name
, inName
) == 0 )
819 require_action_quiet( ifd
, exit
, err
= mStatus_NoSuchNameErr
);
825 *outID
= (mDNSInterfaceID
) ifd
;
827 err
= mStatus_NoError
;
833 //===========================================================================================================================
834 // mDNSPlatformInterfaceIDToInfo
835 //===========================================================================================================================
837 mDNSexport mStatus
mDNSPlatformInterfaceIDToInfo( mDNS
* const inMDNS
, mDNSInterfaceID inID
, mDNSPlatformInterfaceInfo
*outInfo
)
840 mDNSInterfaceData
* ifd
;
846 // Search for an interface with the specified ID,
848 for( ifd
= inMDNS
->p
->interfaceList
; ifd
; ifd
= ifd
->next
)
850 if( ifd
== (mDNSInterfaceData
*) inID
)
855 require_action_quiet( ifd
, exit
, err
= mStatus_NoSuchNameErr
);
859 outInfo
->name
= ifd
->name
;
860 outInfo
->ip
= ifd
->interfaceInfo
.ip
;
861 err
= mStatus_NoError
;
867 //===========================================================================================================================
868 // mDNSPlatformInterfaceIDfromInterfaceIndex
869 //===========================================================================================================================
871 mDNSexport mDNSInterfaceID
mDNSPlatformInterfaceIDfromInterfaceIndex( mDNS
* const inMDNS
, mDNSu32 inIndex
)
876 if( inIndex
== kDNSServiceInterfaceIndexLocalOnly
)
878 id
= mDNSInterface_LocalOnly
;
880 else if( inIndex
!= 0 )
882 mDNSInterfaceData
* ifd
;
884 for( ifd
= inMDNS
->p
->interfaceList
; ifd
; ifd
= ifd
->next
)
886 if( ( ifd
->scopeID
== inIndex
) && ifd
->interfaceInfo
.InterfaceActive
)
888 id
= ifd
->interfaceInfo
.InterfaceID
;
897 //===========================================================================================================================
898 // mDNSPlatformInterfaceIndexfromInterfaceID
899 //===========================================================================================================================
901 mDNSexport mDNSu32
mDNSPlatformInterfaceIndexfromInterfaceID( mDNS
* const inMDNS
, mDNSInterfaceID inID
)
906 if( inID
== mDNSInterface_LocalOnly
)
908 index
= (mDNSu32
) kDNSServiceInterfaceIndexLocalOnly
;
912 mDNSInterfaceData
* ifd
;
914 // Search active interfaces.
915 for( ifd
= inMDNS
->p
->interfaceList
; ifd
; ifd
= ifd
->next
)
917 if( (mDNSInterfaceID
) ifd
== inID
)
919 index
= ifd
->scopeID
;
924 // Search inactive interfaces too so remove events for inactive interfaces report the old interface index.
928 for( ifd
= inMDNS
->p
->inactiveInterfaceList
; ifd
; ifd
= ifd
->next
)
930 if( (mDNSInterfaceID
) ifd
== inID
)
932 index
= ifd
->scopeID
;
942 //===========================================================================================================================
943 // mDNSPlatformTCPSocket
944 //===========================================================================================================================
947 mDNSPlatformTCPSocket
950 TCPSocketFlags flags
,
954 TCPSocket
* sock
= NULL
;
955 u_long on
= 1; // "on" for setsockopt
956 struct sockaddr_in saddr
;
958 mStatus err
= mStatus_NoError
;
962 require_action( flags
== 0, exit
, err
= mStatus_UnsupportedErr
);
964 // Setup connection data object
966 sock
= (TCPSocket
*) malloc( sizeof( TCPSocket
) );
967 require_action( sock
, exit
, err
= mStatus_NoMemoryErr
);
968 memset( sock
, 0, sizeof( TCPSocket
) );
970 sock
->fd
= INVALID_SOCKET
;
973 bzero(&saddr
, sizeof(saddr
));
974 saddr
.sin_family
= AF_INET
;
975 saddr
.sin_addr
.s_addr
= htonl( INADDR_ANY
);
976 saddr
.sin_port
= port
->NotAnInteger
;
980 sock
->fd
= socket(AF_INET
, SOCK_STREAM
, 0);
981 err
= translate_errno( sock
->fd
!= INVALID_SOCKET
, WSAGetLastError(), mStatus_UnknownErr
);
982 require_noerr( err
, exit
);
984 // Set it to be non-blocking
986 err
= ioctlsocket( sock
->fd
, FIONBIO
, &on
);
987 err
= translate_errno( err
== 0, WSAGetLastError(), mStatus_UnknownErr
);
988 require_noerr( err
, exit
);
992 memset( &saddr
, 0, sizeof( saddr
) );
993 len
= sizeof( saddr
);
995 err
= getsockname( sock
->fd
, ( struct sockaddr
* ) &saddr
, &len
);
996 err
= translate_errno( err
== 0, WSAGetLastError(), mStatus_UnknownErr
);
997 require_noerr( err
, exit
);
999 port
->NotAnInteger
= saddr
.sin_port
;
1005 FreeTCPSocket( sock
);
1012 //===========================================================================================================================
1013 // mDNSPlatformTCPConnect
1014 //===========================================================================================================================
1017 mDNSPlatformTCPConnect
1020 const mDNSAddr
* inDstIP
,
1021 mDNSOpaque16 inDstPort
,
1022 mDNSInterfaceID inInterfaceID
,
1023 TCPConnectionCallback inCallback
,
1027 struct sockaddr_in saddr
;
1028 mStatus err
= mStatus_NoError
;
1030 DEBUG_UNUSED( inInterfaceID
);
1032 if ( inDstIP
->type
!= mDNSAddrType_IPv4
)
1034 LogMsg("ERROR: mDNSPlatformTCPConnect - attempt to connect to an IPv6 address: operation not supported");
1035 return mStatus_UnknownErr
;
1038 // Setup connection data object
1040 sock
->callback
= inCallback
;
1041 sock
->context
= inContext
;
1043 bzero(&saddr
, sizeof(saddr
));
1044 saddr
.sin_family
= AF_INET
;
1045 saddr
.sin_port
= inDstPort
.NotAnInteger
;
1046 memcpy(&saddr
.sin_addr
, &inDstIP
->ip
.v4
.NotAnInteger
, sizeof(saddr
.sin_addr
));
1048 // Try and do connect
1050 err
= connect( sock
->fd
, ( struct sockaddr
* ) &saddr
, sizeof( saddr
) );
1051 require_action( !err
|| ( WSAGetLastError() == WSAEWOULDBLOCK
), exit
, err
= mStatus_ConnFailed
);
1052 sock
->connected
= !err
? TRUE
: FALSE
;
1053 sock
->pendingEvent
= CreateEvent( NULL
, FALSE
, FALSE
, NULL
);
1054 err
= translate_errno( sock
->pendingEvent
, GetLastError(), mStatus_UnknownErr
);
1055 require_noerr( err
, exit
);
1056 err
= WSAEventSelect( sock
->fd
, sock
->pendingEvent
, FD_CONNECT
|FD_READ
|FD_CLOSE
);
1057 require_noerr( err
, exit
);
1061 sock
->next
= gTCPConnectionList
;
1062 gTCPConnectionList
= sock
;
1064 gWaitListChanged
= TRUE
;
1070 err
= sock
->connected
? mStatus_ConnEstablished
: mStatus_ConnPending
;
1076 //===========================================================================================================================
1077 // mDNSPlatformTCPAccept
1078 //===========================================================================================================================
1081 mDNSexport TCPSocket
*mDNSPlatformTCPAccept( TCPSocketFlags flags
, int fd
)
1083 TCPSocket
* sock
= NULL
;
1084 mStatus err
= mStatus_NoError
;
1086 require_action( !flags
, exit
, err
= mStatus_UnsupportedErr
);
1088 sock
= malloc( sizeof( TCPSocket
) );
1089 require_action( sock
, exit
, err
= mStatus_NoMemoryErr
);
1091 memset( sock
, 0, sizeof( *sock
) );
1094 sock
->flags
= flags
;
1108 //===========================================================================================================================
1109 // mDNSPlatformTCPCloseConnection
1110 //===========================================================================================================================
1112 mDNSexport
void mDNSPlatformTCPCloseConnection( TCPSocket
*sock
)
1114 TCPSocket
* inserted
= gTCPConnectionList
;
1115 TCPSocket
* last
= NULL
;
1119 if ( inserted
== sock
)
1123 gTCPConnectionList
= inserted
->next
;
1127 last
->next
= inserted
->next
;
1131 gWaitListChanged
= TRUE
;
1137 inserted
= inserted
->next
;
1140 FreeTCPSocket( sock
);
1143 //===========================================================================================================================
1144 // mDNSPlatformReadTCP
1145 //===========================================================================================================================
1147 mDNSexport
long mDNSPlatformReadTCP( TCPSocket
*sock
, void *inBuffer
, unsigned long inBufferSize
, mDNSBool
* closed
)
1151 nread
= recv( sock
->fd
, inBuffer
, inBufferSize
, 0);
1155 if ( WSAGetLastError() == WSAEWOULDBLOCK
)
1172 //===========================================================================================================================
1173 // mDNSPlatformWriteTCP
1174 //===========================================================================================================================
1176 mDNSexport
long mDNSPlatformWriteTCP( TCPSocket
*sock
, const char *inMsg
, unsigned long inMsgSize
)
1181 nsent
= send( sock
->fd
, inMsg
, inMsgSize
, 0 );
1183 err
= translate_errno( ( nsent
>= 0 ) || ( WSAGetLastError() == WSAEWOULDBLOCK
), WSAGetLastError(), mStatus_UnknownErr
);
1184 require_noerr( err
, exit
);
1196 //===========================================================================================================================
1197 // mDNSPlatformTCPGetFD
1198 //===========================================================================================================================
1200 mDNSexport
int mDNSPlatformTCPGetFD(TCPSocket
*sock
)
1202 return ( int ) sock
->fd
;
1205 //===========================================================================================================================
1206 // mDNSPlatformUDPSocket
1207 //===========================================================================================================================
1209 mDNSexport UDPSocket
*mDNSPlatformUDPSocket
1216 DEBUG_UNUSED( port
);
1221 //===========================================================================================================================
1222 // mDNSPlatformUDPClose
1223 //===========================================================================================================================
1225 mDNSexport
void mDNSPlatformUDPClose( UDPSocket
*sock
)
1227 DEBUG_UNUSED( sock
);
1231 //===========================================================================================================================
1232 // mDNSPlatformTLSSetupCerts
1233 //===========================================================================================================================
1236 mDNSPlatformTLSSetupCerts(void)
1238 return mStatus_UnsupportedErr
;
1241 //===========================================================================================================================
1242 // mDNSPlatformTLSTearDownCerts
1243 //===========================================================================================================================
1246 mDNSPlatformTLSTearDownCerts(void)
1250 //===========================================================================================================================
1251 // mDNSPlatformSetDNSConfig
1252 //===========================================================================================================================
1254 mDNSlocal
void SetDNSServers( mDNS
*const m
);
1255 mDNSlocal
void SetSearchDomainList( void );
1258 mDNSexport
void mDNSPlatformSetDNSConfig(mDNS
*const m
, mDNSBool setservers
, mDNSBool setsearch
, domainname
*const fqdn
, DNameListElem
**RegDomains
, DNameListElem
**browseDomains
)
1261 char subKeyName
[kRegistryMaxKeyLength
+ 1];
1273 if (setservers
) SetDNSServers(m
);
1274 if (setsearch
) SetSearchDomainList();
1280 *browseDomains
= NULL
;
1282 err
= RegCreateKey( HKEY_LOCAL_MACHINE
, kServiceParametersNode
TEXT("\\DynDNS\\Setup\\") kServiceDynDNSHostNames
, &key
);
1283 require_noerr( err
, exit
);
1285 err
= RegQueryString( key
, "", &name
, &dwSize
, &enabled
);
1286 if ( !err
&& ( name
[0] != '\0' ) && enabled
)
1288 if ( !MakeDomainNameFromDNSNameString( fqdn
, name
) || !fqdn
->c
[0] )
1290 dlog( kDebugLevelError
, "bad DDNS host name in registry: %s", name
[0] ? name
: "(unknown)");
1306 err
= RegCreateKey( HKEY_LOCAL_MACHINE
, kServiceParametersNode
TEXT("\\DynDNS\\Setup\\") kServiceDynDNSBrowseDomains
, &key
);
1307 require_noerr( err
, exit
);
1309 // Get information about this node
1311 err
= RegQueryInfoKey( key
, NULL
, NULL
, NULL
, &cSubKeys
, &cbMaxSubKey
, &cchMaxClass
, NULL
, NULL
, NULL
, NULL
, NULL
);
1312 require_noerr( err
, exit
);
1314 for ( i
= 0; i
< cSubKeys
; i
++)
1318 dwSize
= kRegistryMaxKeyLength
;
1320 err
= RegEnumKeyExA( key
, i
, subKeyName
, &dwSize
, NULL
, NULL
, NULL
, NULL
);
1324 err
= RegOpenKeyExA( key
, subKeyName
, 0, KEY_READ
, &subKey
);
1325 require_noerr( err
, exit
);
1327 dwSize
= sizeof( DWORD
);
1328 err
= RegQueryValueExA( subKey
, "Enabled", NULL
, NULL
, (LPBYTE
) &enabled
, &dwSize
);
1330 if ( !err
&& ( subKeyName
[0] != '\0' ) && enabled
)
1332 if ( !MakeDomainNameFromDNSNameString( &dname
, subKeyName
) || !dname
.c
[0] )
1334 dlog( kDebugLevelError
, "bad DDNS browse domain in registry: %s", subKeyName
[0] ? subKeyName
: "(unknown)");
1338 DNameListElem
* browseDomain
= (DNameListElem
*) malloc( sizeof( DNameListElem
) );
1339 require_action( browseDomain
, exit
, err
= mStatus_NoMemoryErr
);
1341 AssignDomainName(&browseDomain
->name
, &dname
);
1342 browseDomain
->next
= *browseDomains
;
1344 *browseDomains
= browseDomain
;
1348 RegCloseKey( subKey
);
1359 err
= RegCreateKey( HKEY_LOCAL_MACHINE
, kServiceParametersNode
TEXT("\\DynDNS\\Setup\\") kServiceDynDNSRegistrationDomains
, &key
);
1360 require_noerr( err
, exit
);
1362 err
= RegQueryString( key
, "", &name
, &dwSize
, &enabled
);
1363 if ( !err
&& ( name
[0] != '\0' ) && enabled
)
1365 *RegDomains
= (DNameListElem
*) malloc( sizeof( DNameListElem
) );
1366 if (!*RegDomains
) dlog( kDebugLevelError
, "No memory");
1369 (*RegDomains
)->next
= mDNSNULL
;
1370 if ( !MakeDomainNameFromDNSNameString( &(*RegDomains
)->name
, name
) || (*RegDomains
)->name
.c
[0] )
1372 dlog( kDebugLevelError
, "bad DDNS registration domain in registry: %s", name
[0] ? name
: "(unknown)");
1381 RegCloseKey( subKey
);
1396 //===========================================================================================================================
1397 // mDNSPlatformDynDNSHostNameStatusChanged
1398 //===========================================================================================================================
1401 mDNSPlatformDynDNSHostNameStatusChanged(domainname
*const dname
, mStatus status
)
1403 char uname
[MAX_ESCAPED_DOMAIN_NAME
];
1409 ConvertDomainNameToCString(dname
, uname
);
1415 *p
= (char) tolower(*p
);
1416 if (!(*(p
+1)) && *p
== '.') *p
= 0; // if last character, strip trailing dot
1420 check( strlen( p
) <= MAX_ESCAPED_DOMAIN_NAME
);
1421 name
= kServiceParametersNode
TEXT("\\DynDNS\\State\\HostNames");
1422 err
= RegCreateKey( HKEY_LOCAL_MACHINE
, name
, &key
);
1423 require_noerr( err
, exit
);
1425 status
= ( status
) ? 0 : 1;
1426 err
= RegSetValueEx( key
, kServiceDynDNSStatus
, 0, REG_DWORD
, (const LPBYTE
) &status
, sizeof(DWORD
) );
1427 require_noerr( err
, exit
);
1440 //===========================================================================================================================
1442 //===========================================================================================================================
1444 // This routine needs to be called whenever the system secrets database changes.
1445 // Right now I call it from ProcessingThreadDynDNSConfigChanged, which may or may not be sufficient.
1446 // Also, it needs to call mDNS_SetSecretForDomain() for *every* configured DNS domain/secret pair
1447 // in the database, not just inDomain (the inDomain parameter should be deleted).
1450 SetDomainSecrets( mDNS
* const m
, const domainname
* inDomain
)
1457 LSA_OBJECT_ATTRIBUTES attrs
;
1458 LSA_HANDLE handle
= NULL
;
1462 // Initialize PolyStrings
1464 domain
.m_lsa
= NULL
;
1466 secret
.m_lsa
= NULL
;
1468 // canonicalize name by converting to lower case (keychain and some name servers are case sensitive)
1470 ConvertDomainNameToCString( inDomain
, domain
.m_utf8
);
1471 dlen
= strlen( domain
.m_utf8
);
1472 for ( i
= 0; i
< dlen
; i
++ )
1474 domain
.m_utf8
[i
] = (char) tolower( domain
.m_utf8
[i
] ); // canonicalize -> lower case
1477 MakeDomainNameFromDNSNameString( &domain
.m_dname
, domain
.m_utf8
);
1479 // attrs are reserved, so initialize to zeroes.
1481 ZeroMemory( &attrs
, sizeof( attrs
) );
1483 // Get a handle to the Policy object on the local system
1485 res
= LsaOpenPolicy( NULL
, &attrs
, POLICY_GET_PRIVATE_INFORMATION
, &handle
);
1486 err
= translate_errno( res
== 0, LsaNtStatusToWinError( res
), kUnknownErr
);
1487 require_noerr( err
, exit
);
1489 // Get the encrypted data
1491 domain
.m_lsa
= ( PLSA_UNICODE_STRING
) malloc( sizeof( LSA_UNICODE_STRING
) );
1492 require_action( domain
.m_lsa
!= NULL
, exit
, err
= mStatus_NoMemoryErr
);
1493 err
= MakeLsaStringFromUTF8String( domain
.m_lsa
, domain
.m_utf8
);
1494 require_noerr( err
, exit
);
1498 res
= LsaRetrievePrivateData( handle
, domain
.m_lsa
, &key
.m_lsa
);
1499 err
= translate_errno( res
== 0, LsaNtStatusToWinError( res
), kUnknownErr
);
1500 require_noerr_quiet( err
, exit
);
1502 // <rdar://problem/4192119> Lsa secrets use a flat naming space. Therefore, we will prepend "$" to the keyname to
1503 // make sure it doesn't conflict with a zone name.
1505 // Convert the key to a domainname. Strip off the "$" prefix.
1507 err
= MakeUTF8StringFromLsaString( key
.m_utf8
, sizeof( key
.m_utf8
), key
.m_lsa
);
1508 require_noerr( err
, exit
);
1509 require_action( key
.m_utf8
[0] == '$', exit
, err
= kUnknownErr
);
1510 MakeDomainNameFromDNSNameString( &key
.m_dname
, key
.m_utf8
+ 1 );
1512 // Retrieve the secret
1514 res
= LsaRetrievePrivateData( handle
, key
.m_lsa
, &secret
.m_lsa
);
1515 err
= translate_errno( res
== 0, LsaNtStatusToWinError( res
), kUnknownErr
);
1516 require_noerr_quiet( err
, exit
);
1518 // Convert the secret to UTF8 string
1520 err
= MakeUTF8StringFromLsaString( secret
.m_utf8
, sizeof( secret
.m_utf8
), secret
.m_lsa
);
1521 require_noerr( err
, exit
);
1523 // And finally, tell the core about this secret
1525 debugf("Setting shared secret for zone %s with key %##s", domain
.m_utf8
, key
.m_dname
.c
);
1526 mDNS_SetSecretForDomain( m
, &domain
.m_dname
, &key
.m_dname
, secret
.m_utf8
, mDNSfalse
);
1530 if ( domain
.m_lsa
!= NULL
)
1532 if ( domain
.m_lsa
->Buffer
!= NULL
)
1534 free( domain
.m_lsa
->Buffer
);
1537 free( domain
.m_lsa
);
1540 if ( key
.m_lsa
!= NULL
)
1542 LsaFreeMemory( key
.m_lsa
);
1545 if ( secret
.m_lsa
!= NULL
)
1547 LsaFreeMemory( secret
.m_lsa
);
1558 //===========================================================================================================================
1559 // SetSearchDomainList
1560 //===========================================================================================================================
1562 mDNSlocal
void SetDomainFromDHCP( void );
1563 mDNSlocal
void SetReverseMapSearchDomainList( void );
1566 SetSearchDomainList( void )
1568 char * searchList
= NULL
;
1569 DWORD searchListLen
;
1570 DNameListElem
* head
= NULL
;
1571 DNameListElem
* current
= NULL
;
1576 err
= RegCreateKey( HKEY_LOCAL_MACHINE
, TEXT("SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters"), &key
);
1577 require_noerr( err
, exit
);
1579 err
= RegQueryString( key
, "SearchList", &searchList
, &searchListLen
, NULL
);
1580 require_noerr( err
, exit
);
1582 // Windows separates the search domains with ','
1584 tok
= strtok( searchList
, "," );
1587 if ( ( strcmp( tok
, "" ) != 0 ) && ( strcmp( tok
, "." ) != 0 ) )
1588 mDNS_AddSearchDomain_CString(tok
);
1589 tok
= strtok( NULL
, "," );
1604 SetDomainFromDHCP();
1605 SetReverseMapSearchDomainList();
1609 //===========================================================================================================================
1610 // SetReverseMapSearchDomainList
1611 //===========================================================================================================================
1614 SetReverseMapSearchDomainList( void )
1616 struct ifaddrs
* ifa
;
1618 ifa
= myGetIfAddrs( 1 );
1623 if (ifa
->ifa_addr
->sa_family
== AF_INET
&& !SetupAddr(&addr
, ifa
->ifa_addr
) && !(ifa
->ifa_flags
& IFF_LOOPBACK
) && ifa
->ifa_netmask
)
1628 if (!SetupAddr(&netmask
, ifa
->ifa_netmask
))
1630 sprintf(buffer
, "%d.%d.%d.%d.in-addr.arpa.", addr
.ip
.v4
.b
[3] & netmask
.ip
.v4
.b
[3],
1631 addr
.ip
.v4
.b
[2] & netmask
.ip
.v4
.b
[2],
1632 addr
.ip
.v4
.b
[1] & netmask
.ip
.v4
.b
[1],
1633 addr
.ip
.v4
.b
[0] & netmask
.ip
.v4
.b
[0]);
1634 mDNS_AddSearchDomain_CString(buffer
);
1638 ifa
= ifa
->ifa_next
;
1645 //===========================================================================================================================
1647 //===========================================================================================================================
1650 SetDNSServers( mDNS
*const m
)
1652 PIP_PER_ADAPTER_INFO pAdapterInfo
= NULL
;
1653 FIXED_INFO
* fixedInfo
= NULL
;
1655 IP_ADDR_STRING
* dnsServerList
;
1656 IP_ADDR_STRING
* ipAddr
;
1659 mStatus err
= kUnknownErr
;
1661 // Get the primary interface.
1663 index
= GetPrimaryInterface();
1665 // This should have the interface index of the primary index. Fall back in cases where
1666 // it can't be determined.
1672 for ( i
= 0; i
< 100; i
++ )
1674 err
= GetPerAdapterInfo( index
, pAdapterInfo
, &bufLen
);
1676 if ( err
!= ERROR_BUFFER_OVERFLOW
)
1681 pAdapterInfo
= (PIP_PER_ADAPTER_INFO
) realloc( pAdapterInfo
, bufLen
);
1682 require_action( pAdapterInfo
, exit
, err
= mStatus_NoMemoryErr
);
1685 require_noerr( err
, exit
);
1687 dnsServerList
= &pAdapterInfo
->DnsServerList
;
1691 bufLen
= sizeof( FIXED_INFO
);
1693 for ( i
= 0; i
< 100; i
++ )
1697 GlobalFree( fixedInfo
);
1701 fixedInfo
= (FIXED_INFO
*) GlobalAlloc( GPTR
, bufLen
);
1702 require_action( fixedInfo
, exit
, err
= mStatus_NoMemoryErr
);
1704 err
= GetNetworkParams( fixedInfo
, &bufLen
);
1706 if ( err
!= ERROR_BUFFER_OVERFLOW
)
1712 require_noerr( err
, exit
);
1714 dnsServerList
= &fixedInfo
->DnsServerList
;
1717 for ( ipAddr
= dnsServerList
; ipAddr
; ipAddr
= ipAddr
->Next
)
1720 err
= StringToAddress( &addr
, ipAddr
->IpAddress
.String
);
1721 if ( !err
) mDNS_AddDNSServer(m
, mDNSNULL
, mDNSInterface_Any
, addr
, UnicastDNSPort
);
1728 free( pAdapterInfo
);
1733 GlobalFree( fixedInfo
);
1738 //===========================================================================================================================
1739 // SetDomainFromDHCP
1740 //===========================================================================================================================
1743 SetDomainFromDHCP( void )
1745 DNameListElem
* head
= NULL
;
1747 IP_ADAPTER_INFO
* pAdapterInfo
;
1748 IP_ADAPTER_INFO
* pAdapter
;
1752 LPSTR domain
= NULL
;
1755 mStatus err
= mStatus_NoError
;
1757 pAdapterInfo
= NULL
;
1759 for ( i
= 0; i
< 100; i
++ )
1761 err
= GetAdaptersInfo( pAdapterInfo
, &bufLen
);
1763 if ( err
!= ERROR_BUFFER_OVERFLOW
)
1768 pAdapterInfo
= (IP_ADAPTER_INFO
*) realloc( pAdapterInfo
, bufLen
);
1769 require_action( pAdapterInfo
, exit
, err
= kNoMemoryErr
);
1772 require_noerr( err
, exit
);
1774 index
= GetPrimaryInterface();
1776 for ( pAdapter
= pAdapterInfo
; pAdapter
; pAdapter
= pAdapter
->Next
)
1778 if ( pAdapter
->IpAddressList
.IpAddress
.String
&&
1779 pAdapter
->IpAddressList
.IpAddress
.String
[0] &&
1780 pAdapter
->GatewayList
.IpAddress
.String
&&
1781 pAdapter
->GatewayList
.IpAddress
.String
[0] &&
1782 ( !index
|| ( pAdapter
->Index
== index
) ) )
1784 // Found one that will work
1788 _snprintf( keyName
, 1024, "%s%s", "SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Interfaces\\", pAdapter
->AdapterName
);
1790 err
= RegCreateKeyA( HKEY_LOCAL_MACHINE
, keyName
, &key
);
1791 require_noerr( err
, exit
);
1793 err
= RegQueryString( key
, "Domain", &domain
, &dwSize
, NULL
);
1796 if ( !domain
|| !domain
[0] )
1804 err
= RegQueryString( key
, "DhcpDomain", &domain
, &dwSize
, NULL
);
1808 if ( domain
&& domain
[0] ) mDNS_AddSearchDomain_CString(domain
);
1818 free( pAdapterInfo
);
1833 //===========================================================================================================================
1834 // mDNSPlatformGetPrimaryInterface
1835 //===========================================================================================================================
1838 mDNSPlatformGetPrimaryInterface( mDNS
* const m
, mDNSAddr
* v4
, mDNSAddr
* v6
, mDNSAddr
* router
)
1840 IP_ADAPTER_INFO
* pAdapterInfo
;
1841 IP_ADAPTER_INFO
* pAdapter
;
1846 mStatus err
= mStatus_NoError
;
1852 pAdapterInfo
= NULL
;
1856 for ( i
= 0; i
< 100; i
++ )
1858 err
= GetAdaptersInfo( pAdapterInfo
, &bufLen
);
1860 if ( err
!= ERROR_BUFFER_OVERFLOW
)
1865 pAdapterInfo
= (IP_ADAPTER_INFO
*) realloc( pAdapterInfo
, bufLen
);
1866 require_action( pAdapterInfo
, exit
, err
= kNoMemoryErr
);
1869 require_noerr( err
, exit
);
1871 index
= GetPrimaryInterface();
1873 for ( pAdapter
= pAdapterInfo
; pAdapter
; pAdapter
= pAdapter
->Next
)
1875 if ( pAdapter
->IpAddressList
.IpAddress
.String
&&
1876 pAdapter
->IpAddressList
.IpAddress
.String
[0] &&
1877 pAdapter
->GatewayList
.IpAddress
.String
&&
1878 pAdapter
->GatewayList
.IpAddress
.String
[0] &&
1879 ( StringToAddress( v4
, pAdapter
->IpAddressList
.IpAddress
.String
) == mStatus_NoError
) &&
1880 ( StringToAddress( router
, pAdapter
->GatewayList
.IpAddress
.String
) == mStatus_NoError
) &&
1881 ( !index
|| ( pAdapter
->Index
== index
) ) )
1883 // Found one that will work
1894 free( pAdapterInfo
);
1905 //===========================================================================================================================
1907 //===========================================================================================================================
1909 #if( MDNS_DEBUGMSGS )
1910 mDNSexport
void debugf_( const char *inFormat
, ... )
1916 va_start( args
, inFormat
);
1917 length
= mDNS_vsnprintf( buffer
, sizeof( buffer
), inFormat
, args
);
1920 dlog( kDebugLevelInfo
, "%s\n", buffer
);
1924 //===========================================================================================================================
1926 //===========================================================================================================================
1928 #if( MDNS_DEBUGMSGS > 1 )
1929 mDNSexport
void verbosedebugf_( const char *inFormat
, ... )
1935 va_start( args
, inFormat
);
1936 length
= mDNS_vsnprintf( buffer
, sizeof( buffer
), inFormat
, args
);
1939 dlog( kDebugLevelVerbose
, "%s\n", buffer
);
1943 //===========================================================================================================================
1945 //===========================================================================================================================
1948 mDNSexport void LogMsg( const char *inFormat, ... )
1954 va_start( args, inFormat );
1955 length = mDNS_vsnprintf( buffer, sizeof( buffer ), inFormat, args );
1958 dlog( kDebugLevelWarning, "%s\n", buffer );
1964 #pragma mark == Platform Internals ==
1967 //===========================================================================================================================
1968 // SetupSynchronizationObjects
1969 //===========================================================================================================================
1971 mDNSlocal mStatus
SetupSynchronizationObjects( mDNS
* const inMDNS
)
1975 InitializeCriticalSection( &inMDNS
->p
->lock
);
1976 inMDNS
->p
->lockInitialized
= mDNStrue
;
1978 inMDNS
->p
->cancelEvent
= CreateEvent( NULL
, FALSE
, FALSE
, NULL
);
1979 err
= translate_errno( inMDNS
->p
->cancelEvent
, (mStatus
) GetLastError(), kUnknownErr
);
1980 require_noerr( err
, exit
);
1982 inMDNS
->p
->quitEvent
= CreateEvent( NULL
, FALSE
, FALSE
, NULL
);
1983 err
= translate_errno( inMDNS
->p
->quitEvent
, (mStatus
) GetLastError(), kUnknownErr
);
1984 require_noerr( err
, exit
);
1986 inMDNS
->p
->interfaceListChangedEvent
= CreateEvent( NULL
, FALSE
, FALSE
, NULL
);
1987 err
= translate_errno( inMDNS
->p
->interfaceListChangedEvent
, (mStatus
) GetLastError(), kUnknownErr
);
1988 require_noerr( err
, exit
);
1990 inMDNS
->p
->wakeupEvent
= CreateEvent( NULL
, FALSE
, FALSE
, NULL
);
1991 err
= translate_errno( inMDNS
->p
->wakeupEvent
, (mStatus
) GetLastError(), kUnknownErr
);
1992 require_noerr( err
, exit
);
1997 TearDownSynchronizationObjects( inMDNS
);
2002 //===========================================================================================================================
2003 // TearDownSynchronizationObjects
2004 //===========================================================================================================================
2006 mDNSlocal mStatus
TearDownSynchronizationObjects( mDNS
* const inMDNS
)
2008 if( inMDNS
->p
->quitEvent
)
2010 CloseHandle( inMDNS
->p
->quitEvent
);
2011 inMDNS
->p
->quitEvent
= 0;
2013 if( inMDNS
->p
->cancelEvent
)
2015 CloseHandle( inMDNS
->p
->cancelEvent
);
2016 inMDNS
->p
->cancelEvent
= 0;
2018 if( inMDNS
->p
->interfaceListChangedEvent
)
2020 CloseHandle( inMDNS
->p
->interfaceListChangedEvent
);
2021 inMDNS
->p
->interfaceListChangedEvent
= 0;
2023 if( inMDNS
->p
->wakeupEvent
)
2025 CloseHandle( inMDNS
->p
->wakeupEvent
);
2026 inMDNS
->p
->wakeupEvent
= 0;
2028 if( inMDNS
->p
->lockInitialized
)
2030 DeleteCriticalSection( &inMDNS
->p
->lock
);
2031 inMDNS
->p
->lockInitialized
= mDNSfalse
;
2033 return( mStatus_NoError
);
2037 //===========================================================================================================================
2039 //===========================================================================================================================
2041 mDNSlocal mStatus
SetupNiceName( mDNS
* const inMDNS
)
2044 char tempString
[ 256 ];
2049 // Set up the nice name.
2050 tempString
[ 0 ] = '\0';
2053 // First try and open the registry key that contains the computer description value
2054 if (inMDNS
->p
->descKey
== NULL
)
2056 LPCTSTR s
= TEXT("SYSTEM\\CurrentControlSet\\Services\\lanmanserver\\parameters");
2057 err
= RegOpenKeyEx( HKEY_LOCAL_MACHINE
, s
, 0, KEY_READ
, &inMDNS
->p
->descKey
);
2058 check_translated_errno( err
== 0, errno_compat(), kNameErr
);
2062 inMDNS
->p
->descKey
= NULL
;
2066 // if we opened it...
2067 if (inMDNS
->p
->descKey
!= NULL
)
2070 DWORD descSize
= sizeof( desc
);
2072 // look for the computer description
2073 err
= RegQueryValueEx(inMDNS
->p
->descKey
, TEXT("srvcomment"), 0, NULL
, (LPBYTE
) &desc
, &descSize
);
2077 err
= TCHARtoUTF8( desc
, utf8
, sizeof( utf8
) );
2086 // if we can't find it in the registry, then use the hostname of the machine
2087 if ( err
|| ( utf8
[ 0 ] == '\0' ) )
2089 DWORD tempStringLen
= sizeof( tempString
);
2092 ok
= GetComputerNameExA( ComputerNamePhysicalDnsHostname
, tempString
, &tempStringLen
);
2093 err
= translate_errno( ok
, (mStatus
) GetLastError(), kNameErr
);
2098 err
= WindowsLatin1toUTF8( tempString
, utf8
, sizeof( utf8
) );
2107 // if we can't get the hostname
2108 if ( err
|| ( utf8
[ 0 ] == '\0' ) )
2110 // Invalidate name so fall back to a default name.
2112 strcpy( utf8
, kMDNSDefaultName
);
2115 utf8
[ sizeof( utf8
) - 1 ] = '\0';
2116 inMDNS
->nicelabel
.c
[ 0 ] = (mDNSu8
) (strlen( utf8
) < MAX_DOMAIN_LABEL
? strlen( utf8
) : MAX_DOMAIN_LABEL
);
2117 memcpy( &inMDNS
->nicelabel
.c
[ 1 ], utf8
, inMDNS
->nicelabel
.c
[ 0 ] );
2119 dlog( kDebugLevelInfo
, DEBUG_NAME
"nice name \"%.*s\"\n", inMDNS
->nicelabel
.c
[ 0 ], &inMDNS
->nicelabel
.c
[ 1 ] );
2125 //===========================================================================================================================
2127 //===========================================================================================================================
2129 mDNSlocal mStatus
SetupHostName( mDNS
* const inMDNS
)
2132 char tempString
[ 256 ];
2133 DWORD tempStringLen
;
2134 domainlabel tempLabel
;
2139 // Set up the nice name.
2140 tempString
[ 0 ] = '\0';
2142 // use the hostname of the machine
2143 tempStringLen
= sizeof( tempString
);
2144 ok
= GetComputerNameExA( ComputerNamePhysicalDnsHostname
, tempString
, &tempStringLen
);
2145 err
= translate_errno( ok
, (mStatus
) GetLastError(), kNameErr
);
2148 // if we can't get the hostname
2149 if( err
|| ( tempString
[ 0 ] == '\0' ) )
2151 // Invalidate name so fall back to a default name.
2153 strcpy( tempString
, kMDNSDefaultName
);
2156 tempString
[ sizeof( tempString
) - 1 ] = '\0';
2157 tempLabel
.c
[ 0 ] = (mDNSu8
) (strlen( tempString
) < MAX_DOMAIN_LABEL
? strlen( tempString
) : MAX_DOMAIN_LABEL
);
2158 memcpy( &tempLabel
.c
[ 1 ], tempString
, tempLabel
.c
[ 0 ] );
2160 // Set up the host name.
2162 ConvertUTF8PstringToRFC1034HostLabel( tempLabel
.c
, &inMDNS
->hostlabel
);
2163 if( inMDNS
->hostlabel
.c
[ 0 ] == 0 )
2165 // Nice name has no characters that are representable as an RFC1034 name (e.g. Japanese) so use the default.
2167 MakeDomainLabelFromLiteralString( &inMDNS
->hostlabel
, kMDNSDefaultName
);
2170 check( inMDNS
->hostlabel
.c
[ 0 ] != 0 );
2172 mDNS_SetFQDN( inMDNS
);
2174 dlog( kDebugLevelInfo
, DEBUG_NAME
"host name \"%.*s\"\n", inMDNS
->hostlabel
.c
[ 0 ], &inMDNS
->hostlabel
.c
[ 1 ] );
2179 //===========================================================================================================================
2181 //===========================================================================================================================
2183 mDNSlocal mStatus
SetupName( mDNS
* const inMDNS
)
2189 err
= SetupNiceName( inMDNS
);
2192 err
= SetupHostName( inMDNS
);
2199 //===========================================================================================================================
2200 // SetupInterfaceList
2201 //===========================================================================================================================
2203 mDNSlocal mStatus
SetupInterfaceList( mDNS
* const inMDNS
)
2206 mDNSInterfaceData
** next
;
2207 mDNSInterfaceData
* ifd
;
2208 struct ifaddrs
* addrs
;
2210 struct ifaddrs
* loopbackv4
;
2211 struct ifaddrs
* loopbackv6
;
2216 mDNSBool foundUnicastSock4DestAddr
;
2217 mDNSBool foundUnicastSock6DestAddr
;
2219 dlog( kDebugLevelTrace
, DEBUG_NAME
"setting up interface list\n" );
2223 inMDNS
->p
->registeredLoopback4
= mDNSfalse
;
2225 foundv4
= mDNSfalse
;
2226 foundv6
= mDNSfalse
;
2227 foundUnicastSock4DestAddr
= mDNSfalse
;
2228 foundUnicastSock6DestAddr
= mDNSfalse
;
2230 // Tear down any existing interfaces that may be set up.
2232 TearDownInterfaceList( inMDNS
);
2234 // Set up the name of this machine.
2236 err
= SetupName( inMDNS
);
2239 // Set up the interface list change notification.
2241 err
= SetupNotifications( inMDNS
);
2244 // Set up IPv4 interface(s). We have to set up IPv4 first so any IPv6 interface with an IPv4-routable address
2245 // can refer to the IPv4 interface when it registers to allow DNS AAAA records over the IPv4 interface.
2247 err
= getifaddrs( &addrs
);
2248 require_noerr( err
, exit
);
2252 next
= &inMDNS
->p
->interfaceList
;
2254 flagMask
= IFF_UP
| IFF_MULTICAST
;
2255 flagTest
= IFF_UP
| IFF_MULTICAST
;
2257 #if( MDNS_WINDOWS_ENABLE_IPV4 )
2258 for( p
= addrs
; p
; p
= p
->ifa_next
)
2260 if( !p
->ifa_addr
|| ( p
->ifa_addr
->sa_family
!= AF_INET
) || ( ( p
->ifa_flags
& flagMask
) != flagTest
) )
2264 if( p
->ifa_flags
& IFF_LOOPBACK
)
2272 dlog( kDebugLevelVerbose
, DEBUG_NAME
"Interface %40s (0x%08X) %##a\n",
2273 p
->ifa_name
? p
->ifa_name
: "<null>", p
->ifa_extra
.index
, p
->ifa_addr
);
2275 err
= SetupInterface( inMDNS
, p
, &ifd
);
2276 require_noerr( err
, exit
);
2278 // If this guy is point-to-point (ifd->interfaceInfo.McastTxRx == 0 ) we still want to
2279 // register him, but we also want to note that we haven't found a v4 interface
2280 // so that we register loopback so same host operations work
2282 if ( ifd
->interfaceInfo
.McastTxRx
== mDNStrue
)
2287 // If we're on a platform that doesn't have WSARecvMsg(), there's no way
2288 // of determing the destination address of a packet that is sent to us.
2289 // For multicast packets, that's easy to determine. But for the unicast
2290 // sockets, we'll fake it by taking the address of the first interface
2291 // that is successfully setup.
2293 if ( !foundUnicastSock4DestAddr
)
2295 inMDNS
->p
->unicastSock4DestAddr
= ifd
->interfaceInfo
.ip
;
2296 foundUnicastSock4DestAddr
= TRUE
;
2301 ++inMDNS
->p
->interfaceCount
;
2305 // Set up IPv6 interface(s) after IPv4 is set up (see IPv4 notes above for reasoning).
2307 #if( MDNS_WINDOWS_ENABLE_IPV6 )
2308 for( p
= addrs
; p
; p
= p
->ifa_next
)
2310 if( !p
->ifa_addr
|| ( p
->ifa_addr
->sa_family
!= AF_INET6
) || ( ( p
->ifa_flags
& flagMask
) != flagTest
) )
2314 if( p
->ifa_flags
& IFF_LOOPBACK
)
2322 dlog( kDebugLevelVerbose
, DEBUG_NAME
"Interface %40s (0x%08X) %##a\n",
2323 p
->ifa_name
? p
->ifa_name
: "<null>", p
->ifa_extra
.index
, p
->ifa_addr
);
2325 err
= SetupInterface( inMDNS
, p
, &ifd
);
2326 require_noerr( err
, exit
);
2328 // If this guy is point-to-point (ifd->interfaceInfo.McastTxRx == 0 ) we still want to
2329 // register him, but we also want to note that we haven't found a v4 interface
2330 // so that we register loopback so same host operations work
2332 if ( ifd
->interfaceInfo
.McastTxRx
== mDNStrue
)
2337 // If we're on a platform that doesn't have WSARecvMsg(), there's no way
2338 // of determing the destination address of a packet that is sent to us.
2339 // For multicast packets, that's easy to determine. But for the unicast
2340 // sockets, we'll fake it by taking the address of the first interface
2341 // that is successfully setup.
2343 if ( !foundUnicastSock6DestAddr
)
2345 inMDNS
->p
->unicastSock6DestAddr
= ifd
->interfaceInfo
.ip
;
2346 foundUnicastSock6DestAddr
= TRUE
;
2351 ++inMDNS
->p
->interfaceCount
;
2355 // If there are no real interfaces, but there is a loopback interface, use that so same-machine operations work.
2357 #if( !MDNS_WINDOWS_ENABLE_IPV4 && !MDNS_WINDOWS_ENABLE_IPV6 )
2359 flagMask
|= IFF_LOOPBACK
;
2360 flagTest
|= IFF_LOOPBACK
;
2362 for( p
= addrs
; p
; p
= p
->ifa_next
)
2364 if( !p
->ifa_addr
|| ( ( p
->ifa_flags
& flagMask
) != flagTest
) )
2368 if( ( p
->ifa_addr
->sa_family
!= AF_INET
) && ( p
->ifa_addr
->sa_family
!= AF_INET6
) )
2379 if ( !foundv4
&& loopbackv4
)
2381 dlog( kDebugLevelVerbose
, DEBUG_NAME
"Interface %40s (0x%08X) %##a\n",
2382 loopbackv4
->ifa_name
? loopbackv4
->ifa_name
: "<null>", loopbackv4
->ifa_extra
.index
, loopbackv4
->ifa_addr
);
2384 err
= SetupInterface( inMDNS
, loopbackv4
, &ifd
);
2385 require_noerr( err
, exit
);
2387 inMDNS
->p
->registeredLoopback4
= mDNStrue
;
2389 #if( MDNS_WINDOWS_ENABLE_IPV4 )
2391 // If we're on a platform that doesn't have WSARecvMsg(), there's no way
2392 // of determing the destination address of a packet that is sent to us.
2393 // For multicast packets, that's easy to determine. But for the unicast
2394 // sockets, we'll fake it by taking the address of the first interface
2395 // that is successfully setup.
2397 if ( !foundUnicastSock4DestAddr
)
2399 inMDNS
->p
->unicastSock4DestAddr
= ifd
->defaultAddr
;
2400 foundUnicastSock4DestAddr
= TRUE
;
2406 ++inMDNS
->p
->interfaceCount
;
2412 TearDownInterfaceList( inMDNS
);
2416 freeifaddrs( addrs
);
2418 dlog( kDebugLevelTrace
, DEBUG_NAME
"setting up interface list done (err=%d %m)\n", err
, err
);
2422 //===========================================================================================================================
2423 // TearDownInterfaceList
2424 //===========================================================================================================================
2426 mDNSlocal mStatus
TearDownInterfaceList( mDNS
* const inMDNS
)
2429 mDNSInterfaceData
** p
;
2430 mDNSInterfaceData
* ifd
;
2432 dlog( kDebugLevelTrace
, DEBUG_NAME
"tearing down interface list\n" );
2436 // Free any interfaces that were previously marked inactive and are no longer referenced by the mDNS cache.
2437 // Interfaces are marked inactive, but not deleted immediately if they were still referenced by the mDNS cache
2438 // so that remove events that occur after an interface goes away can still report the correct interface.
2440 p
= &inMDNS
->p
->inactiveInterfaceList
;
2444 if( NumCacheRecordsForInterfaceID( inMDNS
, (mDNSInterfaceID
) ifd
) > 0 )
2450 dlog( kDebugLevelInfo
, DEBUG_NAME
"freeing unreferenced, inactive interface %#p %#a\n", ifd
, &ifd
->interfaceInfo
.ip
);
2455 // Tear down interface list change notifications.
2457 err
= TearDownNotifications( inMDNS
);
2460 // Tear down all the interfaces.
2462 while( inMDNS
->p
->interfaceList
)
2464 ifd
= inMDNS
->p
->interfaceList
;
2465 inMDNS
->p
->interfaceList
= ifd
->next
;
2467 TearDownInterface( inMDNS
, ifd
);
2469 inMDNS
->p
->interfaceCount
= 0;
2471 dlog( kDebugLevelTrace
, DEBUG_NAME
"tearing down interface list done\n" );
2472 return( mStatus_NoError
);
2475 //===========================================================================================================================
2477 //===========================================================================================================================
2479 mDNSlocal mStatus
SetupInterface( mDNS
* const inMDNS
, const struct ifaddrs
*inIFA
, mDNSInterfaceData
**outIFD
)
2481 mDNSInterfaceData
* ifd
;
2482 mDNSInterfaceData
* p
;
2487 dlog( kDebugLevelTrace
, DEBUG_NAME
"setting up interface\n" );
2491 check( inIFA
->ifa_addr
);
2494 // Allocate memory for the interface and initialize it.
2496 ifd
= (mDNSInterfaceData
*) calloc( 1, sizeof( *ifd
) );
2497 require_action( ifd
, exit
, err
= mStatus_NoMemoryErr
);
2498 ifd
->sock
= kInvalidSocketRef
;
2499 ifd
->index
= inIFA
->ifa_extra
.index
;
2500 ifd
->scopeID
= inIFA
->ifa_extra
.index
;
2501 check( strlen( inIFA
->ifa_name
) < sizeof( ifd
->name
) );
2502 strncpy( ifd
->name
, inIFA
->ifa_name
, sizeof( ifd
->name
) - 1 );
2503 ifd
->name
[ sizeof( ifd
->name
) - 1 ] = '\0';
2505 strncpy(ifd
->interfaceInfo
.ifname
, inIFA
->ifa_name
, sizeof(ifd
->interfaceInfo
.ifname
));
2506 ifd
->interfaceInfo
.ifname
[sizeof(ifd
->interfaceInfo
.ifname
)-1] = 0;
2508 // We always send and receive using IPv4, but to reduce traffic, we send and receive using IPv6 only on interfaces
2509 // that have no routable IPv4 address. Having a routable IPv4 address assigned is a reasonable indicator of being
2510 // on a large configured network, which means there's a good chance that most or all the other devices on that
2511 // network should also have v4. By doing this we lose the ability to talk to true v6-only devices on that link,
2512 // but we cut the packet rate in half. At this time, reducing the packet rate is more important than v6-only
2513 // devices on a large configured network, so we are willing to make that sacrifice.
2515 ifd
->interfaceInfo
.McastTxRx
= ( ( inIFA
->ifa_flags
& IFF_MULTICAST
) && !( inIFA
->ifa_flags
& IFF_POINTTOPOINT
) ) ? mDNStrue
: mDNSfalse
;
2516 ifd
->interfaceInfo
.InterfaceID
= NULL
;
2518 for( p
= inMDNS
->p
->interfaceList
; p
; p
= p
->next
)
2520 if ( strcmp( p
->name
, ifd
->name
) == 0 )
2522 if (!ifd
->interfaceInfo
.InterfaceID
)
2524 ifd
->interfaceInfo
.InterfaceID
= (mDNSInterfaceID
) p
;
2527 if ( ( inIFA
->ifa_addr
->sa_family
!= AF_INET
) &&
2528 ( p
->interfaceInfo
.ip
.type
== mDNSAddrType_IPv4
) &&
2529 ( p
->interfaceInfo
.ip
.ip
.v4
.b
[ 0 ] != 169 || p
->interfaceInfo
.ip
.ip
.v4
.b
[ 1 ] != 254 ) )
2531 ifd
->interfaceInfo
.McastTxRx
= mDNSfalse
;
2538 if ( !ifd
->interfaceInfo
.InterfaceID
)
2540 ifd
->interfaceInfo
.InterfaceID
= (mDNSInterfaceID
) ifd
;
2543 // Set up a socket for this interface (if needed).
2545 if( ifd
->interfaceInfo
.McastTxRx
)
2547 err
= SetupSocket( inMDNS
, inIFA
->ifa_addr
, MulticastDNSPort
, &sock
);
2548 require_noerr( err
, exit
);
2550 ifd
->defaultAddr
= ( inIFA
->ifa_addr
->sa_family
== AF_INET6
) ? AllDNSLinkGroup_v6
: AllDNSLinkGroup_v4
;
2552 // Get a ptr to the WSARecvMsg function, if supported. Otherwise, we'll fallback to recvfrom.
2554 #if( !TARGET_OS_WINDOWS_CE )
2558 // If we are running inside VPC, then we won't use WSARecvMsg because it will give us bogus information due to
2559 // a bug in VPC itself.
2561 err
= inMDNS
->p
->inVirtualPC
;
2565 err
= WSAIoctl( sock
, SIO_GET_EXTENSION_FUNCTION_POINTER
, &kWSARecvMsgGUID
, sizeof( kWSARecvMsgGUID
),
2566 &ifd
->wsaRecvMsgFunctionPtr
, sizeof( ifd
->wsaRecvMsgFunctionPtr
), &size
, NULL
, NULL
);
2571 ifd
->wsaRecvMsgFunctionPtr
= NULL
;
2576 // Set up the read pending event and associate it so we can block until data is available for this socket.
2578 ifd
->readPendingEvent
= CreateEvent( NULL
, FALSE
, FALSE
, NULL
);
2579 err
= translate_errno( ifd
->readPendingEvent
, (mStatus
) GetLastError(), kUnknownErr
);
2580 require_noerr( err
, exit
);
2582 err
= WSAEventSelect( ifd
->sock
, ifd
->readPendingEvent
, FD_READ
);
2583 require_noerr( err
, exit
);
2587 // Create a placeholder event so WaitForMultipleObjects Handle slot for this interface is valid.
2589 ifd
->readPendingEvent
= CreateEvent( NULL
, FALSE
, FALSE
, NULL
);
2590 err
= translate_errno( ifd
->readPendingEvent
, (mStatus
) GetLastError(), kUnknownErr
);
2591 require_noerr( err
, exit
);
2594 // Register this interface with mDNS.
2596 err
= SockAddrToMDNSAddr( inIFA
->ifa_addr
, &ifd
->interfaceInfo
.ip
, NULL
);
2597 require_noerr( err
, exit
);
2599 err
= SockAddrToMDNSAddr( inIFA
->ifa_netmask
, &ifd
->interfaceInfo
.mask
, NULL
);
2600 require_noerr( err
, exit
);
2602 ifd
->interfaceInfo
.Advertise
= inMDNS
->AdvertiseLocalAddresses
;
2604 err
= mDNS_RegisterInterface( inMDNS
, &ifd
->interfaceInfo
, mDNSfalse
);
2605 require_noerr( err
, exit
);
2606 ifd
->hostRegistered
= mDNStrue
;
2608 dlog( kDebugLevelInfo
, DEBUG_NAME
"Registered interface %##a with mDNS\n", inIFA
->ifa_addr
);
2618 TearDownInterface( inMDNS
, ifd
);
2620 dlog( kDebugLevelTrace
, DEBUG_NAME
"setting up interface done (err=%d %m)\n", err
, err
);
2624 //===========================================================================================================================
2625 // TearDownInterface
2626 //===========================================================================================================================
2628 mDNSlocal mStatus
TearDownInterface( mDNS
* const inMDNS
, mDNSInterfaceData
*inIFD
)
2635 // Deregister this interface with mDNS.
2637 dlog( kDebugLevelInfo
, DEBUG_NAME
"Deregistering interface %#a with mDNS\n", &inIFD
->interfaceInfo
.ip
);
2639 if( inIFD
->hostRegistered
)
2641 inIFD
->hostRegistered
= mDNSfalse
;
2642 mDNS_DeregisterInterface( inMDNS
, &inIFD
->interfaceInfo
, mDNSfalse
);
2645 // Tear down the multicast socket.
2647 if( inIFD
->readPendingEvent
)
2649 CloseHandle( inIFD
->readPendingEvent
);
2650 inIFD
->readPendingEvent
= 0;
2654 inIFD
->sock
= kInvalidSocketRef
;
2655 if( IsValidSocket( sock
) )
2657 close_compat( sock
);
2660 // If the interface is still referenced by items in the mDNS cache then put it on the inactive list. This keeps
2661 // the InterfaceID valid so remove events report the correct interface. If it is no longer referenced, free it.
2663 if( NumCacheRecordsForInterfaceID( inMDNS
, (mDNSInterfaceID
) inIFD
) > 0 )
2665 inIFD
->next
= inMDNS
->p
->inactiveInterfaceList
;
2666 inMDNS
->p
->inactiveInterfaceList
= inIFD
;
2667 dlog( kDebugLevelInfo
, DEBUG_NAME
"deferring free of interface %#p %#a\n", inIFD
, &inIFD
->interfaceInfo
.ip
);
2671 dlog( kDebugLevelInfo
, DEBUG_NAME
"freeing interface %#p %#a immediately\n", inIFD
, &inIFD
->interfaceInfo
.ip
);
2674 return( mStatus_NoError
);
2677 //===========================================================================================================================
2679 //===========================================================================================================================
2681 mDNSlocal mStatus
SetupSocket( mDNS
* const inMDNS
, const struct sockaddr
*inAddr
, mDNSIPPort port
, SocketRef
*outSocketRef
)
2687 DEBUG_UNUSED( inMDNS
);
2689 dlog( kDebugLevelTrace
, DEBUG_NAME
"setting up socket %##a\n", inAddr
);
2691 check( outSocketRef
);
2693 // Set up an IPv4 or IPv6 UDP socket.
2695 sock
= socket( inAddr
->sa_family
, SOCK_DGRAM
, IPPROTO_UDP
);
2696 err
= translate_errno( IsValidSocket( sock
), errno_compat(), kUnknownErr
);
2697 require_noerr( err
, exit
);
2699 // Turn on reuse address option so multiple servers can listen for Multicast DNS packets,
2700 // if we're creating a multicast socket
2702 if ( port
.NotAnInteger
)
2705 err
= setsockopt( sock
, SOL_SOCKET
, SO_REUSEADDR
, (char *) &option
, sizeof( option
) );
2706 check_translated_errno( err
== 0, errno_compat(), kOptionErr
);
2709 if( inAddr
->sa_family
== AF_INET
)
2712 struct sockaddr_in sa4
;
2713 struct ip_mreq mreqv4
;
2715 // Bind the socket to the desired port
2717 ipv4
.NotAnInteger
= ( (const struct sockaddr_in
*) inAddr
)->sin_addr
.s_addr
;
2718 memset( &sa4
, 0, sizeof( sa4
) );
2719 sa4
.sin_family
= AF_INET
;
2720 sa4
.sin_port
= port
.NotAnInteger
;
2721 sa4
.sin_addr
.s_addr
= ipv4
.NotAnInteger
;
2723 err
= bind( sock
, (struct sockaddr
*) &sa4
, sizeof( sa4
) );
2724 check_translated_errno( err
== 0, errno_compat(), kUnknownErr
);
2726 // Turn on option to receive destination addresses and receiving interface.
2729 err
= setsockopt( sock
, IPPROTO_IP
, IP_PKTINFO
, (char *) &option
, sizeof( option
) );
2730 check_translated_errno( err
== 0, errno_compat(), kOptionErr
);
2732 if (port
.NotAnInteger
)
2734 // Join the all-DNS multicast group so we receive Multicast DNS packets
2736 mreqv4
.imr_multiaddr
.s_addr
= AllDNSLinkGroup_v4
.ip
.v4
.NotAnInteger
;
2737 mreqv4
.imr_interface
.s_addr
= ipv4
.NotAnInteger
;
2738 err
= setsockopt( sock
, IPPROTO_IP
, IP_ADD_MEMBERSHIP
, (char *) &mreqv4
, sizeof( mreqv4
) );
2739 check_translated_errno( err
== 0, errno_compat(), kOptionErr
);
2741 // Specify the interface to send multicast packets on this socket.
2743 sa4
.sin_addr
.s_addr
= ipv4
.NotAnInteger
;
2744 err
= setsockopt( sock
, IPPROTO_IP
, IP_MULTICAST_IF
, (char *) &sa4
.sin_addr
, sizeof( sa4
.sin_addr
) );
2745 check_translated_errno( err
== 0, errno_compat(), kOptionErr
);
2747 // Enable multicast loopback so we receive multicast packets we send (for same-machine operations).
2750 err
= setsockopt( sock
, IPPROTO_IP
, IP_MULTICAST_LOOP
, (char *) &option
, sizeof( option
) );
2751 check_translated_errno( err
== 0, errno_compat(), kOptionErr
);
2754 // Send unicast packets with TTL 255 (helps against spoofing).
2757 err
= setsockopt( sock
, IPPROTO_IP
, IP_TTL
, (char *) &option
, sizeof( option
) );
2758 check_translated_errno( err
== 0, errno_compat(), kOptionErr
);
2760 // Send multicast packets with TTL 255 (helps against spoofing).
2763 err
= setsockopt( sock
, IPPROTO_IP
, IP_MULTICAST_TTL
, (char *) &option
, sizeof( option
) );
2764 check_translated_errno( err
== 0, errno_compat(), kOptionErr
);
2767 else if( inAddr
->sa_family
== AF_INET6
)
2769 struct sockaddr_in6
* sa6p
;
2770 struct sockaddr_in6 sa6
;
2771 struct ipv6_mreq mreqv6
;
2773 sa6p
= (struct sockaddr_in6
*) inAddr
;
2775 // Bind the socket to the desired port
2777 memset( &sa6
, 0, sizeof( sa6
) );
2778 sa6
.sin6_family
= AF_INET6
;
2779 sa6
.sin6_port
= port
.NotAnInteger
;
2780 sa6
.sin6_flowinfo
= 0;
2781 sa6
.sin6_addr
= sa6p
->sin6_addr
;
2782 sa6
.sin6_scope_id
= sa6p
->sin6_scope_id
;
2784 err
= bind( sock
, (struct sockaddr
*) &sa6
, sizeof( sa6
) );
2785 check_translated_errno( err
== 0, errno_compat(), kUnknownErr
);
2787 // Turn on option to receive destination addresses and receiving interface.
2790 err
= setsockopt( sock
, IPPROTO_IPV6
, IPV6_PKTINFO
, (char *) &option
, sizeof( option
) );
2791 check_translated_errno( err
== 0, errno_compat(), kOptionErr
);
2793 // We only want to receive IPv6 packets (not IPv4-mapped IPv6 addresses) because we have a separate socket
2794 // for IPv4, but the IPv6 stack in Windows currently doesn't support IPv4-mapped IPv6 addresses and doesn't
2795 // support the IPV6_V6ONLY socket option so the following code would typically not be executed (or needed).
2797 #if( defined( IPV6_V6ONLY ) )
2799 err
= setsockopt( sock
, IPPROTO_IPV6
, IPV6_V6ONLY
, (char *) &option
, sizeof( option
) );
2800 check_translated_errno( err
== 0, errno_compat(), kOptionErr
);
2803 if ( port
.NotAnInteger
)
2805 // Join the all-DNS multicast group so we receive Multicast DNS packets.
2807 mreqv6
.ipv6mr_multiaddr
= *( (struct in6_addr
*) &AllDNSLinkGroup_v6
.ip
.v6
);
2808 mreqv6
.ipv6mr_interface
= sa6p
->sin6_scope_id
;
2809 err
= setsockopt( sock
, IPPROTO_IPV6
, IPV6_JOIN_GROUP
, (char *) &mreqv6
, sizeof( mreqv6
) );
2810 check_translated_errno( err
== 0, errno_compat(), kOptionErr
);
2812 // Specify the interface to send multicast packets on this socket.
2814 option
= (int) sa6p
->sin6_scope_id
;
2815 err
= setsockopt( sock
, IPPROTO_IPV6
, IPV6_MULTICAST_IF
, (char *) &option
, sizeof( option
) );
2816 check_translated_errno( err
== 0, errno_compat(), kOptionErr
);
2818 // Enable multicast loopback so we receive multicast packets we send (for same-machine operations).
2821 err
= setsockopt( sock
, IPPROTO_IPV6
, IPV6_MULTICAST_LOOP
, (char *) &option
, sizeof( option
) );
2822 check_translated_errno( err
== 0, errno_compat(), kOptionErr
);
2825 // Send unicast packets with TTL 255 (helps against spoofing).
2828 err
= setsockopt( sock
, IPPROTO_IPV6
, IPV6_UNICAST_HOPS
, (char *) &option
, sizeof( option
) );
2829 check_translated_errno( err
== 0, errno_compat(), kOptionErr
);
2831 // Send multicast packets with TTL 255 (helps against spoofing).
2834 err
= setsockopt( sock
, IPPROTO_IPV6
, IPV6_MULTICAST_HOPS
, (char *) &option
, sizeof( option
) );
2835 check_translated_errno( err
== 0, errno_compat(), kOptionErr
);
2839 dlog( kDebugLevelError
, DEBUG_NAME
"%s: unsupport socket family (%d)\n", __ROUTINE__
, inAddr
->sa_family
);
2840 err
= kUnsupportedErr
;
2846 *outSocketRef
= sock
;
2847 sock
= kInvalidSocketRef
;
2848 err
= mStatus_NoError
;
2851 if( IsValidSocket( sock
) )
2853 close_compat( sock
);
2858 //===========================================================================================================================
2860 //===========================================================================================================================
2862 mDNSlocal mStatus
SockAddrToMDNSAddr( const struct sockaddr
* const inSA
, mDNSAddr
*outIP
, mDNSIPPort
*outPort
)
2869 if( inSA
->sa_family
== AF_INET
)
2871 struct sockaddr_in
* sa4
;
2873 sa4
= (struct sockaddr_in
*) inSA
;
2874 outIP
->type
= mDNSAddrType_IPv4
;
2875 outIP
->ip
.v4
.NotAnInteger
= sa4
->sin_addr
.s_addr
;
2878 outPort
->NotAnInteger
= sa4
->sin_port
;
2880 err
= mStatus_NoError
;
2882 else if( inSA
->sa_family
== AF_INET6
)
2884 struct sockaddr_in6
* sa6
;
2886 sa6
= (struct sockaddr_in6
*) inSA
;
2887 outIP
->type
= mDNSAddrType_IPv6
;
2888 outIP
->ip
.v6
= *( (mDNSv6Addr
*) &sa6
->sin6_addr
);
2889 if( IN6_IS_ADDR_LINKLOCAL( &sa6
->sin6_addr
) )
2891 outIP
->ip
.v6
.w
[ 1 ] = 0;
2895 outPort
->NotAnInteger
= sa6
->sin6_port
;
2897 err
= mStatus_NoError
;
2901 dlog( kDebugLevelError
, DEBUG_NAME
"%s: invalid sa_family %d", __ROUTINE__
, inSA
->sa_family
);
2902 err
= mStatus_BadParamErr
;
2907 //===========================================================================================================================
2908 // SetupNotifications
2909 //===========================================================================================================================
2911 mDNSlocal mStatus
SetupNotifications( mDNS
* const inMDNS
)
2915 unsigned long param
;
2920 // Register to listen for address list changes.
2922 sock
= socket( AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
2923 err
= translate_errno( IsValidSocket( sock
), errno_compat(), kUnknownErr
);
2924 require_noerr( err
, exit
);
2925 inMDNS
->p
->interfaceListChangedSocket
= sock
;
2927 // Make the socket non-blocking so the WSAIoctl returns immediately with WSAEWOULDBLOCK. It will set the event
2928 // when a change to the interface list is detected.
2931 err
= ioctlsocket( sock
, FIONBIO
, ¶m
);
2932 err
= translate_errno( err
== 0, errno_compat(), kUnknownErr
);
2933 require_noerr( err
, exit
);
2937 err
= WSAIoctl( sock
, SIO_ADDRESS_LIST_CHANGE
, &inBuffer
, 0, &outBuffer
, 0, &outSize
, NULL
, NULL
);
2940 check( errno_compat() == WSAEWOULDBLOCK
);
2943 err
= WSAEventSelect( sock
, inMDNS
->p
->interfaceListChangedEvent
, FD_ADDRESS_LIST_CHANGE
);
2944 err
= translate_errno( err
== 0, errno_compat(), kUnknownErr
);
2945 require_noerr( err
, exit
);
2947 inMDNS
->p
->descChangedEvent
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2948 err
= translate_errno( inMDNS
->p
->descChangedEvent
, (mStatus
) GetLastError(), kUnknownErr
);
2949 require_noerr( err
, exit
);
2951 if (inMDNS
->p
->descKey
!= NULL
)
2953 err
= RegNotifyChangeKeyValue(inMDNS
->p
->descKey
, TRUE
, REG_NOTIFY_CHANGE_LAST_SET
, inMDNS
->p
->descChangedEvent
, TRUE
);
2954 require_noerr( err
, exit
);
2957 // This will catch all changes to tcp/ip networking, including changes to the domain search list
2959 inMDNS
->p
->tcpipChangedEvent
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
2960 err
= translate_errno( inMDNS
->p
->tcpipChangedEvent
, (mStatus
) GetLastError(), kUnknownErr
);
2961 require_noerr( err
, exit
);
2963 err
= RegCreateKey( HKEY_LOCAL_MACHINE
, TEXT("SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters"), &inMDNS
->p
->tcpipKey
);
2964 require_noerr( err
, exit
);
2966 err
= RegNotifyChangeKeyValue(inMDNS
->p
->tcpipKey
, TRUE
, REG_NOTIFY_CHANGE_NAME
|REG_NOTIFY_CHANGE_LAST_SET
, inMDNS
->p
->tcpipChangedEvent
, TRUE
);
2967 require_noerr( err
, exit
);
2969 // This will catch all changes to ddns configuration
2971 inMDNS
->p
->ddnsChangedEvent
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
2972 err
= translate_errno( inMDNS
->p
->ddnsChangedEvent
, (mStatus
) GetLastError(), kUnknownErr
);
2973 require_noerr( err
, exit
);
2975 err
= RegCreateKey( HKEY_LOCAL_MACHINE
, kServiceParametersNode
TEXT("\\DynDNS\\Setup"), &inMDNS
->p
->ddnsKey
);
2976 require_noerr( err
, exit
);
2978 err
= RegNotifyChangeKeyValue(inMDNS
->p
->ddnsKey
, TRUE
, REG_NOTIFY_CHANGE_NAME
|REG_NOTIFY_CHANGE_LAST_SET
, inMDNS
->p
->ddnsChangedEvent
, TRUE
);
2979 require_noerr( err
, exit
);
2984 TearDownNotifications( inMDNS
);
2989 //===========================================================================================================================
2990 // TearDownNotifications
2991 //===========================================================================================================================
2993 mDNSlocal mStatus
TearDownNotifications( mDNS
* const inMDNS
)
2995 if( IsValidSocket( inMDNS
->p
->interfaceListChangedSocket
) )
2997 close_compat( inMDNS
->p
->interfaceListChangedSocket
);
2998 inMDNS
->p
->interfaceListChangedSocket
= kInvalidSocketRef
;
3001 if ( inMDNS
->p
->descChangedEvent
!= NULL
)
3003 CloseHandle( inMDNS
->p
->descChangedEvent
);
3004 inMDNS
->p
->descChangedEvent
= NULL
;
3007 if ( inMDNS
->p
->descKey
!= NULL
)
3009 RegCloseKey( inMDNS
->p
->descKey
);
3010 inMDNS
->p
->descKey
= NULL
;
3013 if ( inMDNS
->p
->tcpipChangedEvent
!= NULL
)
3015 CloseHandle( inMDNS
->p
->tcpipChangedEvent
);
3016 inMDNS
->p
->tcpipChangedEvent
= NULL
;
3019 if ( inMDNS
->p
->ddnsChangedEvent
!= NULL
)
3021 CloseHandle( inMDNS
->p
->ddnsChangedEvent
);
3022 inMDNS
->p
->ddnsChangedEvent
= NULL
;
3025 if ( inMDNS
->p
->ddnsKey
!= NULL
)
3027 RegCloseKey( inMDNS
->p
->ddnsKey
);
3028 inMDNS
->p
->ddnsKey
= NULL
;
3031 return( mStatus_NoError
);
3035 //===========================================================================================================================
3036 // SetupRetryVPCCheck
3037 //===========================================================================================================================
3040 SetupRetryVPCCheck( mDNS
* const inMDNS
)
3042 LARGE_INTEGER liDueTime
;
3046 dlog( kDebugLevelTrace
, DEBUG_NAME
"setting up retry VirtualPC check\n" );
3048 liDueTime
.QuadPart
= kRetryVPCRate
;
3050 // Create a waitable timer.
3052 inMDNS
->p
->vpcCheckEvent
= CreateWaitableTimer( NULL
, TRUE
, TEXT( "VPCCheckTimer" ) );
3053 err
= translate_errno( inMDNS
->p
->vpcCheckEvent
, (mStatus
) GetLastError(), kUnknownErr
);
3054 require_noerr( err
, exit
);
3056 // Set a timer to wait for 10 seconds.
3058 ok
= SetWaitableTimer( inMDNS
->p
->vpcCheckEvent
, &liDueTime
, 0, NULL
, NULL
, 0 );
3059 err
= translate_errno( ok
, (OSStatus
) GetLastError(), kUnknownErr
);
3060 require_noerr( err
, exit
);
3062 inMDNS
->p
->timersCount
++;
3070 //===========================================================================================================================
3071 // TearDownRetryVPCCheck
3072 //===========================================================================================================================
3075 TearDownRetryVPCCheck( mDNS
* const inMDNS
)
3077 dlog( kDebugLevelTrace
, DEBUG_NAME
"tearing down retry VirtualPC check\n" );
3079 if ( inMDNS
->p
->vpcCheckEvent
)
3081 CancelWaitableTimer( inMDNS
->p
->vpcCheckEvent
);
3082 CloseHandle( inMDNS
->p
->vpcCheckEvent
);
3084 inMDNS
->p
->vpcCheckEvent
= NULL
;
3085 inMDNS
->p
->timersCount
--;
3088 return ( mStatus_NoError
);
3096 //===========================================================================================================================
3098 //===========================================================================================================================
3100 mDNSlocal mStatus
SetupThread( mDNS
* const inMDNS
)
3103 HANDLE threadHandle
;
3107 dlog( kDebugLevelTrace
, DEBUG_NAME
"setting up thread\n" );
3109 // To avoid a race condition with the thread ID needed by the unlocking code, we need to make sure the
3110 // thread has fully initialized. To do this, we create the thread then wait for it to signal it is ready.
3112 inMDNS
->p
->initEvent
= CreateEvent( NULL
, FALSE
, FALSE
, NULL
);
3113 err
= translate_errno( inMDNS
->p
->initEvent
, (mStatus
) GetLastError(), kUnknownErr
);
3114 require_noerr( err
, exit
);
3116 inMDNS
->p
->initStatus
= mStatus_Invalid
;
3118 // Create thread with _beginthreadex() instead of CreateThread() to avoid memory leaks when using static run-time
3119 // libraries. See <http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/createthread.asp>.
3121 threadHandle
= (HANDLE
) _beginthreadex_compat( NULL
, 0, ProcessingThread
, inMDNS
, 0, &threadID
);
3122 err
= translate_errno( threadHandle
, (mStatus
) GetLastError(), kUnknownErr
);
3123 require_noerr( err
, exit
);
3125 result
= WaitForSingleObject( inMDNS
->p
->initEvent
, INFINITE
);
3126 err
= translate_errno( result
== WAIT_OBJECT_0
, (mStatus
) GetLastError(), kUnknownErr
);
3127 require_noerr( err
, exit
);
3128 err
= inMDNS
->p
->initStatus
;
3129 require_noerr( err
, exit
);
3132 if( inMDNS
->p
->initEvent
)
3134 CloseHandle( inMDNS
->p
->initEvent
);
3135 inMDNS
->p
->initEvent
= 0;
3137 dlog( kDebugLevelTrace
, DEBUG_NAME
"setting up thread done (err=%d %m)\n", err
, err
);
3141 //===========================================================================================================================
3143 //===========================================================================================================================
3145 mDNSlocal mStatus
TearDownThread( const mDNS
* const inMDNS
)
3147 // Signal the cancel event to cause the thread to exit. Then wait for the quit event to be signal indicating it did
3148 // exit. If the quit event is not signal in 5 seconds, just give up and close anyway sinec the thread is probably hung.
3150 if( inMDNS
->p
->cancelEvent
)
3155 wasSet
= SetEvent( inMDNS
->p
->cancelEvent
);
3156 check_translated_errno( wasSet
, GetLastError(), kUnknownErr
);
3158 if( inMDNS
->p
->quitEvent
)
3160 result
= WaitForSingleObject( inMDNS
->p
->quitEvent
, 5 * 1000 );
3161 check_translated_errno( result
== WAIT_OBJECT_0
, GetLastError(), kUnknownErr
);
3164 return( mStatus_NoError
);
3167 //===========================================================================================================================
3169 //===========================================================================================================================
3171 mDNSlocal
unsigned WINAPI
ProcessingThread( LPVOID inParam
)
3183 m
= (mDNS
*) inParam
;
3184 err
= ProcessingThreadInitialize( m
);
3190 // Set up the list of objects we'll be waiting on.
3194 err
= ProcessingThreadSetupWaitList( m
, &waitList
, &waitListCount
);
3195 require_noerr( err
, exit
);
3197 // Main processing loop.
3199 gWaitListChanged
= FALSE
;
3203 // Give the mDNS core a chance to do its work and determine next event time.
3205 mDNSs32 interval
= mDNS_Execute(m
) - mDNS_TimeNow(m
);
3207 if ( gWaitListChanged
)
3212 if (m
->p
->idleThreadCallback
)
3214 interval
= m
->p
->idleThreadCallback(m
, interval
);
3216 if (interval
< 0) interval
= 0;
3217 else if (interval
> (0x7FFFFFFF / 1000)) interval
= 0x7FFFFFFF / mDNSPlatformOneSecond
;
3218 else interval
= (interval
* 1000) / mDNSPlatformOneSecond
;
3220 // Wait until something occurs (e.g. cancel, incoming packet, or timeout).
3222 result
= WaitForMultipleObjects( (DWORD
) waitListCount
, waitList
, FALSE
, (DWORD
) interval
);
3223 check( result
!= WAIT_FAILED
);
3225 if ( result
!= WAIT_FAILED
)
3227 if( result
== WAIT_TIMEOUT
)
3229 // Next task timeout occurred. Loop back up to give mDNS core a chance to work.
3231 dlog( kDebugLevelChatty
- 1, DEBUG_NAME
"timeout\n" );
3234 else if( result
== kWaitListCancelEvent
)
3236 // Cancel event. Set the done flag and break to exit.
3238 dlog( kDebugLevelVerbose
, DEBUG_NAME
"canceling...\n" );
3242 else if( result
== kWaitListInterfaceListChangedEvent
)
3244 // Interface list changed event. Break out of the inner loop to re-setup the wait list.
3246 ProcessingThreadInterfaceListChanged( m
);
3249 else if( result
== kWaitListWakeupEvent
)
3251 // Wakeup event due to an mDNS API call. Loop back to call mDNS_Execute.
3253 dlog( kDebugLevelChatty
- 1, DEBUG_NAME
"wakeup for mDNS_Execute\n" );
3256 else if ( result
== kWaitListComputerDescriptionEvent
)
3259 // The computer description might have changed
3261 ProcessingThreadComputerDescriptionChanged( m
);
3264 else if ( result
== kWaitListTCPIPEvent
)
3267 // The TCP/IP might have changed
3269 ProcessingThreadTCPIPConfigChanged( m
);
3272 else if ( result
== kWaitListDynDNSEvent
)
3275 // The DynDNS config might have changed
3277 ProcessingThreadDynDNSConfigChanged( m
);
3284 // Socket data available event. Determine which socket and process the packet.
3286 waitItemIndex
= (int)( ( (int) result
) - WAIT_OBJECT_0
);
3287 dlog( kDebugLevelChatty
, DEBUG_NAME
"socket data available on socket index %d\n", waitItemIndex
);
3288 check( ( waitItemIndex
>= 0 ) && ( waitItemIndex
< waitListCount
) );
3289 if( ( waitItemIndex
>= 0 ) && ( waitItemIndex
< waitListCount
) )
3291 HANDLE signaledObject
;
3293 mDNSInterfaceData
* ifd
;
3296 signaledObject
= waitList
[ waitItemIndex
];
3298 if ( m
->p
->vpcCheckEvent
== signaledObject
)
3300 ProcessingThreadRetryVPCCheck( m
);
3305 #if ( MDNS_WINDOWS_ENABLE_IPV4 )
3306 if ( m
->p
->unicastSock4ReadEvent
== signaledObject
)
3308 ProcessingThreadProcessPacket( m
, NULL
, m
->p
->unicastSock4
);
3313 #if ( MDNS_WINDOWS_ENABLE_IPV6 )
3314 if ( m
->p
->unicastSock6ReadEvent
== signaledObject
)
3316 ProcessingThreadProcessPacket( m
, NULL
, m
->p
->unicastSock6
);
3321 for( ifd
= m
->p
->interfaceList
; ifd
; ifd
= ifd
->next
)
3323 if( ifd
->readPendingEvent
== signaledObject
)
3325 ProcessingThreadProcessPacket( m
, ifd
, ifd
->sock
);
3330 for ( tcd
= gTCPConnectionList
; tcd
; tcd
= tcd
->next
)
3332 if ( tcd
->pendingEvent
== signaledObject
)
3334 mDNSBool connect
= FALSE
;
3336 if ( !tcd
->connected
)
3338 tcd
->connected
= mDNStrue
;
3342 tcd
->callback( tcd
, tcd
->context
, connect
, 0 );
3354 // Unexpected wait result.
3356 dlog( kDebugLevelWarning
, DEBUG_NAME
"%s: unexpected wait result (result=0x%08X)\n", __ROUTINE__
, result
);
3363 err
= ProcessingThreadInitialize( m
);
3369 // Release the wait list.
3379 // Signal the quit event to indicate that the thread is finished.
3382 wasSet
= SetEvent( m
->p
->quitEvent
);
3383 check_translated_errno( wasSet
, GetLastError(), kUnknownErr
);
3385 // Call _endthreadex() explicitly instead of just exiting normally to avoid memory leaks when using static run-time
3386 // libraries. See <http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/createthread.asp>.
3388 _endthreadex_compat( 0 );
3392 //===========================================================================================================================
3393 // ProcessingThreadInitialize
3394 //===========================================================================================================================
3396 mDNSlocal mStatus
ProcessingThreadInitialize( mDNS
* const inMDNS
)
3401 inMDNS
->p
->threadID
= GetCurrentThreadId();
3403 err
= IsVPCRunning( &inMDNS
->p
->inVirtualPC
);
3407 TearDownRetryVPCCheck( inMDNS
);
3408 SetupRetryVPCCheck( inMDNS
);
3411 err
= SetupInterfaceList( inMDNS
);
3412 require_noerr( err
, exit
);
3414 err
= uDNS_SetupDNSConfig( inMDNS
);
3415 require_noerr( err
, exit
);
3421 TearDownInterfaceList( inMDNS
);
3422 TearDownRetryVPCCheck( inMDNS
);
3424 inMDNS
->p
->initStatus
= err
;
3426 wasSet
= SetEvent( inMDNS
->p
->initEvent
);
3427 check_translated_errno( wasSet
, GetLastError(), kUnknownErr
);
3431 //===========================================================================================================================
3432 // ProcessingThreadSetupWaitList
3433 //===========================================================================================================================
3435 mDNSlocal mStatus
ProcessingThreadSetupWaitList( mDNS
* const inMDNS
, HANDLE
**outWaitList
, int *outWaitListCount
)
3440 HANDLE
* waitItemPtr
;
3441 mDNSInterfaceData
* ifd
;
3444 dlog( kDebugLevelTrace
, DEBUG_NAME
"thread setting up wait list\n" );
3447 check( outWaitList
);
3448 check( outWaitListCount
);
3450 // Allocate an array to hold all the objects to wait on.
3452 waitListCount
= kWaitListFixedItemCount
+ inMDNS
->p
->timersCount
+ inMDNS
->p
->interfaceCount
+ gTCPConnections
;
3453 waitList
= (HANDLE
*) malloc( waitListCount
* sizeof( *waitList
) );
3454 require_action( waitList
, exit
, err
= mStatus_NoMemoryErr
);
3455 waitItemPtr
= waitList
;
3457 // Add the fixed wait items to the beginning of the list.
3459 *waitItemPtr
++ = inMDNS
->p
->cancelEvent
;
3460 *waitItemPtr
++ = inMDNS
->p
->interfaceListChangedEvent
;
3461 *waitItemPtr
++ = inMDNS
->p
->wakeupEvent
;
3462 *waitItemPtr
++ = inMDNS
->p
->descChangedEvent
;
3463 *waitItemPtr
++ = inMDNS
->p
->tcpipChangedEvent
;
3464 *waitItemPtr
++ = inMDNS
->p
->ddnsChangedEvent
;
3468 if ( inMDNS
->p
->vpcCheckEvent
)
3470 *waitItemPtr
++ = inMDNS
->p
->vpcCheckEvent
;
3473 // Append all the dynamic wait items to the list.
3474 #if ( MDNS_WINDOWS_ENABLE_IPV4 )
3475 *waitItemPtr
++ = inMDNS
->p
->unicastSock4ReadEvent
;
3478 #if ( MDNS_WINDOWS_ENABLE_IPV6 )
3479 *waitItemPtr
++ = inMDNS
->p
->unicastSock6ReadEvent
;
3482 for( ifd
= inMDNS
->p
->interfaceList
; ifd
; ifd
= ifd
->next
)
3484 *waitItemPtr
++ = ifd
->readPendingEvent
;
3487 for ( tcd
= gTCPConnectionList
; tcd
; tcd
= tcd
->next
)
3489 *waitItemPtr
++ = tcd
->pendingEvent
;
3492 check( (int)( waitItemPtr
- waitList
) == waitListCount
);
3494 *outWaitList
= waitList
;
3495 *outWaitListCount
= waitListCount
;
3497 err
= mStatus_NoError
;
3504 dlog( kDebugLevelTrace
, DEBUG_NAME
"thread setting up wait list done (err=%d %m)\n", err
, err
);
3508 //===========================================================================================================================
3509 // ProcessingThreadProcessPacket
3510 //===========================================================================================================================
3512 mDNSlocal
void ProcessingThreadProcessPacket( mDNS
*inMDNS
, mDNSInterfaceData
*inIFD
, SocketRef inSock
)
3515 const mDNSInterfaceID iid
= inIFD
? inIFD
->interfaceInfo
.InterfaceID
: NULL
;
3516 LPFN_WSARECVMSG recvMsgPtr
;
3522 struct sockaddr_storage addr
;
3528 check( IsValidSocket( inSock
) );
3530 // Set up the default in case the packet info options are not supported or reported correctly.
3534 recvMsgPtr
= inIFD
->wsaRecvMsgFunctionPtr
;
3535 dstAddr
= inIFD
->defaultAddr
;
3536 dstPort
= MulticastDNSPort
;
3539 else if ( inSock
== inMDNS
->p
->unicastSock4
)
3541 recvMsgPtr
= inMDNS
->p
->unicastSock4RecvMsgPtr
;
3542 dstAddr
= inMDNS
->p
->unicastSock4DestAddr
;
3543 dstPort
= zeroIPPort
;
3546 else if ( inSock
== inMDNS
->p
->unicastSock6
)
3548 recvMsgPtr
= inMDNS
->p
->unicastSock6RecvMsgPtr
;
3549 dstAddr
= inMDNS
->p
->unicastSock6DestAddr
;
3550 dstPort
= zeroIPPort
;
3555 dlog( kDebugLevelError
, DEBUG_NAME
"packet received on unknown socket\n" );
3559 #if( !TARGET_OS_WINDOWS_CE )
3564 uint8_t controlBuffer
[ 128 ];
3566 LPWSACMSGHDR header
;
3568 // Set up the buffer and read the packet.
3570 msg
.name
= (LPSOCKADDR
) &addr
;
3571 msg
.namelen
= (INT
) sizeof( addr
);
3572 buf
.buf
= (char *) &packet
;
3573 buf
.len
= (u_long
) sizeof( packet
);
3574 msg
.lpBuffers
= &buf
;
3575 msg
.dwBufferCount
= 1;
3576 msg
.Control
.buf
= (char *) controlBuffer
;
3577 msg
.Control
.len
= (u_long
) sizeof( controlBuffer
);
3580 err
= recvMsgPtr( inSock
, &msg
, &size
, NULL
, NULL
);
3581 err
= translate_errno( err
== 0, (OSStatus
) GetLastError(), kUnknownErr
);
3582 require_noerr( err
, exit
);
3585 // Parse the control information. Reject packets received on the wrong interface.
3587 for( header
= WSA_CMSG_FIRSTHDR( &msg
); header
; header
= WSA_CMSG_NXTHDR( &msg
, header
) )
3589 if( ( header
->cmsg_level
== IPPROTO_IP
) && ( header
->cmsg_type
== IP_PKTINFO
) )
3591 IN_PKTINFO
* ipv4PacketInfo
;
3593 ipv4PacketInfo
= (IN_PKTINFO
*) WSA_CMSG_DATA( header
);
3597 require_action( ipv4PacketInfo
->ipi_ifindex
== inIFD
->index
, exit
, err
= kMismatchErr
);
3600 dstAddr
.type
= mDNSAddrType_IPv4
;
3601 dstAddr
.ip
.v4
.NotAnInteger
= ipv4PacketInfo
->ipi_addr
.s_addr
;
3603 else if( ( header
->cmsg_level
== IPPROTO_IPV6
) && ( header
->cmsg_type
== IPV6_PKTINFO
) )
3605 IN6_PKTINFO
* ipv6PacketInfo
;
3607 ipv6PacketInfo
= (IN6_PKTINFO
*) WSA_CMSG_DATA( header
);
3611 require_action( ipv6PacketInfo
->ipi6_ifindex
== ( inIFD
->index
- kIPv6IfIndexBase
), exit
, err
= kMismatchErr
);
3614 dstAddr
.type
= mDNSAddrType_IPv6
;
3615 dstAddr
.ip
.v6
= *( (mDNSv6Addr
*) &ipv6PacketInfo
->ipi6_addr
);
3624 addrSize
= sizeof( addr
);
3625 n
= recvfrom( inSock
, (char *) &packet
, sizeof( packet
), 0, (struct sockaddr
*) &addr
, &addrSize
);
3626 err
= translate_errno( n
> 0, errno_compat(), kUnknownErr
);
3627 require_noerr( err
, exit
);
3629 SockAddrToMDNSAddr( (struct sockaddr
*) &addr
, &srcAddr
, &srcPort
);
3631 // Dispatch the packet to mDNS.
3633 dlog( kDebugLevelChatty
, DEBUG_NAME
"packet received\n" );
3634 dlog( kDebugLevelChatty
, DEBUG_NAME
" size = %d\n", n
);
3635 dlog( kDebugLevelChatty
, DEBUG_NAME
" src = %#a:%u\n", &srcAddr
, ntohs( srcPort
.NotAnInteger
) );
3636 dlog( kDebugLevelChatty
, DEBUG_NAME
" dst = %#a:%u\n", &dstAddr
, ntohs( dstPort
.NotAnInteger
) );
3640 dlog( kDebugLevelChatty
, DEBUG_NAME
" interface = %#a (index=0x%08X)\n", &inIFD
->interfaceInfo
.ip
, (int) inIFD
->index
);
3643 dlog( kDebugLevelChatty
, DEBUG_NAME
"\n" );
3645 end
= ( (mDNSu8
*) &packet
) + n
;
3646 mDNSCoreReceive( inMDNS
, &packet
, end
, &srcAddr
, srcPort
, &dstAddr
, dstPort
, iid
);
3652 //===========================================================================================================================
3653 // ProcessingThreadInterfaceListChanged
3654 //===========================================================================================================================
3656 mDNSlocal
void ProcessingThreadInterfaceListChanged( mDNS
*inMDNS
)
3660 dlog( kDebugLevelInfo
, DEBUG_NAME
"interface list changed\n" );
3663 if (inMDNS
->p
->interfaceListChangedCallback
)
3665 inMDNS
->p
->interfaceListChangedCallback(inMDNS
);
3668 mDNSPlatformLock( inMDNS
);
3670 // Tear down the existing interfaces and set up new ones using the new IP info.
3672 err
= TearDownInterfaceList( inMDNS
);
3675 err
= SetupInterfaceList( inMDNS
);
3678 err
= uDNS_SetupDNSConfig( inMDNS
);
3681 mDNSPlatformUnlock( inMDNS
);
3683 // Inform clients of the change.
3685 if( inMDNS
->MainCallback
)
3687 inMDNS
->MainCallback( inMDNS
, mStatus_ConfigChanged
);
3690 // Force mDNS to update.
3692 mDNSCoreMachineSleep( inMDNS
, mDNSfalse
);
3696 //===========================================================================================================================
3697 // ProcessingThreadComputerDescriptionChanged
3698 //===========================================================================================================================
3699 mDNSlocal
void ProcessingThreadComputerDescriptionChanged( mDNS
*inMDNS
)
3703 dlog( kDebugLevelInfo
, DEBUG_NAME
"computer description has changed\n" );
3706 mDNSPlatformLock( inMDNS
);
3709 SetupNiceName( inMDNS
);
3711 if (inMDNS
->p
->hostDescriptionChangedCallback
)
3713 inMDNS
->p
->hostDescriptionChangedCallback(inMDNS
);
3716 // and reset the event handler
3717 if ((inMDNS
->p
->descKey
!= NULL
) && (inMDNS
->p
->descChangedEvent
))
3719 err
= RegNotifyChangeKeyValue(inMDNS
->p
->descKey
, TRUE
, REG_NOTIFY_CHANGE_LAST_SET
, inMDNS
->p
->descChangedEvent
, TRUE
);
3723 mDNSPlatformUnlock( inMDNS
);
3727 //===========================================================================================================================
3728 // ProcessingThreadTCPIPConfigChanged
3729 //===========================================================================================================================
3730 mDNSlocal
void ProcessingThreadTCPIPConfigChanged( mDNS
* inMDNS
)
3734 dlog( kDebugLevelInfo
, DEBUG_NAME
"TCP/IP config has changed\n" );
3737 mDNSPlatformLock( inMDNS
);
3739 err
= uDNS_SetupDNSConfig( inMDNS
);
3742 // and reset the event handler
3744 if ( ( inMDNS
->p
->tcpipKey
!= NULL
) && ( inMDNS
->p
->tcpipChangedEvent
) )
3746 err
= RegNotifyChangeKeyValue( inMDNS
->p
->tcpipKey
, TRUE
, REG_NOTIFY_CHANGE_NAME
|REG_NOTIFY_CHANGE_LAST_SET
, inMDNS
->p
->tcpipChangedEvent
, TRUE
);
3750 mDNSPlatformUnlock( inMDNS
);
3754 //===========================================================================================================================
3755 // ProcessingThreadDynDNSConfigChanged
3756 //===========================================================================================================================
3757 mDNSlocal
void ProcessingThreadDynDNSConfigChanged( mDNS
*inMDNS
)
3761 dlog( kDebugLevelInfo
, DEBUG_NAME
"DynDNS config has changed\n" );
3764 SetDomainSecrets( inMDNS
);
3766 mDNSPlatformLock( inMDNS
);
3768 err
= uDNS_SetupDNSConfig( inMDNS
);
3771 // and reset the event handler
3773 if ((inMDNS
->p
->ddnsKey
!= NULL
) && (inMDNS
->p
->ddnsChangedEvent
))
3775 err
= RegNotifyChangeKeyValue(inMDNS
->p
->ddnsKey
, TRUE
, REG_NOTIFY_CHANGE_NAME
|REG_NOTIFY_CHANGE_LAST_SET
, inMDNS
->p
->ddnsChangedEvent
, TRUE
);
3779 mDNSPlatformUnlock( inMDNS
);
3783 //===========================================================================================================================
3784 // ProcessingThreadRetryVPCCheck
3785 //===========================================================================================================================
3788 ProcessingThreadRetryVPCCheck( mDNS
* inMDNS
)
3790 mStatus err
= mStatus_NoError
;
3792 dlog( kDebugLevelTrace
, DEBUG_NAME
"in ProcessingThreadRetryVPCCheck\n" );
3794 TearDownRetryVPCCheck( inMDNS
);
3796 if ( inMDNS
->p
->vpcCheckCount
< kRetryVPCMax
)
3798 inMDNS
->p
->vpcCheckCount
++;
3800 err
= IsVPCRunning( &inMDNS
->p
->inVirtualPC
);
3801 require_noerr( err
, exit
);
3803 if ( inMDNS
->p
->inVirtualPC
)
3805 ProcessingThreadInterfaceListChanged( inMDNS
);
3813 SetupRetryVPCCheck( inMDNS
);
3823 #pragma mark == Utilities ==
3826 //===========================================================================================================================
3828 //===========================================================================================================================
3830 mDNSlocal
int getifaddrs( struct ifaddrs
**outAddrs
)
3834 #if( MDNS_WINDOWS_USE_IPV6_IF_ADDRS && !TARGET_OS_WINDOWS_CE )
3836 // Try to the load the GetAdaptersAddresses function from the IP Helpers DLL. This API is only available on Windows
3837 // XP or later. Looking up the symbol at runtime allows the code to still work on older systems without that API.
3839 if( !gIPHelperLibraryInstance
)
3841 gIPHelperLibraryInstance
= LoadLibrary( TEXT( "Iphlpapi" ) );
3842 if( gIPHelperLibraryInstance
)
3844 gGetAdaptersAddressesFunctionPtr
=
3845 (GetAdaptersAddressesFunctionPtr
) GetProcAddress( gIPHelperLibraryInstance
, "GetAdaptersAddresses" );
3846 if( !gGetAdaptersAddressesFunctionPtr
)
3850 ok
= FreeLibrary( gIPHelperLibraryInstance
);
3851 check_translated_errno( ok
, GetLastError(), kUnknownErr
);
3852 gIPHelperLibraryInstance
= NULL
;
3857 // Use the new IPv6-capable routine if supported. Otherwise, fall back to the old and compatible IPv4-only code.
3858 // <rdar://problem/4278934> Fall back to using getifaddrs_ipv4 if getifaddrs_ipv6 fails
3860 if( !gGetAdaptersAddressesFunctionPtr
|| ( ( err
= getifaddrs_ipv6( outAddrs
) ) != mStatus_NoError
) )
3862 err
= getifaddrs_ipv4( outAddrs
);
3863 require_noerr( err
, exit
);
3866 #elif( !TARGET_OS_WINDOWS_CE )
3868 err
= getifaddrs_ipv4( outAddrs
);
3869 require_noerr( err
, exit
);
3873 err
= getifaddrs_ce( outAddrs
);
3874 require_noerr( err
, exit
);
3882 #if( MDNS_WINDOWS_USE_IPV6_IF_ADDRS )
3883 //===========================================================================================================================
3885 //===========================================================================================================================
3887 mDNSlocal
int getifaddrs_ipv6( struct ifaddrs
**outAddrs
)
3892 struct ifaddrs
* head
;
3893 struct ifaddrs
** next
;
3894 IP_ADAPTER_ADDRESSES
* iaaList
;
3896 IP_ADAPTER_ADDRESSES
* iaa
;
3898 struct ifaddrs
* ifa
;
3900 check( gGetAdaptersAddressesFunctionPtr
);
3906 // Get the list of interfaces. The first call gets the size and the second call gets the actual data.
3907 // This loops to handle the case where the interface changes in the window after getting the size, but before the
3908 // second call completes. A limit of 100 retries is enforced to prevent infinite loops if something else is wrong.
3910 flags
= GAA_FLAG_INCLUDE_PREFIX
| GAA_FLAG_SKIP_ANYCAST
| GAA_FLAG_SKIP_MULTICAST
| GAA_FLAG_SKIP_DNS_SERVER
| GAA_FLAG_SKIP_FRIENDLY_NAME
;
3915 err
= gGetAdaptersAddressesFunctionPtr( AF_UNSPEC
, flags
, NULL
, NULL
, &iaaListSize
);
3916 check( err
== ERROR_BUFFER_OVERFLOW
);
3917 check( iaaListSize
>= sizeof( IP_ADAPTER_ADDRESSES
) );
3919 iaaList
= (IP_ADAPTER_ADDRESSES
*) malloc( iaaListSize
);
3920 require_action( iaaList
, exit
, err
= ERROR_NOT_ENOUGH_MEMORY
);
3922 err
= gGetAdaptersAddressesFunctionPtr( AF_UNSPEC
, flags
, NULL
, iaaList
, &iaaListSize
);
3923 if( err
== ERROR_SUCCESS
) break;
3928 require( i
< 100, exit
);
3929 dlog( kDebugLevelWarning
, "%s: retrying GetAdaptersAddresses after %d failure(s) (%d %m)\n", __ROUTINE__
, i
, err
, err
);
3932 for( iaa
= iaaList
; iaa
; iaa
= iaa
->Next
)
3935 IP_ADAPTER_UNICAST_ADDRESS
* addr
;
3937 IP_ADAPTER_PREFIX
* firstPrefix
;
3939 if( iaa
->IfIndex
> 0xFFFFFF )
3941 dlog( kDebugLevelAlert
, DEBUG_NAME
"%s: IPv4 ifindex out-of-range (0x%08X)\n", __ROUTINE__
, iaa
->IfIndex
);
3943 if( iaa
->Ipv6IfIndex
> 0xFF )
3945 dlog( kDebugLevelAlert
, DEBUG_NAME
"%s: IPv6 ifindex out-of-range (0x%08X)\n", __ROUTINE__
, iaa
->Ipv6IfIndex
);
3948 // For IPv4 interfaces, there seems to be a bug in iphlpapi.dll that causes the
3949 // following code to crash when iterating through the prefix list. This seems
3950 // to occur when iaa->Ipv6IfIndex != 0 when IPv6 is not installed on the host.
3951 // This shouldn't happen according to Microsoft docs which states:
3953 // "Ipv6IfIndex contains 0 if IPv6 is not available on the interface."
3955 // So the data structure seems to be corrupted when we return from
3956 // GetAdaptersAddresses(). The bug seems to occur when iaa->Length <
3957 // sizeof(IP_ADAPTER_ADDRESSES), so when that happens, we'll manually
3958 // modify iaa to have the correct values.
3960 if ( iaa
->Length
>= sizeof( IP_ADAPTER_ADDRESSES
) )
3962 ipv6IfIndex
= iaa
->Ipv6IfIndex
;
3963 firstPrefix
= iaa
->FirstPrefix
;
3971 // Skip psuedo and tunnel interfaces.
3973 if( ( ipv6IfIndex
== 1 ) || ( iaa
->IfType
== IF_TYPE_TUNNEL
) )
3978 // Add each address as a separate interface to emulate the way getifaddrs works.
3980 for( addrIndex
= 0, addr
= iaa
->FirstUnicastAddress
; addr
; ++addrIndex
, addr
= addr
->Next
)
3984 IP_ADAPTER_PREFIX
* prefix
;
3987 family
= addr
->Address
.lpSockaddr
->sa_family
;
3988 if( ( family
!= AF_INET
) && ( family
!= AF_INET6
) ) continue;
3990 ifa
= (struct ifaddrs
*) calloc( 1, sizeof( struct ifaddrs
) );
3991 require_action( ifa
, exit
, err
= WSAENOBUFS
);
3994 next
= &ifa
->ifa_next
;
3998 size
= strlen( iaa
->AdapterName
) + 1;
3999 ifa
->ifa_name
= (char *) malloc( size
);
4000 require_action( ifa
->ifa_name
, exit
, err
= WSAENOBUFS
);
4001 memcpy( ifa
->ifa_name
, iaa
->AdapterName
, size
);
4003 // Get interface flags.
4006 if( iaa
->OperStatus
== IfOperStatusUp
) ifa
->ifa_flags
|= IFF_UP
;
4007 if( iaa
->IfType
== IF_TYPE_SOFTWARE_LOOPBACK
) ifa
->ifa_flags
|= IFF_LOOPBACK
;
4008 else if ( IsPointToPoint( addr
) ) ifa
->ifa_flags
|= IFF_POINTTOPOINT
;
4009 if( !( iaa
->Flags
& IP_ADAPTER_NO_MULTICAST
) ) ifa
->ifa_flags
|= IFF_MULTICAST
;
4012 // <rdar://problem/4045657> Interface index being returned is 512
4014 // Windows does not have a uniform scheme for IPv4 and IPv6 interface indexes.
4015 // This code used to shift the IPv4 index up to ensure uniqueness between
4016 // it and IPv6 indexes. Although this worked, it was somewhat confusing to developers, who
4017 // then see interface indexes passed back that don't correspond to anything
4018 // that is seen in Win32 APIs or command line tools like "route". As a relatively
4019 // small percentage of developers are actively using IPv6, it seems to
4020 // make sense to make our use of IPv4 as confusion free as possible.
4021 // So now, IPv6 interface indexes will be shifted up by a
4022 // constant value which will serve to uniquely identify them, and we will
4023 // leave IPv4 interface indexes unmodified.
4027 case AF_INET
: ifa
->ifa_extra
.index
= iaa
->IfIndex
; break;
4028 case AF_INET6
: ifa
->ifa_extra
.index
= ipv6IfIndex
+ kIPv6IfIndexBase
; break;
4038 ifa
->ifa_addr
= (struct sockaddr
*) calloc( 1, (size_t) addr
->Address
.iSockaddrLength
);
4039 require_action( ifa
->ifa_addr
, exit
, err
= WSAENOBUFS
);
4040 memcpy( ifa
->ifa_addr
, addr
->Address
.lpSockaddr
, (size_t) addr
->Address
.iSockaddrLength
);
4046 check( ifa
->ifa_addr
);
4048 // Get subnet mask (IPv4)/link prefix (IPv6). It is specified as a bit length (e.g. 24 for 255.255.255.0).
4051 for( prefixIndex
= 0, prefix
= firstPrefix
; prefix
; ++prefixIndex
, prefix
= prefix
->Next
)
4053 if( prefixIndex
== addrIndex
)
4055 check_string( prefix
->Address
.lpSockaddr
->sa_family
== family
, "addr family != netmask family" );
4056 prefixLength
= prefix
->PrefixLength
;
4064 struct sockaddr_in
* sa4
;
4066 require_action( prefixLength
<= 32, exit
, err
= ERROR_INVALID_DATA
);
4068 sa4
= (struct sockaddr_in
*) calloc( 1, sizeof( *sa4
) );
4069 require_action( sa4
, exit
, err
= WSAENOBUFS
);
4071 sa4
->sin_family
= AF_INET
;
4073 if ( prefixLength
!= 0 )
4075 sa4
->sin_addr
.s_addr
= htonl( 0xFFFFFFFFU
<< ( 32 - prefixLength
) );
4081 dlog( kDebugLevelWarning
, DEBUG_NAME
"%s: IPv4 prefixLength is 0\n", __ROUTINE__
);
4082 err
= AddressToIndexAndMask( ifa
->ifa_addr
, &index
, (struct sockaddr
*) sa4
);
4083 require_noerr( err
, exit
);
4086 dlog( kDebugLevelInfo
, DEBUG_NAME
"%s: IPv4 mask = %s\n", __ROUTINE__
, inet_ntoa( sa4
->sin_addr
) );
4087 ifa
->ifa_netmask
= (struct sockaddr
*) sa4
;
4093 struct sockaddr_in6
* sa6
;
4098 require_action( prefixLength
<= 128, exit
, err
= ERROR_INVALID_DATA
);
4100 sa6
= (struct sockaddr_in6
*) calloc( 1, sizeof( *sa6
) );
4101 require_action( sa6
, exit
, err
= WSAENOBUFS
);
4102 sa6
->sin6_family
= AF_INET6
;
4104 if( prefixLength
== 0 )
4106 dlog( kDebugLevelWarning
, DEBUG_NAME
"%s: IPv6 link prefix 0, defaulting to /128\n", __ROUTINE__
);
4110 for( len
= (int) prefixLength
; len
> 0; len
-= 8 )
4112 if( len
>= 8 ) maskByte
= 0xFF;
4113 else maskByte
= (uint8_t)( ( 0xFFU
<< ( 8 - len
) ) & 0xFFU
);
4114 sa6
->sin6_addr
.s6_addr
[ maskIndex
++ ] = maskByte
;
4116 ifa
->ifa_netmask
= (struct sockaddr
*) sa6
;
4133 err
= ERROR_SUCCESS
;
4138 freeifaddrs( head
);
4144 return( (int) err
);
4147 #endif // MDNS_WINDOWS_USE_IPV6_IF_ADDRS
4149 #if( !TARGET_OS_WINDOWS_CE )
4150 //===========================================================================================================================
4152 //===========================================================================================================================
4154 mDNSlocal
int getifaddrs_ipv4( struct ifaddrs
**outAddrs
)
4160 INTERFACE_INFO
* buffer
;
4161 INTERFACE_INFO
* tempBuffer
;
4162 INTERFACE_INFO
* ifInfo
;
4165 struct ifaddrs
* head
;
4166 struct ifaddrs
** next
;
4167 struct ifaddrs
* ifa
;
4169 sock
= INVALID_SOCKET
;
4174 // Get the interface list. WSAIoctl is called with SIO_GET_INTERFACE_LIST, but since this does not provide a
4175 // way to determine the size of the interface list beforehand, we have to start with an initial size guess and
4176 // call WSAIoctl repeatedly with increasing buffer sizes until it succeeds. Limit this to 100 tries for safety.
4178 sock
= socket( AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
4179 err
= translate_errno( IsValidSocket( sock
), errno_compat(), kUnknownErr
);
4180 require_noerr( err
, exit
);
4183 size
= 16 * sizeof( INTERFACE_INFO
);
4186 tempBuffer
= (INTERFACE_INFO
*) realloc( buffer
, size
);
4187 require_action( tempBuffer
, exit
, err
= WSAENOBUFS
);
4188 buffer
= tempBuffer
;
4190 err
= WSAIoctl( sock
, SIO_GET_INTERFACE_LIST
, NULL
, 0, buffer
, size
, &actualSize
, NULL
, NULL
);
4197 require_action( n
< 100, exit
, err
= WSAEADDRNOTAVAIL
);
4199 size
+= ( 16 * sizeof( INTERFACE_INFO
) );
4201 check( actualSize
<= size
);
4202 check( ( actualSize
% sizeof( INTERFACE_INFO
) ) == 0 );
4203 n
= (int)( actualSize
/ sizeof( INTERFACE_INFO
) );
4205 // Process the raw interface list and build a linked list of IPv4 interfaces.
4207 for( i
= 0; i
< n
; ++i
)
4209 ifInfo
= &buffer
[ i
];
4210 if( ifInfo
->iiAddress
.Address
.sa_family
!= AF_INET
)
4215 ifa
= (struct ifaddrs
*) calloc( 1, sizeof( struct ifaddrs
) );
4216 require_action( ifa
, exit
, err
= WSAENOBUFS
);
4219 next
= &ifa
->ifa_next
;
4223 ifa
->ifa_name
= (char *) malloc( 16 );
4224 require_action( ifa
->ifa_name
, exit
, err
= WSAENOBUFS
);
4225 sprintf( ifa
->ifa_name
, "%d", i
+ 1 );
4227 // Get interface flags.
4229 ifa
->ifa_flags
= (u_int
) ifInfo
->iiFlags
;
4233 if ( ifInfo
->iiAddress
.Address
.sa_family
== AF_INET
)
4235 struct sockaddr_in
* sa4
;
4237 sa4
= &ifInfo
->iiAddress
.AddressIn
;
4238 ifa
->ifa_addr
= (struct sockaddr
*) calloc( 1, sizeof( *sa4
) );
4239 require_action( ifa
->ifa_addr
, exit
, err
= WSAENOBUFS
);
4240 memcpy( ifa
->ifa_addr
, sa4
, sizeof( *sa4
) );
4242 ifa
->ifa_netmask
= (struct sockaddr
*) calloc(1, sizeof( *sa4
) );
4244 // <rdar://problem/4076478> Service won't start on Win2K. The address
4245 // family field was not being initialized.
4247 ifa
->ifa_netmask
->sa_family
= AF_INET
;
4248 require_action( ifa
->ifa_netmask
, exit
, err
= WSAENOBUFS
);
4249 err
= AddressToIndexAndMask( ifa
->ifa_addr
, &ifa
->ifa_extra
.index
, ifa
->ifa_netmask
);
4250 require_noerr( err
, exit
);
4254 // Emulate an interface index.
4256 ifa
->ifa_extra
.index
= (uint32_t)( i
+ 1 );
4272 freeifaddrs( head
);
4278 if( sock
!= INVALID_SOCKET
)
4280 closesocket( sock
);
4284 #endif // !TARGET_OS_WINDOWS_CE )
4286 #if( TARGET_OS_WINDOWS_CE )
4287 //===========================================================================================================================
4289 //===========================================================================================================================
4291 mDNSlocal
int getifaddrs_ce( struct ifaddrs
**outAddrs
)
4297 SOCKET_ADDRESS_LIST
* addressList
;
4298 struct ifaddrs
* head
;
4299 struct ifaddrs
** next
;
4300 struct ifaddrs
* ifa
;
4304 sock
= kInvalidSocketRef
;
4309 // Open a temporary socket because one is needed to use WSAIoctl (we'll close it before exiting this function).
4311 sock
= socket( AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
4312 err
= translate_errno( IsValidSocket( sock
), errno_compat(), kUnknownErr
);
4313 require_noerr( err
, exit
);
4315 // Call WSAIoctl with SIO_ADDRESS_LIST_QUERY and pass a null buffer. This call will fail, but the size needed to
4316 // for the request will be filled in. Once we know the size, allocate a buffer to hold the entire list.
4318 // NOTE: Due to a bug in Windows CE, the size returned by WSAIoctl is not enough so double it as a workaround.
4321 WSAIoctl( sock
, SIO_ADDRESS_LIST_QUERY
, NULL
, 0, NULL
, 0, &size
, NULL
, NULL
);
4322 require_action( size
> 0, exit
, err
= -1 );
4325 buffer
= calloc( 1, size
);
4326 require_action( buffer
, exit
, err
= -1 );
4328 // We now know the size of the list and have a buffer to hold so call WSAIoctl again to get it.
4330 err
= WSAIoctl( sock
, SIO_ADDRESS_LIST_QUERY
, NULL
, 0, buffer
, size
, &size
, NULL
, NULL
);
4331 require_noerr( err
, exit
);
4332 addressList
= (SOCKET_ADDRESS_LIST
*) buffer
;
4334 // Process the raw interface list and build a linked list of interfaces.
4336 // NOTE: Due to a bug in Windows CE, the iAddressCount field is always 0 so use 1 in that case.
4338 n
= addressList
->iAddressCount
;
4343 for( i
= 0; i
< n
; ++i
)
4345 ifa
= (struct ifaddrs
*) calloc( 1, sizeof( struct ifaddrs
) );
4346 require_action( ifa
, exit
, err
= WSAENOBUFS
);
4349 next
= &ifa
->ifa_next
;
4353 ifa
->ifa_name
= (char *) malloc( 16 );
4354 require_action( ifa
->ifa_name
, exit
, err
= WSAENOBUFS
);
4355 sprintf( ifa
->ifa_name
, "%d", i
+ 1 );
4357 // Get flags. Note: SIO_ADDRESS_LIST_QUERY does not report flags so just fake IFF_UP and IFF_MULTICAST.
4359 ifa
->ifa_flags
= IFF_UP
| IFF_MULTICAST
;
4363 switch( addressList
->Address
[ i
].lpSockaddr
->sa_family
)
4367 struct sockaddr_in
* sa4
;
4369 sa4
= (struct sockaddr_in
*) addressList
->Address
[ i
].lpSockaddr
;
4370 ifa
->ifa_addr
= (struct sockaddr
*) calloc( 1, sizeof( *sa4
) );
4371 require_action( ifa
->ifa_addr
, exit
, err
= WSAENOBUFS
);
4372 memcpy( ifa
->ifa_addr
, sa4
, sizeof( *sa4
) );
4393 freeifaddrs( head
);
4399 if( sock
!= INVALID_SOCKET
)
4401 closesocket( sock
);
4405 #endif // TARGET_OS_WINDOWS_CE )
4407 //===========================================================================================================================
4409 //===========================================================================================================================
4411 mDNSlocal
void freeifaddrs( struct ifaddrs
*inIFAs
)
4416 // Free each piece of the structure. Set to null after freeing to handle macro-aliased fields.
4418 for( p
= inIFAs
; p
; p
= q
)
4424 free( p
->ifa_name
);
4429 free( p
->ifa_addr
);
4432 if( p
->ifa_netmask
)
4434 free( p
->ifa_netmask
);
4435 p
->ifa_netmask
= NULL
;
4437 if( p
->ifa_broadaddr
)
4439 free( p
->ifa_broadaddr
);
4440 p
->ifa_broadaddr
= NULL
;
4442 if( p
->ifa_dstaddr
)
4444 free( p
->ifa_dstaddr
);
4445 p
->ifa_dstaddr
= NULL
;
4449 free( p
->ifa_data
);
4457 //===========================================================================================================================
4458 // GetPrimaryInterface
4459 //===========================================================================================================================
4462 GetPrimaryInterface()
4464 PMIB_IPFORWARDTABLE pIpForwardTable
= NULL
;
4466 BOOL bOrder
= FALSE
;
4470 unsigned long int i
;
4472 // Find out how big our buffer needs to be.
4474 err
= GetIpForwardTable(NULL
, &dwSize
, bOrder
);
4475 require_action( err
== ERROR_INSUFFICIENT_BUFFER
, exit
, err
= kUnknownErr
);
4477 // Allocate the memory for the table
4479 pIpForwardTable
= (PMIB_IPFORWARDTABLE
) malloc( dwSize
);
4480 require_action( pIpForwardTable
, exit
, err
= kNoMemoryErr
);
4482 // Now get the table.
4484 err
= GetIpForwardTable(pIpForwardTable
, &dwSize
, bOrder
);
4485 require_noerr( err
, exit
);
4488 // Search for the row in the table we want.
4490 for ( i
= 0; i
< pIpForwardTable
->dwNumEntries
; i
++)
4492 // Look for a default route
4494 if ( pIpForwardTable
->table
[i
].dwForwardDest
== 0 )
4496 if ( index
&& ( pIpForwardTable
->table
[i
].dwForwardMetric1
>= metric
) )
4501 index
= pIpForwardTable
->table
[i
].dwForwardIfIndex
;
4502 metric
= pIpForwardTable
->table
[i
].dwForwardMetric1
;
4508 if ( pIpForwardTable
!= NULL
)
4510 free( pIpForwardTable
);
4517 //===========================================================================================================================
4518 // AddressToIndexAndMask
4519 //===========================================================================================================================
4522 AddressToIndexAndMask( struct sockaddr
* addr
, uint32_t * ifIndex
, struct sockaddr
* mask
)
4524 // Before calling AddIPAddress we use GetIpAddrTable to get
4525 // an adapter to which we can add the IP.
4527 PMIB_IPADDRTABLE pIPAddrTable
= NULL
;
4529 mStatus err
= mStatus_UnknownErr
;
4532 // For now, this is only for IPv4 addresses. That is why we can safely cast
4533 // addr's to sockaddr_in.
4535 require_action( addr
->sa_family
== AF_INET
, exit
, err
= mStatus_UnknownErr
);
4537 // Make an initial call to GetIpAddrTable to get the
4538 // necessary size into the dwSize variable
4540 for ( i
= 0; i
< 100; i
++ )
4542 err
= GetIpAddrTable( pIPAddrTable
, &dwSize
, 0 );
4544 if ( err
!= ERROR_INSUFFICIENT_BUFFER
)
4549 pIPAddrTable
= (MIB_IPADDRTABLE
*) realloc( pIPAddrTable
, dwSize
);
4550 require_action( pIPAddrTable
, exit
, err
= WSAENOBUFS
);
4553 require_noerr( err
, exit
);
4555 for ( i
= 0; i
< pIPAddrTable
->dwNumEntries
; i
++ )
4557 if ( ( ( struct sockaddr_in
* ) addr
)->sin_addr
.s_addr
== pIPAddrTable
->table
[i
].dwAddr
)
4559 *ifIndex
= pIPAddrTable
->table
[i
].dwIndex
;
4560 ( ( struct sockaddr_in
*) mask
)->sin_addr
.s_addr
= pIPAddrTable
->table
[i
].dwMask
;
4561 err
= mStatus_NoError
;
4570 free( pIPAddrTable
);
4577 //===========================================================================================================================
4578 // CanReceiveUnicast
4579 //===========================================================================================================================
4581 mDNSlocal mDNSBool
CanReceiveUnicast( void )
4585 struct sockaddr_in addr
;
4587 // Try to bind to the port without the SO_REUSEADDR option to test if someone else has already bound to it.
4589 sock
= socket( AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
4590 check_translated_errno( IsValidSocket( sock
), errno_compat(), kUnknownErr
);
4591 ok
= IsValidSocket( sock
);
4594 memset( &addr
, 0, sizeof( addr
) );
4595 addr
.sin_family
= AF_INET
;
4596 addr
.sin_port
= MulticastDNSPort
.NotAnInteger
;
4597 addr
.sin_addr
.s_addr
= htonl( INADDR_ANY
);
4599 ok
= ( bind( sock
, (struct sockaddr
*) &addr
, sizeof( addr
) ) == 0 );
4600 close_compat( sock
);
4603 dlog( kDebugLevelInfo
, DEBUG_NAME
"Unicast UDP responses %s\n", ok
? "okay" : "*not allowed*" );
4608 //===========================================================================================================================
4610 //===========================================================================================================================
4612 mDNSlocal mDNSBool
IsPointToPoint( IP_ADAPTER_UNICAST_ADDRESS
* addr
)
4614 struct ifaddrs
* addrs
= NULL
;
4615 struct ifaddrs
* p
= NULL
;
4617 mDNSBool ret
= mDNSfalse
;
4619 // For now, only works for IPv4 interfaces
4621 if ( addr
->Address
.lpSockaddr
->sa_family
== AF_INET
)
4623 // The getifaddrs_ipv4 call will give us correct information regarding IFF_POINTTOPOINT flags.
4625 err
= getifaddrs_ipv4( &addrs
);
4626 require_noerr( err
, exit
);
4628 for ( p
= addrs
; p
; p
= p
->ifa_next
)
4630 if ( ( addr
->Address
.lpSockaddr
->sa_family
== p
->ifa_addr
->sa_family
) &&
4631 ( ( ( struct sockaddr_in
* ) addr
->Address
.lpSockaddr
)->sin_addr
.s_addr
== ( ( struct sockaddr_in
* ) p
->ifa_addr
)->sin_addr
.s_addr
) )
4633 ret
= ( p
->ifa_flags
& IFF_POINTTOPOINT
) ? mDNStrue
: mDNSfalse
;
4643 freeifaddrs( addrs
);
4650 //===========================================================================================================================
4651 // GetWindowsVersionString
4652 //===========================================================================================================================
4654 mDNSlocal OSStatus
GetWindowsVersionString( char *inBuffer
, size_t inBufferSize
)
4656 #if( !defined( VER_PLATFORM_WIN32_CE ) )
4657 #define VER_PLATFORM_WIN32_CE 3
4661 OSVERSIONINFO osInfo
;
4663 const char * versionString
;
4669 versionString
= "unknown Windows version";
4671 osInfo
.dwOSVersionInfoSize
= sizeof( OSVERSIONINFO
);
4672 ok
= GetVersionEx( &osInfo
);
4673 err
= translate_errno( ok
, (OSStatus
) GetLastError(), kUnknownErr
);
4674 require_noerr( err
, exit
);
4676 platformID
= osInfo
.dwPlatformId
;
4677 majorVersion
= osInfo
.dwMajorVersion
;
4678 minorVersion
= osInfo
.dwMinorVersion
;
4679 buildNumber
= osInfo
.dwBuildNumber
& 0xFFFF;
4681 if( ( platformID
== VER_PLATFORM_WIN32_WINDOWS
) && ( majorVersion
== 4 ) )
4683 if( ( minorVersion
< 10 ) && ( buildNumber
== 950 ) )
4685 versionString
= "Windows 95";
4687 else if( ( minorVersion
< 10 ) && ( ( buildNumber
> 950 ) && ( buildNumber
<= 1080 ) ) )
4689 versionString
= "Windows 95 SP1";
4691 else if( ( minorVersion
< 10 ) && ( buildNumber
> 1080 ) )
4693 versionString
= "Windows 95 OSR2";
4695 else if( ( minorVersion
== 10 ) && ( buildNumber
== 1998 ) )
4697 versionString
= "Windows 98";
4699 else if( ( minorVersion
== 10 ) && ( ( buildNumber
> 1998 ) && ( buildNumber
< 2183 ) ) )
4701 versionString
= "Windows 98 SP1";
4703 else if( ( minorVersion
== 10 ) && ( buildNumber
>= 2183 ) )
4705 versionString
= "Windows 98 SE";
4707 else if( minorVersion
== 90 )
4709 versionString
= "Windows ME";
4712 else if( platformID
== VER_PLATFORM_WIN32_NT
)
4714 if( ( majorVersion
== 3 ) && ( minorVersion
== 51 ) )
4716 versionString
= "Windows NT 3.51";
4718 else if( ( majorVersion
== 4 ) && ( minorVersion
== 0 ) )
4720 versionString
= "Windows NT 4";
4722 else if( ( majorVersion
== 5 ) && ( minorVersion
== 0 ) )
4724 versionString
= "Windows 2000";
4726 else if( ( majorVersion
== 5 ) && ( minorVersion
== 1 ) )
4728 versionString
= "Windows XP";
4730 else if( ( majorVersion
== 5 ) && ( minorVersion
== 2 ) )
4732 versionString
= "Windows Server 2003";
4735 else if( platformID
== VER_PLATFORM_WIN32_CE
)
4737 versionString
= "Windows CE";
4741 if( inBuffer
&& ( inBufferSize
> 0 ) )
4744 strncpy( inBuffer
, versionString
, inBufferSize
);
4745 inBuffer
[ inBufferSize
] = '\0';
4751 //===========================================================================================================================
4753 //===========================================================================================================================
4756 RegQueryString( HKEY key
, LPCSTR valueName
, LPSTR
* string
, DWORD
* stringLen
, DWORD
* enabled
)
4762 *stringLen
= MAX_ESCAPED_DOMAIN_NAME
;
4773 *string
= (char*) malloc( *stringLen
);
4774 require_action( *string
, exit
, err
= mStatus_NoMemoryErr
);
4776 err
= RegQueryValueExA( key
, valueName
, 0, &type
, (LPBYTE
) *string
, stringLen
);
4780 while ( ( err
== ERROR_MORE_DATA
) && ( i
< 100 ) );
4782 require_noerr_quiet( err
, exit
);
4786 DWORD dwSize
= sizeof( DWORD
);
4788 err
= RegQueryValueEx( key
, TEXT("Enabled"), NULL
, NULL
, (LPBYTE
) enabled
, &dwSize
);
4800 //===========================================================================================================================
4802 //===========================================================================================================================
4804 mDNSlocal mStatus
StringToAddress( mDNSAddr
* ip
, LPSTR string
)
4806 struct sockaddr_in6 sa6
;
4807 struct sockaddr_in sa4
;
4811 sa6
.sin6_family
= AF_INET6
;
4812 dwSize
= sizeof( sa6
);
4814 err
= WSAStringToAddressA( string
, AF_INET6
, NULL
, (struct sockaddr
*) &sa6
, &dwSize
);
4816 if ( err
== mStatus_NoError
)
4818 err
= SetupAddr( ip
, (struct sockaddr
*) &sa6
);
4819 require_noerr( err
, exit
);
4823 sa4
.sin_family
= AF_INET
;
4824 dwSize
= sizeof( sa4
);
4826 err
= WSAStringToAddressA( string
, AF_INET
, NULL
, (struct sockaddr
*) &sa4
, &dwSize
);
4827 err
= translate_errno( err
== 0, WSAGetLastError(), kUnknownErr
);
4828 require_noerr( err
, exit
);
4830 err
= SetupAddr( ip
, (struct sockaddr
*) &sa4
);
4831 require_noerr( err
, exit
);
4840 //===========================================================================================================================
4842 //===========================================================================================================================
4844 mDNSlocal
struct ifaddrs
*
4845 myGetIfAddrs(int refresh
)
4847 static struct ifaddrs
*ifa
= NULL
;
4864 //===========================================================================================================================
4866 //===========================================================================================================================
4869 TCHARtoUTF8( const TCHAR
*inString
, char *inBuffer
, size_t inBufferSize
)
4871 #if( defined( UNICODE ) || defined( _UNICODE ) )
4875 len
= WideCharToMultiByte( CP_UTF8
, 0, inString
, -1, inBuffer
, (int) inBufferSize
, NULL
, NULL
);
4876 err
= translate_errno( len
> 0, errno_compat(), kUnknownErr
);
4877 require_noerr( err
, exit
);
4882 return( WindowsLatin1toUTF8( inString
, inBuffer
, inBufferSize
) );
4887 //===========================================================================================================================
4888 // WindowsLatin1toUTF8
4889 //===========================================================================================================================
4892 WindowsLatin1toUTF8( const char *inString
, char *inBuffer
, size_t inBufferSize
)
4900 // Windows doesn't support going directly from Latin-1 to UTF-8 so we have to go from Latin-1 to UTF-16 first.
4902 len
= MultiByteToWideChar( CP_ACP
, 0, inString
, -1, NULL
, 0 );
4903 err
= translate_errno( len
> 0, errno_compat(), kUnknownErr
);
4904 require_noerr( err
, exit
);
4906 utf16
= (WCHAR
*) malloc( len
* sizeof( *utf16
) );
4907 require_action( utf16
, exit
, err
= kNoMemoryErr
);
4909 len
= MultiByteToWideChar( CP_ACP
, 0, inString
, -1, utf16
, len
);
4910 err
= translate_errno( len
> 0, errno_compat(), kUnknownErr
);
4911 require_noerr( err
, exit
);
4913 // Now convert the temporary UTF-16 to UTF-8.
4915 len
= WideCharToMultiByte( CP_UTF8
, 0, utf16
, -1, inBuffer
, (int) inBufferSize
, NULL
, NULL
);
4916 err
= translate_errno( len
> 0, errno_compat(), kUnknownErr
);
4917 require_noerr( err
, exit
);
4920 if( utf16
) free( utf16
);
4925 //===========================================================================================================================
4926 // ConvertUTF8ToLsaString
4927 //===========================================================================================================================
4930 MakeLsaStringFromUTF8String( PLSA_UNICODE_STRING output
, const char * input
)
4938 output
->Buffer
= NULL
;
4940 size
= MultiByteToWideChar( CP_UTF8
, 0, input
, -1, NULL
, 0 );
4941 err
= translate_errno( size
> 0, GetLastError(), kUnknownErr
);
4942 require_noerr( err
, exit
);
4944 output
->Length
= (USHORT
)( size
* sizeof( wchar_t ) );
4945 output
->Buffer
= (PWCHAR
) malloc( output
->Length
);
4946 require_action( output
->Buffer
, exit
, err
= mStatus_NoMemoryErr
);
4947 size
= MultiByteToWideChar( CP_UTF8
, 0, input
, -1, output
->Buffer
, size
);
4948 err
= translate_errno( size
> 0, GetLastError(), kUnknownErr
);
4949 require_noerr( err
, exit
);
4951 // We're going to subtrace one wchar_t from the size, because we didn't
4952 // include it when we encoded the string
4954 output
->MaximumLength
= output
->Length
;
4955 output
->Length
-= sizeof( wchar_t );
4959 if ( err
&& output
->Buffer
)
4961 free( output
->Buffer
);
4962 output
->Buffer
= NULL
;
4969 //===========================================================================================================================
4970 // ConvertLsaStringToUTF8
4971 //===========================================================================================================================
4974 MakeUTF8StringFromLsaString( char * output
, size_t len
, PLSA_UNICODE_STRING input
)
4977 OSStatus err
= kNoErr
;
4979 // The Length field of this structure holds the number of bytes,
4980 // but WideCharToMultiByte expects the number of wchar_t's. So
4981 // we divide by sizeof(wchar_t) to get the correct number.
4983 size
= (size_t) WideCharToMultiByte(CP_UTF8
, 0, input
->Buffer
, ( input
->Length
/ sizeof( wchar_t ) ), NULL
, 0, NULL
, NULL
);
4984 err
= translate_errno( size
!= 0, GetLastError(), kUnknownErr
);
4985 require_noerr( err
, exit
);
4987 // Ensure that we have enough space (Add one for trailing '\0')
4989 require_action( ( size
+ 1 ) <= len
, exit
, err
= mStatus_NoMemoryErr
);
4991 // Convert the string
4993 size
= (size_t) WideCharToMultiByte( CP_UTF8
, 0, input
->Buffer
, ( input
->Length
/ sizeof( wchar_t ) ), output
, (int) size
, NULL
, NULL
);
4994 err
= translate_errno( size
!= 0, GetLastError(), kUnknownErr
);
4995 require_noerr( err
, exit
);
4997 // have to add the trailing 0 because WideCharToMultiByte doesn't do it,
4998 // although it does return the correct size
5000 output
[size
] = '\0';
5008 //===========================================================================================================================
5009 // FreeTCPConnectionData
5010 //===========================================================================================================================
5013 FreeTCPSocket( TCPSocket
*sock
)
5017 if ( sock
->pendingEvent
)
5019 CloseHandle( sock
->pendingEvent
);
5022 if ( sock
->fd
!= INVALID_SOCKET
)
5024 closesocket( sock
->fd
);
5030 //===========================================================================================================================
5032 //===========================================================================================================================
5034 mDNSlocal mStatus
SetupAddr(mDNSAddr
*ip
, const struct sockaddr
*const sa
)
5036 if (!sa
) { LogMsg("SetupAddr ERROR: NULL sockaddr"); return(mStatus_Invalid
); }
5038 if (sa
->sa_family
== AF_INET
)
5040 struct sockaddr_in
*ifa_addr
= (struct sockaddr_in
*)sa
;
5041 ip
->type
= mDNSAddrType_IPv4
;
5042 ip
->ip
.v4
.NotAnInteger
= ifa_addr
->sin_addr
.s_addr
;
5043 return(mStatus_NoError
);
5046 if (sa
->sa_family
== AF_INET6
)
5048 struct sockaddr_in6
*ifa_addr
= (struct sockaddr_in6
*)sa
;
5049 ip
->type
= mDNSAddrType_IPv6
;
5050 if (IN6_IS_ADDR_LINKLOCAL(&ifa_addr
->sin6_addr
)) ifa_addr
->sin6_addr
.u
.Word
[1] = 0;
5051 ip
->ip
.v6
= *(mDNSv6Addr
*)&ifa_addr
->sin6_addr
;
5052 return(mStatus_NoError
);
5055 LogMsg("SetupAddr invalid sa_family %d", sa
->sa_family
);
5056 return(mStatus_Invalid
);