1 /****************************************************************************
2 *																			*
3 *						cryptlib TCP/IP Interface Header					*
4 *						Copyright Peter Gutmann 1998-2015					*
5 *																			*
6 ****************************************************************************/
7 
8 #ifdef USE_TCP
9 
10 /****************************************************************************
11 *																			*
12 *						 				AMX									*
13 *																			*
14 ****************************************************************************/
15 
16 #ifdef __AMX__
17 
18 #include <kn_sock.h>
19 
20 /* All KwikNet functions have kn_ prefix, to use the standard sockets API
21    names we have to redefine them to the usual names */
22 
23 #define accept				kn_accept
24 #define bind				kn_bind
25 #define closesocket			kn_close
26 #define connect				kn_connect
27 #define getsockopt			kn_getsockopt
28 #define listen				kn_listen
29 #define recv				kn_recv
30 #define select				kn_select
31 #define send				kn_send
32 #define setsockopt			kn_setsockopt
33 #define shutdown			kn_shutdown
34 #define socket				kn_socket
35 
36 #endif /* AMX */
37 
38 /****************************************************************************
39 *																			*
40 *						 				BeOS								*
41 *																			*
42 ****************************************************************************/
43 
44 /* If we're building under BeOS the system may have the new(er) BONE (BeOs
45    Network Environment) network stack.  This didn't quite make it into BeOS
46    v5 before the demise of Be Inc but was leaked after Be folded, as was the
47    experimental/developmental Dano release of BeOS, which would have become
48    BeOS 5.1 and also has a newer network stack.  In order to detect this we
49    have to pull in sys/socket.h before we try anything else */
50 
51 #ifdef __BEOS__
52   #include <sys/socket.h>
53 #endif /* __BEOS__ */
54 
55 /* If we're using the original (rather minimal) BeOS TCP/IP stack, we have
56    to provide a customised interface for it rather than using the same one
57    as the generic Unix/BSD interface */
58 
59 #if defined( __BEOS__ ) && !defined( BONE_VERSION )
60 
61 #include <errno.h>
62 #include <fcntl.h>
63 #include <netdb.h>
64 #include <socket.h>
65 
66 /* BeOS doesn't define any of the PF_xxx's, howewever it does defines
67    some of the AF_xxx equivalents, since these are synonyms we just define
68    the PF_xxx's ourselves */
69 
70 #define PF_UNSPEC				0
71 #define PF_INET					AF_INET
72 
73 /* BeOS doesn't define in_*_t's */
74 
75 #define in_addr_t				u_long
76 #define in_port_t				u_short
77 
78 /* BeOS doesn't define NO_ADDRESS, but NO_DATA is a synonym for this */
79 
80 #define NO_ADDRESS				NO_DATA
81 
82 /* BeOS doesn't support checking for anything except readability in select()
83    and only supports one or two socket options, so we define our own
84    versions of these functions that no-op out unsupported options */
85 
86 #define select( sockets, readFD, writeFD, exceptFD, timeout ) \
87 		my_select( sockets, readFD, writeFD, exceptFD, timeout )
88 #define getsockopt( socket, level, optname, optval, optlen ) \
89 		my_getsockopt( socket, level, optname, optval, optlen )
90 #define setsockopt( socket, level, optname, optval, optlen ) \
91 		my_setsockopt( socket, level, optname, optval, optlen )
92 
93 /* The following options would be required, but aren't provided by BeOS.  If
94    you're building under a newer BeOS version that supports these options,
95    you'll also need to update my_set/setsockopt() to no longer no-op them
96    out */
97 
98 #define SO_ERROR				-1
99 #define TCP_NODELAY				-1
100 
101 /****************************************************************************
102 *																			*
103 *						 			ThreadX									*
104 *																			*
105 ****************************************************************************/
106 
107 #elif defined( __ThreadX__ )
108 
109 /* ThreadX doesn't have native socket support, there is a ThreadX component
110    called NetX but everyone seems to use assorted non-ThreadX network
111    stacks.  The following is a representative entry for Treck's network
112    stack */
113 
114 #include "trsocket.h"
115 
116 #undef USE_DNSSRV
117 #undef __WINDOWS__
118 
119 /* Some versions of the Treck stack don't support all IPv6 options */
120 
121 #ifndef NI_NUMERICSERV
122   #define NI_NUMERICSERV	0	/* Unnecessary for Treck stack */
123 #endif /* !NI_NUMERICSERV */
124 
125 /* The Treck stack doesn't implement IPV6_V6ONLY (needed for getsockopt()),
126    the following define gives it an out-of-range value that results in
127    getsockopt() failing, so the operation is skipped */
128 
129 #ifndef IPV6_V6ONLY
130   #define IPV6_V6ONLY		5000
131 #endif /* !IPV6_V6ONLY */
132 
133 /* Like Windows, Treck uses special names for close() and ioctl() to avoid
134    conflicts with standard system calls, and defines special functions for
135    obtaining error information rather than using a static errno-type
136    value */
137 
138 #define closesocket			tfClose
139 #define ioctlsocket			tfIoctl
140 #define getErrorCode()		tfGetSocketError( netStream->netSocket )
141 #define getHostErrorCode()	tfGetSocketError( netStream->netSocket )
142 
143 /* Map Treck's nonstandard error names to more standard ones */
144 
145 #ifndef EADDRNOTAVAIL
146   #define EADDRNOTAVAIL		TM_EADDRNOTAVAIL
147   #define EAGAIN			TM_EAGAIN
148   #define ECONNABORTED		TM_ECONNABORTED
149   #define ECONNREFUSED		TM_ECONNREFUSED
150   #define ECONNRESET		TM_ECONNRESET
151   #define EINPROGRESS		TM_EINPROGRESS
152   #define EINTR				TM_EINTR
153   #define EMFILE			TM_EMFILE
154   #define EMSGSIZE			TM_EMSGSIZE
155   #define ENETUNREACH		TM_ENETUNREACH
156   #define ENOBUFS			TM_ENOBUFS
157   #define ENOTCONN			TM_ENOTCONN
158   #define ETIMEDOUT			TM_ETIMEDOUT
159   #define HOST_NOT_FOUND	TM_DNS_ENAME_ERROR
160   #define NO_ADDRESS		TM_DNS_EANSWER
161   #define NO_DATA			TM_DNS_EANSWER	/* No equivalent in Treck stack */
162   #define TRY_AGAIN			TM_EAGAIN
163 #endif /* Standard error names not defined */
164 
165 /****************************************************************************
166 *																			*
167 *						 			uITRON									*
168 *																			*
169 ****************************************************************************/
170 
171 #elif defined( __ITRON__ )
172 
173 /* uITRON has a TCP/IP API but it doesn't seem to be widely used, and the
174    only available documentation is in Japanese.  If you need TCP/IP support
175    under uITRON and have an implementation available, you can add the
176    appropriate interface by replacing net_tcp.c and net_dns.c with the
177    equivalent uITRON API glue code */
178 
179 #error You need to set up the TCP/IP headers and interface in net_tcp.c/net_dns.c
180 
181 /****************************************************************************
182 *																			*
183 *						 			Nucleus									*
184 *																			*
185 ****************************************************************************/
186 
187 #elif defined( __Nucleus__ )
188 
189 /* Nucleus has it's own functions for network I/O that provide a sort of
190    weird parallel-universe version of the standard sockets API, we map these
191    to standard sockets functions, types, and constants */
192 
193 #include <nu_net.h>
194 
195 #define sockaddr_in		SCK_SOCKADDR_IP_STRUCT
196 #define sin_family		sck_family
197 #define sin_port		sck_port
198 #define sin_addr		sck_addr
199 
200 #define AF_INET			SK_FAM_IP
201 #define FD_SETSIZE		FD_ELEMENTS
202 #define INADDR_ANY		IP_ADDR_ANY
203 #define PF_INET			SK_FAM_IP
204 #define PF_INET6		SK_FAM_IP6
205 #define PF_UNSPEC		SK_FAM_UNSPEC
206 #define SOCK_STREAM		NU_TYPE_STREAM
207 
208 #define fd_set			struct nu_fd_set
209 // Nucelus typedefs struct nu_fd_set -> FD_SET, which clashes with
210 // the standard sockets FD_SET.
211 #define in_addr_t		UINT32
212 #define in_port_t		UINT16
213 
214 #define accept			NU_Accept
215 #define bind			NU_Bind
216 #define close			NU_Close_Socket
217 #define connect			NU_Connect
218 #define gethostbyname	NU_Get_Host_By_Name
219 #define getsockopt		NU_Getsockopt
220 #define listen			NU_Listen
221 #define recv			NU_Recv
222 #define send			NU_Send
223 #define select			NU_Select
224 #define setsockopt		NU_Setsockopt
225 #define shutdown		NU_Shutdown
226 #define socket			NU_Socket
227 
228 #define FD_ZERO			NU_FD_Init
229 #define FD_ISSET		NU_FD_Check
230 #define FD_SET			NU_FD_Set
231 
232 /* Nucleus NET has IPv6 support, but in a very hit-and-miss manner, for
233    example the EAI_xxx values aren't defined (so the autodetection in the
234    IPv6 section won't work), but then values like IPV6_V6ONLY are defined.
235    On the other hand standard functions like getaddrinfo() don't exist at
236    all, so for now we have to restrict ourselves to IPv4.  In order to
237    deal with the erratic presence of IPv6 values we undefine any conflicting
238    ones as required */
239 
240 #undef IPV6_V6ONLY
241 
242 /****************************************************************************
243 *																			*
244 *						 Unix and Unix-compatible Systems					*
245 *																			*
246 ****************************************************************************/
247 
248 /* Guardian sockets originally couldn't handle nonblocking I/O like standard
249    BSD sockets, but required the use of a special non-blocking socket type
250    (nowait sockets) and the use of AWAITIOX() on the I/O tag returned from
251    the nowait socket call, since the async state was tied to this rather
252    than to the socket handle.  One of the early G06 releases added select()
253    support, although even the latest documentation still claims that
254    select() isn't supported.  To avoid having to support two completely
255    different interfaces, we use the more recent (and BSD standard) select()
256    interface.  Anyone running this code on old systems will have to add
257    wrappers for the necessary socket_nw()/accept_nw()/AWAITIOX() calls */
258 
259 #elif ( defined( __BEOS__ ) && defined( BONE_VERSION ) ) || \
260 	  defined( __ECOS__ ) || defined( __MVS__ ) || \
261 	  defined( __PALMOS__ ) || defined( __RTEMS__ ) || \
262 	  defined ( __SYMBIAN32__ ) || defined( __TANDEM_NSK__ ) || \
263 	  defined( __TANDEM_OSS__ ) || defined( __UNIX__ )
264 
265 /* C_IN is a cryptlib.h value which is also defined in some versions of
266    netdb.h, so we have to undefine it before we include any network header
267    files */
268 
269 #undef C_IN
270 
271 /* PHUX and Tandem OSS have broken networking headers that require manually
272    defining _XOPEN_SOURCE_EXTENDED in order for various function prototypes
273    to be enabled.  The Tandem variant of this problem has all the function
274    prototypes for the NSK target and a comment by the 'else' that follows
275    saying that it's for the OSS target, but then an ifdef for
276    _XOPEN_SOURCE_EXTENDED that prevents it from being enabled unless
277    _XOPEN_SOURCE_EXTENDED is also defined */
278 
279 #if ( defined( __hpux ) && ( OSVERSION >= 10 ) ) || defined( _OSS_TARGET )
280   #define _XOPEN_SOURCE_EXTENDED	1
281 #endif /* Workaround for inconsistent networking headers */
282 
283 /* In OS X 10.3 (Panther), Apple broke the bind interface by changing the
284    BIND_4_COMPAT define to BIND_8_COMPAT ("Apple reinvented the wheel and
285    made it square" is one of the more polite comments on this change).  In
286    order to get things to work, we have to define BIND_8_COMPAT here, which
287    forces the inclusion of nameser_compat.h when we include nameser.h.  All
288    (non-Apple) systems automatically define BIND_4_COMPAT to force this
289    inclusion, since Bind9 support (in the form of anything other than the
290    installed binaries) is still pretty rare */
291 
292 #if defined( __APPLE__ ) && !defined( BIND_8_COMPAT )
293   #define BIND_8_COMPAT
294 #endif /* Mac OS X without backwards-compatibility bind define */
295 
296 #include <errno.h>
297 #include <fcntl.h>
298 #include <netdb.h>
299 #if defined( __APPLE__ ) || defined( __BEOS__ ) || defined( __bsdi__ ) || \
300 	(defined( __FreeBSD__ )||defined(__DragonFly__)) || defined( __hpux ) || defined( __MVS__ ) || \
301 	defined( __NetBSD__ ) || defined( __OpenBSD__ ) || defined( __QNX__ ) || \
302 	( defined( sun ) && OSVERSION <= 5 ) || defined( __SYMBIAN32__ ) || \
303 	defined( __VMCMS__ )
304   #include <netinet/in.h>
305 #endif /* OS x || BeOS || *BSDs || PHUX || SunOS 4.x/2.5.x || Symbian OS */
306 #include <arpa/inet.h>
307 #if !( defined( __CYGWIN__ ) || defined( __PALMOS__ ) || \
308 	   defined( __SYMBIAN32__ ) || defined( USE_EMBEDDED_OS ) )
309   #include <arpa/nameser.h>
310 #endif /* Cygwin || Symbian OS */
311 #if defined( __MVS__ ) || defined( __VMCMS__ )
312   /* The following have conflicting definitions in xti.h */
313   #undef T_NULL
314   #undef T_UNSPEC
315 #endif /* MVS || VM */
316 #if !defined( __MVS__ )
317   /* netinet/tcp.h is a BSD-ism, but all Unixen seem to use this even if
318      XPG4 and SUS say it should be in xti.h */
319   #include <netinet/tcp.h>
320 #endif /* !MVS */
321 #if !( defined( __CYGWIN__ ) || defined( __PALMOS__ ) || \
322 	   defined( __SYMBIAN32__ ) || defined( USE_EMBEDDED_OS ) )
323   #include <resolv.h>
324 #endif /* Cygwin || Symbian OS */
325 #if !defined( TCP_NODELAY ) && !defined( USE_EMBEDDED_OS )
326   #include <xti.h>
327   #if defined( __MVS__ ) || defined( __VMCMS__ )
328 	/* The following have conflicting definitions in nameser.h */
329 	#undef T_NULL
330 	#undef T_UNSPEC
331   #endif /* MVS || VM */
332 #endif /* TCP_NODELAY */
333 #ifdef __SCO_VERSION__
334   #include <signal.h>
335   #ifndef SIGIO
336 	#include <sys/signal.h>
337   #endif /* SIGIO not defined in signal.h - only from SCO */
338 #endif /* UnixWare/SCO */
339 #if defined( _AIX ) || defined( __PALMOS__ ) || defined( __QNX__ )
340   #include <sys/select.h>
341 #endif /* Aches || Palm OS || QNX */
342 #include <sys/socket.h>
343 #include <sys/time.h>
344 #include <sys/types.h>
345 #ifdef __PALMOS__
346   /* Needed for close().  unistd.h, which contains this, is normally
347      included by default in Unix environments, but isn't for PalmOS */
348   #include <unistd.h>
349 #endif /* Palm OS */
350 
351 /* AIX and SCO don't define sockaddr_storage in their IPv6 headers so if
352    we detect the use if IPv6 (via IPv6-only status codes) we define a
353    placeholder equivalent here */
354 
355 #if ( ( defined( _AIX ) && OSVERSION <= 5 ) || \
356 	  defined( __SCO_VERSION__ ) ) && \
357 	defined( EAI_BADFLAGS ) && defined( EAI_NONAME )
358   struct sockaddr_storage {
359 		union {
360 			struct sockaddr_in6 bigSockaddrStruct;
361 			char padding[ 128 ];
362 			} dummyMember;
363 		};
364 #endif /* IPv6 versions without sockaddr_storage */
365 
366 /* PHUX generally doesn't define h_errno, we have to be careful here since
367    later versions may use macros to get around threading issues so we check
368    for the existence of a macro with the given name before defining our own
369    version */
370 
371 #if defined( __hpux ) && !defined( h_errno )
372   /* Usually missing from netdb.h */
373   extern int h_errno;
374 #endif /* PHUX && !h_errno */
375 
376 /****************************************************************************
377 *																			*
378 *						 			VxWorks									*
379 *																			*
380 ****************************************************************************/
381 
382 #elif defined( __VxWorks__ )
383 
384 /* The VxWorks' netBufLib.h header defines its own clFree() that conflicts
385    with our one.  To deal with this we either use the nonportable
386    push_macro()/pop_macro() pragma if they're available or we re-include
387    misc/debug.h after overriding the include-once mechanism by undefining
388    _DEBUG_DEFINED and overriding the clAlloc()/clFree()-definition-once
389    mechanism by undefining clAlloc().
390 
391    gcc's support for pop_macro() is typically buggy, so if we don't get
392    clFree() defined after we pop it we fall back to the re-include as well.
393    This is why it's done as a #ifndef rather than a #else */
394 
395 #if defined( __GNUC__ ) || defined( _MSC_VER )
396   #pragma push_macro( "clFree" )
397 #endif /* push_macro() support */
398 #undef clFree
399 
400 #include <ioLib.h>
401 #include <selectLib.h>
402 #include <hostLib.h>
403 #include <sockLib.h>
404 #include <arpa/inet.h>
405 #include <netinet/in.h>
406 #include <netinet/tcp.h>
407 #include <netinet6/in6.h>
408 #include <sys/socket.h>
409 
410 #undef clFree
411 #if defined( __GNUC__ ) || defined( _MSC_VER )
412   #pragma pop_macro( "clFree" )
413 #endif /* push_macro() support */
414 #ifndef clFree				/* See comment above */
415   #undef _DEBUG_DEFINED		/* Override include-once */
416   #undef clAlloc			/* Override define-once */
417   #include "misc/debug.h"
418 #endif /* push_macro() support */
419 
420 /* Although VxWorks defines AI_NUMERICSERV, any attempt to use it with
421    getaddrinfo() produces an EAI_BADFLAGS error, so we no-op it out */
422 
423 #undef AI_NUMERICSERV
424 #define AI_NUMERICSERV	0
425 
426 /* VxWorks doesn't have an h_errno and no-one seems to know what the
427    substitute for it is, if any, so we no-op it out */
428 
429 #define h_errno			0
430 
431 /****************************************************************************
432 *																			*
433 *						 			Windows									*
434 *																			*
435 ****************************************************************************/
436 
437 #elif defined( __WINDOWS__ )
438 
439 /* Winsock2 wasn't available until VC++/eVC++ 4.0 so if we're running an
440    older version we have to use the Winsock1 interface */
441 
442 #if defined( _MSC_VER ) && ( _MSC_VER <= 800 ) || \
443 	defined( __WINCE__ ) && ( _WIN32_WCE < 400 )
444   #include <winsock.h>
445 #else
446   #include <winsock2.h>
447   #include <ws2tcpip.h>
448 #endif /* Older WinCE vs. newer WinCE and Win32 */
449 
450 /* VC++ 7 and newer have IPv6 support included in ws2tcpip.h, VC++ 6 can
451    have it bolted-on using the IPv6 Technology Preview but it's not present
452    by default.  In addition the Tech.Preview is quite buggy and unstable,
453    leaking handles and memory and in some cases leading to runaway memory
454    consumption that locks up the machine if the process isn't killed in
455    time, so we don't want to encourage its use */
456 
457 #if defined( _MSC_VER ) && ( _MSC_VER > 1300 )
458   /* #include <tpipv6.h> */	/* From IPv6 Tech.Preview */
459 #endif /* VC++ 7 and newer */
460 
461 /* VC++ 7 and newer have DNS headers, for older versions (or for builds
462    using the DDK) we have to define the necessary types and constants
463    ourselves */
464 
465 #if defined( _MSC_VER ) && ( _MSC_VER > 1300 ) && !defined( WIN_DDK )
466   #include <windns.h>
467 #elif defined( _MSC_VER ) && ( _MSC_VER > 800 )
468   /* windns.h is for newer compilers and many people don't have it yet, not
469 	 helped by the fact that it's also changed over time.  For example,
470 	 DnsRecordListFree() has also been DnsFreeRecordList() and DnsFree() at
471 	 various times, with the parameters changing to match.  Because of this,
472 	 we have to define our own (very cut-down) subset of what's in there
473 	 here.  We define PIP4_ARRAY as a void * since it's only used to specify
474 	 optional DNS servers to query, we never need this so we just set the
475 	 parameter to NULL.  As with the DnsXXX functions, PIP4_ARRAY has
476 	 changed over time.  It was known as PIP_ARRAY in the original VC++ .NET
477 	 release but was renamed PIP4_ARRAY for .NET 2003, although some MSDN
478 	 entries still refer to PIP_ARRAY even in the 2003 version */
479   typedef LONG DNS_STATUS;
480   typedef void *PIP4_ARRAY;
481   typedef DWORD IP4_ADDRESS;
482   typedef enum { DnsFreeFlat, DnsFreeRecordList } DNS_FREE_TYPE;
483   typedef enum { DnsConfigPrimaryDomainName_W, DnsConfigPrimaryDomainName_A,
484 				 DnsConfigPrimaryDomainName_UTF8, DnsConfigAdapterDomainName_W,
485 				 DnsConfigAdapterDomainName_A, DnsConfigAdapterDomainName_UTF8,
486 				 DnsConfigDnsServerList, DnsConfigSearchList,
487 				 DnsConfigAdapterInfo, DnsConfigPrimaryHostNameRegistrationEnabled,
488 				 DnsConfigAdapterHostNameRegistrationEnabled,
489 				 DnsConfigAddressRegistrationMaxCount, DnsConfigHostName_W,
490 				 DnsConfigHostName_A, DnsConfigHostName_UTF8,
491 				 DnsConfigFullHostName_W, DnsConfigFullHostName_A,
492 				 DnsConfigFullHostName_UTF8 } DNS_CONFIG_TYPE;
493   #define DNS_TYPE_A				1
494   #define DNS_TYPE_PTR				12
495   #define DNS_TYPE_SRV				33
496   #define DNS_QUERY_STANDARD		0
497   #define DNS_QUERY_BYPASS_CACHE	8
498   typedef struct {
499 	/* Technically these are DWORDs, but only integers are allowed for
500 	   bitfields.  This is OK in this case because sizeof( int ) ==
501 	   sizeof( DWORD ) */
502 	unsigned int Section : 2;
503 	unsigned int Delete : 1;
504 	unsigned int CharSet : 2;
505 	unsigned int Unused : 3;
506 	unsigned int Reserved : 24;
507 	} DNS_RECORD_FLAGS;
508   typedef struct {
509 	IP4_ADDRESS IpAddress;
510 	} DNS_A_DATA, *PDNS_A_DATA;
511   typedef struct {
512 	LPTSTR pNameHost;
513 	} DNS_PTR_DATA, *PDNS_PTR_DATA;
514   typedef struct {
515 	LPTSTR pNameTarget;
516 	WORD wPriority;
517 	WORD wWeight;
518 	WORD wPort;
519 	WORD Pad;
520 	} DNS_SRV_DATA, *PDNS_SRV_DATA;
521   typedef struct _DnsRecord {
522 	struct _DnsRecord *pNext;
523 	LPTSTR pName;
524 	WORD wType;
525 	WORD wDataLength;
526 	union {
527 		DWORD DW;
528 		DNS_RECORD_FLAGS S;
529 	} Flags;
530 	DWORD dwTtl;
531 	DWORD dwReserved;
532 	union {
533 		DNS_A_DATA A;
534 		DNS_PTR_DATA PTR, Ptr,
535 					 NS, Ns,
536 					 CNAME, Cname,
537 					 MB, Mb,
538 					 MD, Md,
539 					 MF, Mf,
540 					 MG, Mg,
541 					 MR, Mr;
542 	#if 0
543 		DNS_MINFO_DATA MINFO, Minfo,
544 					   RP, Rp;
545 		DNS_MX_DATA MX, Mx,
546 					AFSDB, Afsdb,
547 					RT, Rt;
548 		DNS_TXT_DATA HINFO, Hinfo,
549 					 ISDN, Isdn,
550 					 TXT, Txt,
551 					 X25;
552 		DNS_NULL_DATA Null;
553 		DNS_WKS_DATA WKS, Wks;
554 		DNS_AAAA_DATA AAAA;
555 		DNS_KEY_DATA KEY, Key;
556 		DNS_SIG_DATA SIG, Sig;
557 		DNS_ATMA_DATA ATMA, Atma;
558 		DNS_NXT_DATA NXT, Nxt;
559 	#endif /* 0 */
560 		DNS_SRV_DATA SRV, Srv;
561 	#if 0
562 		DNS_TKEY_DATA TKEY, Tkey;
563 		DNS_TSIG_DATA TSIG, Tsig;
564 		DNS_WINS_DATA WINS, Wins;
565 		DNS_WINSR_DATA WINSR, WinsR,
566 					   NBSTAT, Nbstat;
567 	#endif /* 0 */
568 		} Data;
569 	} DNS_RECORD, *PDNS_RECORD;
570 #endif /* VC++ 7 and newer vs. older versions */
571 
572 /* The Winsock FD_SET() in newer versions of VC++ uses a comma expression
573    that results in the following warning wherever it's used:
574 
575 	warning C4548: expression before comma has no effect; expected
576 				   expression with side-effect
577 
578    In theory we could use the __pragma operator introduced in VS 2010
579    to disable the warning:
580 
581    FD_SET ->
582 	__pragma( warning( push ) ) \
583 	__pragma( warning( disable:4548 ) ) \
584 	FD_SET( ... );
585 	__pragma( warning( pop ) )
586 
587    but there's no obvious way to define a new macro to replace an existing
588    one, so for now we'll have to live with the warnings */
589 
590 /* For backwards-compatibility purposes, wspiapi.h overrides the new address/
591    name-handling functions introduced for IPv6 with complex macros that
592    substitute inline function calls that try and dynamically load different
593    libraries depending on the Windows version and call various helper
594    functions to provide the same service.  Since we dynamically load the
595    required libraries, we don't need any of this complexity, so we undefine
596    the macros in order to make our own ones work */
597 
598 #ifdef getaddrinfo
599   #undef freeaddrinfo
600   #undef getaddrinfo
601   #undef getnameinfo
602 #endif /* getaddrinfo defined as macros in wspiapi.h */
603 
604 /* Set up the appropriate calling convention for the Winsock API */
605 
606 #if defined( WSAAPI )
607   #define SOCKET_API	WSAAPI
608 #elif defined( WINSOCKAPI )
609   #define SOCKET_API	WINSOCKAPI
610 #else
611   #define SOCKET_API	FAR PASCAL
612 #endif /* WSAAPI */
613 
614 /****************************************************************************
615 *																			*
616 *						 		Custom TCP Stacks							*
617 *																			*
618 ****************************************************************************/
619 
620 #elif defined( USE_LWIP )
621 
622 #define LWIP_DNS		1		/* Needed for DNS lookups */
623 
624 #include "lwip/sockets.h"
625 #include "lwip/netdb.h"
626 
627 /* LWIP has small pieces of IPv6 (getaddrinfo(), freeaddrinfo()) but none of
628    the surrounding functions (gai_strerror()) or defines (AI_PASSIVE,
629    NI_NUMERICxxx, IPPROTO_IPV6, IPV6_V6ONLY, etc), so we remove the two
630    xxxaddrinfo()s (which exist as macros) and rename the LWIP addrinfo
631    struct to something else so that we can replace it with out own one */
632 
633 #undef getaddrinfo
634 #undef freeaddrinfo
635 #define addrinfo		_lwip_addrinfo
636 
637 /* LWIP doesn't define NO_ADDRESS, but NO_DATA is a synonym for this, or
638    IPPROTO_ICMP */
639 
640 #define NO_ADDRESS				NO_DATA
641 #define IPPROTO_ICMP			1
642 
643 /****************************************************************************
644 *																			*
645 *						 			Other Systems							*
646 *																			*
647 ****************************************************************************/
648 
649 #else
650 
651 #error You need to set up OS-specific networking include handling in net_tcp.h
652 
653 #endif /* OS-specific includes and defines */
654 
655 /****************************************************************************
656 *																			*
657 *						 	General/Portability Defines						*
658 *																			*
659 ****************************************************************************/
660 
661 /* The size of a (v4) IP address and the number of IP addresses that we try
662    to connect to for a given host, used if we're providing an emulated
663    (IPv4-only) getaddrinfo() */
664 
665 #define IP_ADDR_SIZE	4
666 #define IP_ADDR_COUNT	16
667 
668 /* Test for common socket errors.  For isBadSocket() we don't just compare
669    the socket to INVALID_SOCKET but perform a proper range check both to
670    catch any problems with buggy implementations that may return something
671    other than -1 to indicate an error, and because we're going to use the
672    value in FD_xyz() macros which often don't perform any range checking,
673    and a value outside the range 0...FD_SETSIZE can cause segfaults and
674    other problems.  In addition we exclude stdin/stdout/stderr if they're
675    present, since a socket with these handle values is somewhat suspicious,
676    The one exception to this is Windows sockets, which don't use a Berkeley-
677    type bitflag representation and therefore don't have the range problems
678    that the Berkeley implementation does */
679 
680 #ifndef __WINDOWS__
681   #define INVALID_SOCKET			-1
682 #endif /* __WINDOWS__ */
683 #if defined( __WINDOWS__ )
684   #define isBadSocket( socket )		( ( socket ) <= 0 )
685 #elif defined( STDERR_FILENO )
686   #define isBadSocket( socket )		( ( socket ) <= STDERR_FILENO || \
687 									  ( socket ) >= FD_SETSIZE )
688 #else
689   #define isBadSocket( socket )		( ( socket ) <= 0 || \
690 									  ( socket ) >= FD_SETSIZE )
691 #endif /* STDERR_FILENO */
692 #ifdef __WINDOWS__
693   #define isSocketError( status )	( ( status ) == SOCKET_ERROR )
694   #define isBadAddress( address )	( ( address ) == INADDR_NONE )
695 #else
696   #define isSocketError( status )	( ( status ) == -1 )
697   #define isBadAddress( address )	( ( address ) == ( in_addr_t ) -1 )
698 #endif /* Windows vs. other systems */
699 #if defined( __SYMBIAN32__ )
700   /* Symbian OS doesn't support nonblocking I/O */
701   #define isNonblockWarning()		0
702 #elif defined( __BEOS__ )
703   #if defined( BONE_VERSION )
704 	/* BONE returns "Operation now in progress" */
705 	#define isNonblockWarning()		( errno == EWOULDBLOCK || \
706 									  errno == 0x80007024 )
707   #else
708 	/* BeOS, even though it supposedly doesn't support nonblocking
709 	   sockets, can return EWOULDBLOCK */
710 	#define isNonblockWarning()		( errno == EWOULDBLOCK )
711   #endif /* BeOS with/without BONE */
712 #elif defined( __WINDOWS__ )
713   #define isNonblockWarning()		( WSAGetLastError() == WSAEWOULDBLOCK )
714 #else
715 	#define isNonblockWarning()		( errno == EINPROGRESS )
716 #endif /* OS-specific socket error handling */
717 
718 /* Error code handling */
719 
720 #if defined( __WINDOWS__ )
721   #define getErrorCode()			WSAGetLastError()
722   #define getHostErrorCode()		WSAGetLastError()
723 #elif !defined( getErrorCode )
724   #define getErrorCode()			errno
725   #if ( defined( __MVS__ ) && defined( _OPEN_THREADS ) )
726 	/* MVS converts this into a hidden function in the presence of threads,
727 	   but not transparently like other systems */
728 	#define getHostErrorCode()		( *__h_errno() )
729   #else
730 	#define getHostErrorCode()		h_errno
731   #endif /* MVS */
732 #endif /* OS-specific error code handling */
733 
734 /* Windows and BeOS use a distinct socket handle type and require the use of
735    separate closesocket() and ioctlsocket() functions because socket handles
736    aren't the same as standard Windows/BeOS handles */
737 
738 #ifdef SOCKET
739   /* MP-RAS has already defined this */
740   #undef SOCKET
741 #endif /* SOCKET */
742 #define SOCKET						int
743 #if !defined( __WINDOWS__ ) && !defined( closesocket )
744   #if !defined( __BEOS__ ) || \
745 	  ( defined( __BEOS__ ) && defined( BONE_VERSION ) )
746 	#define closesocket				close
747   #endif /* BeOS without BONE */
748   #define ioctlsocket				ioctl
749 #endif /* OS-specific portability defines */
750 
751 /* Many systems don't define the in_*_t's */
752 
753 #if defined( __APPLE__ ) || defined( __BEOS__ ) || \
754 	defined( __bsdi__ ) || defined( _CRAY ) || \
755 	defined( __CYGWIN__ ) || (defined( __FreeBSD__ )||defined(__DragonFly__)) || \
756 	defined( __hpux ) || defined( __linux__ ) || \
757 	defined( __NetBSD__ ) || defined( __OpenBSD__ ) || \
758 	defined( __QNX__ ) || ( defined( sun ) && OSVERSION <= 5 ) || \
759 	defined( __WINDOWS__ )
760   #ifndef in_addr_t
761 	#define in_addr_t				u_long
762 	#define in_port_t				u_short
763   #endif /* in_addr_t */
764 #elif defined( USE_LWIP )
765 	#define in_addr_t				unsigned long
766 	#define in_port_t				unsigned short
767 #endif /* Systems without in_*_t's */
768 
769 /* The handling of size parameters to socket functions is, as with most
770    things Unix, subject to random portability problems.  The traditional
771    BSD sockets API used int for size parameters to socket functions, Posix
772    decided it'd be better to use size_t, but then people complained that
773    this wasn't binary-compatible with existing usage because on 64-bit
774    systems size_t != int.  Instead of changing it back to int, Posix defined
775    a new type, socklen_t, which may or may not be an int.  So some systems
776    have int, some have size_t, some have socklen_t defined to int, and some
777    have socklen_t defined to something else.  PHUX, as usual, is
778    particularly bad, defaulting to the BSD form with int unless you define
779    _XOPEN_SOURCE_EXTENDED, in which case you get socklen_t but it's mapped
780    to size_t without any change in the sockets API, which still expects int
781    (the PHUX select() has a similar problem, see the comment in
782    random/unix.c).
783 
784    To resolve this, we try and use socklen_t if we detect its presence,
785    otherwise we use int where we know it's safe to do so, and failing that
786    we fall back to size_t */
787 
788 #if defined( socklen_t ) || defined( __socklen_t_defined ) || \
789 	defined( _SOCKLEN_T )
790   #define SIZE_TYPE					socklen_t
791 #elif defined( __BEOS__ ) || defined( _CRAY ) || defined( __WINDOWS__ )
792   #define SIZE_TYPE					int
793 #else
794   #define SIZE_TYPE					size_t
795 #endif /* Different size types */
796 
797 /* The Bind namespace (via nameser.h) was cleaned up between the old (widely-
798    used) Bind4 API and the newer (little-used) Bind8/9 one.  In order to
799    handle both, we use the newer definitions, but map them back to the Bind4
800    forms if required.  The only thing this doesn't give us is the HEADER
801    struct, which seems to have no equivalent in Bind8/9 */
802 
803 #ifndef NS_PACKETSZ
804   #define NS_PACKETSZ				PACKETSZ
805   #define NS_HFIXEDSZ				HFIXEDSZ
806   #define NS_RRFIXEDSZ				RRFIXEDSZ
807   #define NS_QFIXEDSZ				QFIXEDSZ
808 #endif /* Bind8 names */
809 
810 /* Older versions of QNX don't define HFIXEDSZ either */
811 
812 #if defined( __QNX__ ) && ( OSVERSION <= 4 )
813   #define HFIXEDSZ					12
814 #endif /* QNX 4.x */
815 
816 /* Values defined in some environments but not in others.  MSG_NOSIGNAL is
817    used to avoid SIGPIPEs on writes if the other side closes the connection,
818    if it's not implemented in this environment we just clear the flag */
819 
820 #ifndef SHUT_WR
821   #define SHUT_WR					1
822 #endif /* SHUT_WR */
823 #ifndef MSG_NOSIGNAL
824   #define MSG_NOSIGNAL				0
825 #endif /* MSG_NOSIGNAL */
826 
827 /* For some connections that involve long-running sessions we need to be
828    able to gracefully recover from local errors such as an interrupted system
829    call, and remote errors such as the remote process or host crashing and
830    restarting, which we can do by closing and re-opening the connection.  The
831    various situations are:
832 
833 	Local error:
834 		Retry the call on EAGAIN or EINTR
835 
836 	Process crashes and restarts:
837 		Write: Remote host sends a RST in response to an attempt to continue
838 				a TCP session that it doesn't remember, which is reported
839 				locally as the dreaded (if you ssh or NNTP to remote hosts a
840 				lot) connection reset by peer error.
841 		Read: Remote host sends a FIN, we read 0 bytes.
842 
843 	Network problem:
844 		Write: Data is re-sent, if a read is pending it returns ETIMEDOUT,
845 				otherwise write returns EPIPE or SIGPIPE (although we try
846 				and avoid the latter using MSG_NOSIGNAL).  Some
847 				implementations may also return ENETUNREACH or EHOSTUNREACH
848 				if they receive the right ICMP information.
849 		Read: See above, without the write sematics.
850 
851 	Host crashes and restarts:
852 		Write: Looks like a network outage until the host is restarted, then
853 				gets an EPIPE/SIGPIPE.
854 		Read: As for write, but gets a ECONNRESET.
855 
856    The following macros check for various non-fatal/recoverable error
857    conditions, in the future we may want to address some of the others listed
858    above as well.  A restartable error is a local error for which we can
859    retry the call, a recoverable error is a remote error for which we would
860    need to re-establish the connection.  Note that any version of Winsock
861    newer than the 16-bit ones shouldn't give us an EINPROGRESS, however some
862    early stacks would still give this on occasions such as when another
863    thread was doing (blocking) name resolution, and even with the very latest
864    versions this is still something that can cause problems for other
865    threads */
866 
867 #ifdef __WINDOWS__
868   #define isRecoverableError( status )	( ( status ) == WSAECONNRESET )
869   #define isRestartableError()			( WSAGetLastError() == WSAEWOULDBLOCK || \
870 										  WSAGetLastError() == WSAEINPROGRESS )
871   #define isTimeoutError()				( WSAGetLastError() == WSAETIMEDOUT )
872 #else
873   #define isRecoverableError( status )	( ( status ) == ECONNRESET )
874   #define isRestartableError()			( errno == EINTR || errno == EAGAIN )
875   #define isTimeoutError()				( errno == ETIMEDOUT )
876 #endif /* OS-specific status codes */
877 
878 /****************************************************************************
879 *																			*
880 *						 		IPv6 Defines								*
881 *																			*
882 ****************************************************************************/
883 
884 /* Now that we've included all of the networking headers, try and guess
885    whether this is an IPv6-enabled system.  We can detect this by the
886    existence of definitions for the EAI_xxx return values from
887    getaddrinfo().  Note that we can't safely detect it using the more
888    obvious AF_INET6 since many headers defined this in anticipation of IPv6
889    long before the remaining code support was present */
890 
891 #if defined( EAI_BADFLAGS ) && defined( EAI_NONAME )
892   #define IPv6
893 #endif /* getaddrinfo() return values defined */
894 
895 /* Some systems have just enough IPv6 defines present to be awkward (BeOS
896    with the BONE network stack) so we temporarily define IPv6 and then use a
897    stack-specific subset of IPv6 defines further on */
898 
899 #if defined( __BEOS__ ) && defined( BONE_VERSION )
900   #define IPv6
901 #endif /* BeOS with BONE */
902 
903 /* The generic sockaddr struct used to reserve storage for protocol-specific
904    sockaddr structs.  The IPv4 equivalent is given below in the IPv6-
905    emulation definitions */
906 
907 #ifdef IPv6
908   #define SOCKADDR_STORAGE			struct sockaddr_storage
909 #endif /* IPv6 */
910 
911 /* IPv6 emulation functions used to provide a single consistent interface */
912 
913 #ifndef IPv6
914   /* The addrinfo struct used by getaddrinfo() */
915   struct addrinfo {
916 	int ai_flags;				/* AI_PASSIVE, NI_NUMERICHOST */
917 	int ai_family;				/* PF_INET */
918 	int ai_socktype;			/* SOCK_STREAM */
919 	int ai_protocol;			/* IPPROTO_TCP */
920 	size_t ai_addrlen;			/* Length of ai_addr */
921 	char *ai_canonname;			/* CNAME for nodename */
922 	ARRAY_FIXED( ai_addrlen ) \
923 	struct sockaddr *ai_addr;	/* IPv4 or IPv6 sockaddr */
924 	struct addrinfo *ai_next;	/* Next addrinfo structure list */
925 	};
926 
927   /* The generic sockaddr struct used to reserve storage for protocol-
928      specific sockaddr structs.  This isn't quite right but since all
929 	 we're using it for is to reserve storage (we never actually look
930 	 inside it) it's OK to use here  */
931   typedef char SOCKADDR_STORAGE[ 128 ];
932 
933   /* getaddrinfo() flags and values */
934   #define AI_PASSIVE		0x1		/* Flag for hints are for getaddrinfo() */
935 
936   /* getnameinfo() flags and values.  We have to use slightly different
937      values for these under Windows because Windows uses different values
938 	 for these than anyone else, and even if we're not on an explicitly
939 	 IPv6-enabled system we could still end up dynamically pulling in the
940 	 required libraries, so we need to ensure that we're using the same flag
941 	 values that Windows does */
942   #ifdef __WINDOWS__
943 	#define NI_NUMERICHOST	0x2		/* Return numeric form of host addr.*/
944 	#define NI_NUMERICSERV	0x8		/* Return numeric form of host port */
945   #else
946 	#define NI_NUMERICHOST	0x1		/* Return numeric form of host addr.*/
947 	#define NI_NUMERICSERV	0x2		/* Return numeric form of host port */
948   #endif /* __WINDOWS__ */
949 
950   /* get/setsockopt() flags and values.  Again, we have to use slightly
951      different values for Windows in some cases */
952   #define IPPROTO_IPV6		41		/* IPv6 */
953   #if defined( __WINDOWS__ ) || defined( __VxWorks__ )
954 	#define IPV6_V6ONLY		27		/* Force dual stack to use only IPv6 */
955   #else
956 	#define IPV6_V6ONLY		26		/* Force dual stack to use only IPv6 */
957   #endif /* __WINDOWS__ */
958 
959   /* If there's no getaddrinfo() available and we're not using dynamic
960      linking, use an emulation of the function */
961   #ifndef __WINDOWS__
962 	#define getaddrinfo		my_getaddrinfo
963 	#define freeaddrinfo	my_freeaddrinfo
964 	#define getnameinfo		my_getnameinfo
965 
966 	static int my_getaddrinfo( const char *nodename, const char *servname,
967 							   const struct addrinfo *hints,
968 							   struct addrinfo **res );
969 	static void my_freeaddrinfo( struct addrinfo *ai );
970 	static int my_getnameinfo( const struct sockaddr *sa, SIZE_TYPE salen,
971 							   char *node, SIZE_TYPE nodelen,
972 							   char *service, SIZE_TYPE servicelen,
973 							   int flags );
974 
975 	/* Windows uses the Pascal calling convention for these functions, we
976 	   hide this behind a define that becomes a no-op on non-Windows
977 	   systems */
978 	#define SOCKET_API
979   #endif /* __WINDOWS__ */
980 #else
981   /* IPV6_V6ONLY isn't universally defined under Windows even if IPv6
982 	 support is available.  The situations under which this occurs are
983 	 rather unclear, it's happened for some x86-64 builds (although not for
984 	 straight x86 builds on the same machine), for older WinCE builds, and
985 	 in one case for an x86 build using VS 2005, possibly caused by
986 	 differences between VS and WinSDK headers.  To resolve this mess, if
987 	 IPv6 is defined under Windows but IPV6_V6ONLY isn't, we explicitly
988 	 define it ourselves */
989   #if defined( __WINDOWS__ ) && !defined( IPV6_V6ONLY )
990 	#define IPV6_V6ONLY		27		/* Force dual stack to use only IPv6 */
991   #endif /* Some Windows build environments */
992 #endif /* IPv6 */
993 
994 /* A subset of the above for BeOS with the BONE network stack.  See the
995    full IPv6 version above for descriptions of the entries */
996 
997 #if defined( __BEOS__ ) && defined( BONE_VERSION )
998   #undef IPv6						/* We really don't do IPv6 */
999 
1000   typedef char SOCKADDR_STORAGE[ 128 ];
1001 
1002   #define getaddrinfo		my_getaddrinfo
1003   #define freeaddrinfo		my_freeaddrinfo
1004   #define getnameinfo		my_getnameinfo
1005 
1006   static int my_getaddrinfo( const char *nodename, const char *servname,
1007 							 const struct addrinfo *hints,
1008 							 struct addrinfo **res );
1009   static void my_freeaddrinfo( struct addrinfo *ai );
1010   static int my_getnameinfo( const struct sockaddr *sa, SIZE_TYPE salen,
1011 							 char *node, SIZE_TYPE nodelen,
1012 							 char *service, SIZE_TYPE servicelen,
1013 							 int flags );
1014 #endif /* BeOS with BONE */
1015 
1016 /****************************************************************************
1017 *																			*
1018 *						 		Resolver Defines							*
1019 *																			*
1020 ****************************************************************************/
1021 
1022 /* Values defined in some environments but not in others.  T_SRV and
1023    NS_SRVFIXEDSZ are used for DNS SRV lookups.  Newer versions of bind use a
1024    ns_t_srv enum for T_SRV but since we can't autodetect this via the
1025    preprocessor we always define T_SRV ourselves */
1026 
1027 #ifndef T_SRV
1028   #define T_SRV						33
1029 #endif /* !T_SRV */
1030 #ifndef NS_SRVFIXEDSZ
1031   #define NS_SRVFIXEDSZ				( NS_RRFIXEDSZ + 6 )
1032 #endif /* !NS_SRVFIXEDSZ */
1033 #ifndef AI_ADDRCONFIG
1034   #define AI_ADDRCONFIG				0
1035 #endif /* !AI_ADDRCONFIG */
1036 #ifndef AI_NUMERICSERV
1037   #define AI_NUMERICSERV			0
1038 #endif /* !AI_NUMERICSERV */
1039 
1040 /* Check whether an address family returned from a DNS lookup is allowed
1041    (meaning recognised) */
1042 
1043 #ifdef IPv6
1044   #define allowedAddressFamily( family ) \
1045 		  ( ( ( family ) == AF_INET ) || ( ( family ) == AF_INET6 ) )
1046 #else
1047   #define allowedAddressFamily( family )	( ( family ) == AF_INET )
1048 #endif /* IPv6 */
1049 
1050 /* gethostbyname is a problem function because the standard version is non-
1051    thread-safe due to the use of static internal storage to contain the
1052    returned host info.  Some OSes (Windows, PHUX >= 11.0, OSF/1 >= 4.0,
1053    Aches >= 4.3) don't have a problem with this because they use thread
1054    local storage, but others either require the use of nonstandard _r
1055    variants or simply don't handle it at all.  To make it even more
1056    entertaining, there are at least three different variations of the _r
1057    form:
1058 
1059 	Linux (and glibc systems in general, but not BeOS with BONE):
1060 
1061 	int gethostbyname_r( const char *name, struct hostent *result_buf,
1062 						 char *buf, size_t buflen, struct hostent **result,
1063 						 int *h_errnop);
1064 
1065 	Slowaris >= 2.5.1, IRIX >= 6.5, QNX:
1066 
1067 	struct hostent *gethostbyname_r( const char *name,
1068 									 struct hostent *result, char *buffer,
1069 									 int buflen, int *h_errnop );
1070 
1071 	OSF/1, Aches (deprecated, see above):
1072 
1073 	int gethostbyname_r( const char *name, struct hostent *hptr,
1074 						 struct hostent_data *hdptr );
1075 
1076    To work around this mess, we define macros for thread-safe versions of
1077    gethostbyname that can be retargeted to the appropriate function as
1078    required */
1079 
1080 #if defined( USE_THREADS ) && defined( __GLIBC__ ) && ( __GLIBC__ >= 2 ) && \
1081 	( !defined( __BEOS__ ) || !defined( BONE_VERSION ) )
1082   #define gethostbyname_vars() \
1083 		  char hostBuf[ 4096 ]; \
1084 		  struct hostent hostEnt;
1085   #define gethostbyname_threadsafe( hostName, hostEntPtr, hostErrno ) \
1086 		  if( gethostbyname_r( hostName, &hostEnt, hostBuf, 4096, &hostEntPtr, &hostErrno ) < 0 ) \
1087 			hostEntPtr = NULL
1088 #elif defined( USE_THREADS ) && \
1089 	  ( ( defined( sun ) && OSVERSION > 4 ) || \
1090 		( defined( __sgi ) && OSVERSION >= 6 ) || defined( __QNX__ ) )
1091   #define gethostbyname_vars() \
1092 		  char hostBuf[ 4096 ]; \
1093 		  struct hostent hostEnt;
1094   #define gethostbyname_threadsafe( hostName, hostEntPtr, hostErrno ) \
1095 		  hostEntPtr = gethostbyname_r( hostName, &hostEnt, hostBuf, 4096, &hostErrno )
1096 #elif defined( USE_THREADS ) && ( defined( USE_LWIP ) )
1097   #define gethostbyname_vars() \
1098 		  char hostBuf[ 1024 ]; \
1099 		  struct hostent hostEnt;
1100   #define gethostbyname_threadsafe( hostName, hostEntPtr, hostErrno ) \
1101 		  if( gethostbyname_r( hostName, &hostEnt, hostBuf, 1024, &hostEntPtr, &hostErrno ) < 0 ) \
1102 			hostEntPtr = NULL
1103 #else
1104   #define gethostbyname_vars()
1105   #define gethostbyname_threadsafe( hostName, hostEntPtr, hostErrno ) \
1106 		  hostEntPtr = gethostbyname( hostName ); \
1107 		  hostErrno = h_errno;
1108 #endif /* Various gethostbyname variants */
1109 
1110 /****************************************************************************
1111 *																			*
1112 *						 	Non-blocking I/O Defines						*
1113 *																			*
1114 ****************************************************************************/
1115 
1116 /* The traditional way to set a descriptor to nonblocking mode was an
1117    ioctl with FIONBIO, however Posix prefers the O_NONBLOCK flag for fcntl()
1118    so we use this if it's available, with some exceptions for systems like
1119    VxWorks where it's present but doesn't work as expected.
1120 
1121    Unfortunately if we haven't got the fcntl() interface available there's
1122    no way to determine whether a socket is non-blocking or not, which is
1123    particularly troublesome for Windows where we need to ensure that the
1124    socket is blocking in order to avoid Winsock bugs with nonblocking
1125    sockets.  Although WSAIoctl() would appear to provide an interface for
1126    obtaining the nonblocking status, it doesn't provide any more
1127    functionality than ioctlsocket(), returning an error if we try and read
1128    the FIONBIO value.
1129 
1130    If we're just using this as a basic valid-socket check we could also use
1131    ( GetFileType( ( HANDLE ) stream->netSocket ) == FILE_TYPE_PIPE ) ? 0 : \
1132    WSAEBADF to check that it's a socket, but there's a bug under all Win9x
1133    versions for which GetFileType() on a socket returns FILE_TYPE_UNKNOWN,
1134    so we can't reliably detect a socket with this.  In any case though
1135    ioctlsocket() will return WSAENOTSOCK if it's not a socket, so this is
1136    covered by the default handling anyway.
1137 
1138    The best that we can do in this case is to force the socket to be
1139    blocking, which somewhat voids the guarantee that we leave the socket as
1140    we found it, but OTOH if we've been passed an invalid socket the caller
1141    will have to abort and fix the problem anyway, so changing the socket
1142    state isn't such a big deal.
1143 
1144    BeOS is even worse, not only is there no way to determine whether a
1145    socket is blocking or not, it'll also quite happily perform socket
1146    functions like setsockopt() on a file descriptor (for example stdout),
1147    so we can't even use this as a check for socket validity as it is under
1148    other OSes.  Because of this the check socket function will always
1149    indicate that something vaguely handle-like is a valid socket.
1150 
1151    When we get the nonblocking status, if there's an error getting the
1152    status we report it as a non-blocking socket, which results in the socket
1153    being reported as invalid, the same as if it were a a genuine non-
1154    blocking socket.
1155 
1156    If we're using the ioctlsocket() interface we make the argument an
1157    unsigned long, in most cases this is a 'void *' but under Windows it's
1158    an 'unsigned long *' so we use the most restrictive type */
1159 
1160 #if defined( F_GETFL ) && defined( F_SETFL ) && defined( O_NONBLOCK ) && \
1161 	!defined( __VxWorks__ )
1162   #define getSocketNonblockingStatus( socket, value ) \
1163 			{ \
1164 			value = fcntl( socket, F_GETFL, 0 ); \
1165 			value = ( isSocketError( value ) || ( value & O_NONBLOCK ) ) ? \
1166 					TRUE : FALSE; \
1167 			}
1168   #define setSocketNonblocking( socket ) \
1169 			{ \
1170 			const int flags = fcntl( socket, F_GETFL, 0 ); \
1171 			fcntl( socket, F_SETFL, flags | O_NONBLOCK ); \
1172 			}
1173   #define setSocketBlocking( socket ) \
1174 			{ \
1175 			const int flags = fcntl( socket, F_GETFL, 0 ); \
1176 			fcntl( socket, F_SETFL, flags & ~O_NONBLOCK ); \
1177 			}
1178 #elif defined( FIONBIO )
1179   #define getSocketNonblockingStatus( socket, value ) \
1180 			{ \
1181 			unsigned long nonBlock = FALSE; \
1182 			value = ioctlsocket( socket, FIONBIO, &nonBlock ); \
1183 			value = isSocketError( value ) ? TRUE : FALSE; \
1184 			}
1185   #define setSocketNonblocking( socket ) \
1186 			{ \
1187 			unsigned long nonBlock = TRUE; \
1188 			ioctlsocket( socket, FIONBIO, &nonBlock ); \
1189 			}
1190   #define setSocketBlocking( socket ) \
1191 			{ \
1192 			unsigned long nonBlock = FALSE; \
1193 			ioctlsocket( socket, FIONBIO, &nonBlock ); \
1194 			}
1195 #elif defined( __AMX__ ) || defined( __BEOS__ )
1196   #define getSocketNonblockingStatus( socket, value ) \
1197 			{ \
1198 			int nonBlock = FALSE; \
1199 			value = getsockopt( socket, SOL_SOCKET, SO_NONBLOCK, &nonBlock, sizeof( int ) ); \
1200 			value = ( isSocketError( value ) || nonBlock ) ? \
1201 					TRUE : FALSE; \
1202 			}
1203   #define setSocketNonblocking( socket ) \
1204 			{ \
1205 			int nonBlock = TRUE; \
1206 			setsockopt( socket, SOL_SOCKET, SO_NONBLOCK, &nonBlock, sizeof( int ) ); \
1207 			}
1208   #define setSocketBlocking( socket ) \
1209 			{ \
1210 			int nonBlock = FALSE; \
1211 			setsockopt( socket, SOL_SOCKET, SO_NONBLOCK, &nonBlock, sizeof( int ) ); \
1212 			}
1213 #elif defined( __Nucleus__ )
1214   /* Nucleus doesn't provide a mechanism to check whether a socket is non-
1215      blocking, however the only time that this capability is required is
1216 	 when we're checking a user-provided socket.  These are created
1217 	 blocking by default under Nucleus, so we just hardwire the check to say
1218 	 that it's blocking */
1219   #define getSocketNonblockingStatus( socket, value )	value = FALSE
1220   #define setSocketNonblocking( socket ) \
1221 			NU_Fcntl( socket, NU_SETFLAG, NU_NO_BLOCK )
1222   #define setSocketBlocking( socket ) \
1223 			NU_Fcntl( socket, NU_SETFLAG, NU_BLOCK )
1224 #elif defined( __SYMBIAN32__ )
1225   /* Symbian OS doesn't support nonblocking I/O */
1226   #define getSocketNonblockingStatus( socket, value )	value = FALSE
1227   #define setSocketNonblocking( socket )
1228   #define setSocketBlocking( socket )
1229 #else
1230 `  #error Need to create macros to handle nonblocking I/O
1231 #endif /* Handling of blocking/nonblocking sockets */
1232 
1233 /****************************************************************************
1234 *																			*
1235 *						 	Misc.Functions and Defines						*
1236 *																			*
1237 ****************************************************************************/
1238 
1239 /* DNS dynamic-binding init/shutdown functions */
1240 
1241 #ifdef __WINDOWS__
1242   CHECK_RETVAL \
1243   int initDNS( const INSTANCE_HANDLE hTCP, const INSTANCE_HANDLE hAddr );
1244   void endDNS( const INSTANCE_HANDLE hTCP );
1245   #ifdef USE_DNSSRV
1246 	CHECK_RETVAL \
1247 	int initDNSSRV( const INSTANCE_HANDLE hTCP );
1248 	void endDNSSRV( const INSTANCE_HANDLE hTCP );
1249   #else
1250 	#define initDNSSRV( hTCP )		CRYPT_ERROR
1251 	#define endDNSSRV( hTCP )
1252   #endif /* USE_DNSSRV */
1253 #endif /* __WINDOWS__ */
1254 
1255 /* Prototypes for functions in dns.c */
1256 
1257 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2 ) ) \
1258 int getAddressInfo( INOUT NET_STREAM_INFO *netStream,
1259 					OUT_PTR_COND struct addrinfo **addrInfoPtrPtr,
1260 					IN_BUFFER_OPT( nameLen ) const char *name,
1261 					IN_LENGTH_Z const int nameLen,
1262 					IN_PORT const int port, const BOOLEAN isServer,
1263 					const BOOLEAN isStreamSocket );
1264 STDC_NONNULL_ARG( ( 1 ) ) \
1265 void freeAddressInfo( struct addrinfo *addrInfoPtr );
1266 STDC_NONNULL_ARG( ( 1, 3, 5, 6 ) ) \
1267 void getNameInfo( IN_BUFFER( sockAddrLen ) const void *sockAddr,
1268 				  IN_LENGTH_SHORT_MIN( 8 ) const int sockAddrLen,
1269 				  OUT_BUFFER( addressMaxLen, *addressLen ) char *address,
1270 				  IN_LENGTH_DNS const int addressMaxLen,
1271 				  OUT_LENGTH_BOUNDED_Z( addressMaxLen ) int *addressLen,
1272 				  OUT_PORT_Z int *port );
1273 
1274 /* Prototypes for functions in dns_srv.c */
1275 
1276 #ifdef USE_DNSSRV
1277   CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2, 4, 5 ) ) \
1278   int findHostInfo( INOUT NET_STREAM_INFO *netStream,
1279 					OUT_BUFFER_FIXED( hostNameMaxLen ) char *hostName,
1280 					IN_LENGTH_DNS const int hostNameMaxLen,
1281 					OUT_PORT_Z int *hostPort,
1282 					IN_BUFFER( nameLen ) const char *name,
1283 					IN_LENGTH_DNS const int nameLen );
1284 #else
1285   /* If there's no DNS support available in the OS there's not much that we
1286 	 can do to handle automatic host detection.  Setting hostPort as a side-
1287 	 effect is necessary because the #define otherwise no-ops it out,
1288 	 leading to declared-but-not-used warnings from some compilers */
1289   #define findHostInfo( netStream, hostName, hostNameLen, hostPort, name, nameLen )	\
1290 		  setSocketError( netStream, "DNS SRV services not available", 30, \
1291 						  CRYPT_ERROR_NOTAVAIL, FALSE ); \
1292 		  memset( hostName, 0, min( 16, hostNameLen ) ); \
1293 		  *( hostPort ) = 0
1294 #endif /* USE_DNSSRV */
1295 
1296 /* Prototypes for functions in tcp.c */
1297 
1298 CHECK_RETVAL STDC_NONNULL_ARG( ( 1 ) ) \
1299 int getSocketError( NET_STREAM_INFO *netStream,
1300 					IN_ERROR const int status,
1301 					OUT_INT_Z int *socketErrorCode );
1302 CHECK_RETVAL STDC_NONNULL_ARG( ( 1 ) ) \
1303 int getHostError( NET_STREAM_INFO *netStream, IN_ERROR const int status );
1304 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2 ) ) \
1305 int setSocketError( INOUT NET_STREAM_INFO *netStream,
1306 					IN_BUFFER( errorMessageLength ) const char *errorMessage,
1307 					IN_LENGTH_ERRORMESSAGE const int errorMessageLength,
1308 					IN_ERROR const int status, const BOOLEAN isFatal );
1309 
1310 #endif /* USE_TCP */
1311