VirtualBox

source: vbox/trunk/src/VBox/Runtime/r3/socket.cpp@ 49971

Last change on this file since 49971 was 48935, checked in by vboxsync, 11 years ago

Runtime: Whitespace and svn:keyword cleanups by scm.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 59.8 KB
Line 
1/* $Id: socket.cpp 48935 2013-10-07 21:19:37Z vboxsync $ */
2/** @file
3 * IPRT - Network Sockets.
4 */
5
6/*
7 * Copyright (C) 2006-2013 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 */
26
27
28/*******************************************************************************
29* Header Files *
30*******************************************************************************/
31#ifdef RT_OS_WINDOWS
32# include <winsock2.h>
33# include <ws2tcpip.h>
34#else /* !RT_OS_WINDOWS */
35# include <errno.h>
36# include <sys/select.h>
37# include <sys/stat.h>
38# include <sys/socket.h>
39# include <netinet/in.h>
40# include <netinet/tcp.h>
41# include <arpa/inet.h>
42# ifdef IPRT_WITH_TCPIP_V6
43# include <netinet6/in6.h>
44# endif
45# include <sys/un.h>
46# include <netdb.h>
47# include <unistd.h>
48# include <fcntl.h>
49# include <sys/uio.h>
50#endif /* !RT_OS_WINDOWS */
51#include <limits.h>
52
53#include "internal/iprt.h"
54#include <iprt/socket.h>
55
56#include <iprt/alloca.h>
57#include <iprt/asm.h>
58#include <iprt/assert.h>
59#include <iprt/ctype.h>
60#include <iprt/err.h>
61#include <iprt/mempool.h>
62#include <iprt/poll.h>
63#include <iprt/string.h>
64#include <iprt/thread.h>
65#include <iprt/time.h>
66#include <iprt/mem.h>
67#include <iprt/sg.h>
68#include <iprt/log.h>
69
70#include "internal/magics.h"
71#include "internal/socket.h"
72#include "internal/string.h"
73
74
75/*******************************************************************************
76* Defined Constants And Macros *
77*******************************************************************************/
78/* non-standard linux stuff (it seems). */
79#ifndef MSG_NOSIGNAL
80# define MSG_NOSIGNAL 0
81#endif
82
83/* Windows has different names for SHUT_XXX. */
84#ifndef SHUT_RDWR
85# ifdef SD_BOTH
86# define SHUT_RDWR SD_BOTH
87# else
88# define SHUT_RDWR 2
89# endif
90#endif
91#ifndef SHUT_WR
92# ifdef SD_SEND
93# define SHUT_WR SD_SEND
94# else
95# define SHUT_WR 1
96# endif
97#endif
98#ifndef SHUT_RD
99# ifdef SD_RECEIVE
100# define SHUT_RD SD_RECEIVE
101# else
102# define SHUT_RD 0
103# endif
104#endif
105
106/* fixup backlevel OSes. */
107#if defined(RT_OS_OS2) || defined(RT_OS_WINDOWS)
108# define socklen_t int
109#endif
110
111/** How many pending connection. */
112#define RTTCP_SERVER_BACKLOG 10
113
114/* Limit read and write sizes on Windows and OS/2. */
115#ifdef RT_OS_WINDOWS
116# define RTSOCKET_MAX_WRITE (INT_MAX / 2)
117# define RTSOCKET_MAX_READ (INT_MAX / 2)
118#elif defined(RT_OS_OS2)
119# define RTSOCKET_MAX_WRITE 0x10000
120# define RTSOCKET_MAX_READ 0x10000
121#endif
122
123
124/*******************************************************************************
125* Structures and Typedefs *
126*******************************************************************************/
127/**
128 * Socket handle data.
129 *
130 * This is mainly required for implementing RTPollSet on Windows.
131 */
132typedef struct RTSOCKETINT
133{
134 /** Magic number (RTSOCKET_MAGIC). */
135 uint32_t u32Magic;
136 /** Exclusive user count.
137 * This is used to prevent two threads from accessing the handle concurrently.
138 * It can be higher than 1 if this handle is reference multiple times in a
139 * polling set (Windows). */
140 uint32_t volatile cUsers;
141 /** The native socket handle. */
142 RTSOCKETNATIVE hNative;
143 /** Indicates whether the handle has been closed or not. */
144 bool volatile fClosed;
145 /** Indicates whether the socket is operating in blocking or non-blocking mode
146 * currently. */
147 bool fBlocking;
148#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
149 /** The pollset currently polling this socket. This is NIL if no one is
150 * polling. */
151 RTPOLLSET hPollSet;
152#endif
153#ifdef RT_OS_WINDOWS
154 /** The event semaphore we've associated with the socket handle.
155 * This is WSA_INVALID_EVENT if not done. */
156 WSAEVENT hEvent;
157 /** The events we're polling for. */
158 uint32_t fPollEvts;
159 /** The events we're currently subscribing to with WSAEventSelect.
160 * This is ZERO if we're currently not subscribing to anything. */
161 uint32_t fSubscribedEvts;
162 /** Saved events which are only posted once. */
163 uint32_t fEventsSaved;
164#endif /* RT_OS_WINDOWS */
165} RTSOCKETINT;
166
167
168/**
169 * Address union used internally for things like getpeername and getsockname.
170 */
171typedef union RTSOCKADDRUNION
172{
173 struct sockaddr Addr;
174 struct sockaddr_in IPv4;
175#ifdef IPRT_WITH_TCPIP_V6
176 struct sockaddr_in6 IPv6;
177#endif
178} RTSOCKADDRUNION;
179
180
181/**
182 * Get the last error as an iprt status code.
183 *
184 * @returns IPRT status code.
185 */
186DECLINLINE(int) rtSocketError(void)
187{
188#ifdef RT_OS_WINDOWS
189 return RTErrConvertFromWin32(WSAGetLastError());
190#else
191 return RTErrConvertFromErrno(errno);
192#endif
193}
194
195
196/**
197 * Resets the last error.
198 */
199DECLINLINE(void) rtSocketErrorReset(void)
200{
201#ifdef RT_OS_WINDOWS
202 WSASetLastError(0);
203#else
204 errno = 0;
205#endif
206}
207
208
209/**
210 * Get the last resolver error as an iprt status code.
211 *
212 * @returns iprt status code.
213 */
214int rtSocketResolverError(void)
215{
216#ifdef RT_OS_WINDOWS
217 return RTErrConvertFromWin32(WSAGetLastError());
218#else
219 switch (h_errno)
220 {
221 case HOST_NOT_FOUND:
222 return VERR_NET_HOST_NOT_FOUND;
223 case NO_DATA:
224 return VERR_NET_ADDRESS_NOT_AVAILABLE;
225 case NO_RECOVERY:
226 return VERR_IO_GEN_FAILURE;
227 case TRY_AGAIN:
228 return VERR_TRY_AGAIN;
229
230 default:
231 return VERR_UNRESOLVED_ERROR;
232 }
233#endif
234}
235
236
237/**
238 * Converts from a native socket address to a generic IPRT network address.
239 *
240 * @returns IPRT status code.
241 * @param pSrc The source address.
242 * @param cbSrc The size of the source address.
243 * @param pAddr Where to return the generic IPRT network
244 * address.
245 */
246static int rtSocketNetAddrFromAddr(RTSOCKADDRUNION const *pSrc, size_t cbSrc, PRTNETADDR pAddr)
247{
248 /*
249 * Convert the address.
250 */
251 if ( cbSrc == sizeof(struct sockaddr_in)
252 && pSrc->Addr.sa_family == AF_INET)
253 {
254 RT_ZERO(*pAddr);
255 pAddr->enmType = RTNETADDRTYPE_IPV4;
256 pAddr->uPort = RT_N2H_U16(pSrc->IPv4.sin_port);
257 pAddr->uAddr.IPv4.u = pSrc->IPv4.sin_addr.s_addr;
258 }
259#ifdef IPRT_WITH_TCPIP_V6
260 else if ( cbSrc == sizeof(struct sockaddr_in6)
261 && pSrc->Addr.sa_family == AF_INET6)
262 {
263 RT_ZERO(*pAddr);
264 pAddr->enmType = RTNETADDRTYPE_IPV6;
265 pAddr->uPort = RT_N2H_U16(pSrc->IPv6.sin6_port);
266 pAddr->uAddr.IPv6.au32[0] = pSrc->IPv6.sin6_addr.s6_addr32[0];
267 pAddr->uAddr.IPv6.au32[1] = pSrc->IPv6.sin6_addr.s6_addr32[1];
268 pAddr->uAddr.IPv6.au32[2] = pSrc->IPv6.sin6_addr.s6_addr32[2];
269 pAddr->uAddr.IPv6.au32[3] = pSrc->IPv6.sin6_addr.s6_addr32[3];
270 }
271#endif
272 else
273 return VERR_NET_ADDRESS_FAMILY_NOT_SUPPORTED;
274 return VINF_SUCCESS;
275}
276
277
278/**
279 * Converts from a generic IPRT network address to a native socket address.
280 *
281 * @returns IPRT status code.
282 * @param pAddr Pointer to the generic IPRT network address.
283 * @param pDst The source address.
284 * @param cbSrc The size of the source address.
285 * @param pcbAddr Where to store the size of the returned address.
286 * Optional
287 */
288static int rtSocketAddrFromNetAddr(PCRTNETADDR pAddr, RTSOCKADDRUNION *pDst, size_t cbDst, int *pcbAddr)
289{
290 RT_BZERO(pDst, cbDst);
291 if ( pAddr->enmType == RTNETADDRTYPE_IPV4
292 && cbDst >= sizeof(struct sockaddr_in))
293 {
294 pDst->Addr.sa_family = AF_INET;
295 pDst->IPv4.sin_port = RT_H2N_U16(pAddr->uPort);
296 pDst->IPv4.sin_addr.s_addr = pAddr->uAddr.IPv4.u;
297 if (pcbAddr)
298 *pcbAddr = sizeof(pDst->IPv4);
299 }
300#ifdef IPRT_WITH_TCPIP_V6
301 else if ( pAddr->enmType == RTNETADDRTYPE_IPV6
302 && cbDst >= sizeof(struct sockaddr_in6))
303 {
304 pDst->Addr.sa_family = AF_INET6;
305 pDst->IPv6.sin6_port = RT_H2N_U16(pAddr->uPort);
306 pSrc->IPv6.sin6_addr.s6_addr32[0] = pAddr->uAddr.IPv6.au32[0];
307 pSrc->IPv6.sin6_addr.s6_addr32[1] = pAddr->uAddr.IPv6.au32[1];
308 pSrc->IPv6.sin6_addr.s6_addr32[2] = pAddr->uAddr.IPv6.au32[2];
309 pSrc->IPv6.sin6_addr.s6_addr32[3] = pAddr->uAddr.IPv6.au32[3];
310 if (pcbAddr)
311 *pcbAddr = sizeof(pDst->IPv6);
312 }
313#endif
314 else
315 return VERR_NET_ADDRESS_FAMILY_NOT_SUPPORTED;
316 return VINF_SUCCESS;
317}
318
319
320/**
321 * Tries to lock the socket for exclusive usage by the calling thread.
322 *
323 * Call rtSocketUnlock() to unlock.
324 *
325 * @returns @c true if locked, @c false if not.
326 * @param pThis The socket structure.
327 */
328DECLINLINE(bool) rtSocketTryLock(RTSOCKETINT *pThis)
329{
330 return ASMAtomicCmpXchgU32(&pThis->cUsers, 1, 0);
331}
332
333
334/**
335 * Unlocks the socket.
336 *
337 * @param pThis The socket structure.
338 */
339DECLINLINE(void) rtSocketUnlock(RTSOCKETINT *pThis)
340{
341 ASMAtomicCmpXchgU32(&pThis->cUsers, 0, 1);
342}
343
344
345/**
346 * The slow path of rtSocketSwitchBlockingMode that does the actual switching.
347 *
348 * @returns IPRT status code.
349 * @param pThis The socket structure.
350 * @param fBlocking The desired mode of operation.
351 * @remarks Do not call directly.
352 */
353static int rtSocketSwitchBlockingModeSlow(RTSOCKETINT *pThis, bool fBlocking)
354{
355#ifdef RT_OS_WINDOWS
356 u_long uBlocking = fBlocking ? 0 : 1;
357 if (ioctlsocket(pThis->hNative, FIONBIO, &uBlocking))
358 return rtSocketError();
359
360#else
361 int fFlags = fcntl(pThis->hNative, F_GETFL, 0);
362 if (fFlags == -1)
363 return rtSocketError();
364
365 if (fBlocking)
366 fFlags &= ~O_NONBLOCK;
367 else
368 fFlags |= O_NONBLOCK;
369 if (fcntl(pThis->hNative, F_SETFL, fFlags) == -1)
370 return rtSocketError();
371#endif
372
373 pThis->fBlocking = fBlocking;
374 return VINF_SUCCESS;
375}
376
377
378/**
379 * Switches the socket to the desired blocking mode if necessary.
380 *
381 * The socket must be locked.
382 *
383 * @returns IPRT status code.
384 * @param pThis The socket structure.
385 * @param fBlocking The desired mode of operation.
386 */
387DECLINLINE(int) rtSocketSwitchBlockingMode(RTSOCKETINT *pThis, bool fBlocking)
388{
389 if (pThis->fBlocking != fBlocking)
390 return rtSocketSwitchBlockingModeSlow(pThis, fBlocking);
391 return VINF_SUCCESS;
392}
393
394
395/**
396 * Creates an IPRT socket handle for a native one.
397 *
398 * @returns IPRT status code.
399 * @param ppSocket Where to return the IPRT socket handle.
400 * @param hNative The native handle.
401 */
402int rtSocketCreateForNative(RTSOCKETINT **ppSocket, RTSOCKETNATIVE hNative)
403{
404 RTSOCKETINT *pThis = (RTSOCKETINT *)RTMemPoolAlloc(RTMEMPOOL_DEFAULT, sizeof(*pThis));
405 if (!pThis)
406 return VERR_NO_MEMORY;
407 pThis->u32Magic = RTSOCKET_MAGIC;
408 pThis->cUsers = 0;
409 pThis->hNative = hNative;
410 pThis->fClosed = false;
411 pThis->fBlocking = true;
412#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
413 pThis->hPollSet = NIL_RTPOLLSET;
414#endif
415#ifdef RT_OS_WINDOWS
416 pThis->hEvent = WSA_INVALID_EVENT;
417 pThis->fPollEvts = 0;
418 pThis->fSubscribedEvts = 0;
419#endif
420 *ppSocket = pThis;
421 return VINF_SUCCESS;
422}
423
424
425RTDECL(int) RTSocketFromNative(PRTSOCKET phSocket, RTHCINTPTR uNative)
426{
427 AssertReturn(uNative != NIL_RTSOCKETNATIVE, VERR_INVALID_PARAMETER);
428#ifndef RT_OS_WINDOWS
429 AssertReturn(uNative >= 0, VERR_INVALID_PARAMETER);
430#endif
431 AssertPtrReturn(phSocket, VERR_INVALID_POINTER);
432 return rtSocketCreateForNative(phSocket, uNative);
433}
434
435
436/**
437 * Wrapper around socket().
438 *
439 * @returns IPRT status code.
440 * @param phSocket Where to store the handle to the socket on
441 * success.
442 * @param iDomain The protocol family (PF_XXX).
443 * @param iType The socket type (SOCK_XXX).
444 * @param iProtocol Socket parameter, usually 0.
445 */
446int rtSocketCreate(PRTSOCKET phSocket, int iDomain, int iType, int iProtocol)
447{
448 /*
449 * Create the socket.
450 */
451 RTSOCKETNATIVE hNative = socket(iDomain, iType, iProtocol);
452 if (hNative == NIL_RTSOCKETNATIVE)
453 return rtSocketError();
454
455 /*
456 * Wrap it.
457 */
458 int rc = rtSocketCreateForNative(phSocket, hNative);
459 if (RT_FAILURE(rc))
460 {
461#ifdef RT_OS_WINDOWS
462 closesocket(hNative);
463#else
464 close(hNative);
465#endif
466 }
467 return rc;
468}
469
470
471RTDECL(uint32_t) RTSocketRetain(RTSOCKET hSocket)
472{
473 RTSOCKETINT *pThis = hSocket;
474 AssertPtrReturn(pThis, UINT32_MAX);
475 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, UINT32_MAX);
476 return RTMemPoolRetain(pThis);
477}
478
479
480/**
481 * Worker for RTSocketRelease and RTSocketClose.
482 *
483 * @returns IPRT status code.
484 * @param pThis The socket handle instance data.
485 * @param fDestroy Whether we're reaching ref count zero.
486 */
487static int rtSocketCloseIt(RTSOCKETINT *pThis, bool fDestroy)
488{
489 /*
490 * Invalidate the handle structure on destroy.
491 */
492 if (fDestroy)
493 {
494 Assert(ASMAtomicReadU32(&pThis->u32Magic) == RTSOCKET_MAGIC);
495 ASMAtomicWriteU32(&pThis->u32Magic, RTSOCKET_MAGIC_DEAD);
496 }
497
498 int rc = VINF_SUCCESS;
499 if (ASMAtomicCmpXchgBool(&pThis->fClosed, true, false))
500 {
501 /*
502 * Close the native handle.
503 */
504 RTSOCKETNATIVE hNative = pThis->hNative;
505 if (hNative != NIL_RTSOCKETNATIVE)
506 {
507 pThis->hNative = NIL_RTSOCKETNATIVE;
508
509#ifdef RT_OS_WINDOWS
510 if (closesocket(hNative))
511#else
512 if (close(hNative))
513#endif
514 {
515 rc = rtSocketError();
516#ifdef RT_OS_WINDOWS
517 AssertMsgFailed(("\"%s\": closesocket(%p) -> %Rrc\n", (uintptr_t)hNative, rc));
518#else
519 AssertMsgFailed(("\"%s\": close(%d) -> %Rrc\n", hNative, rc));
520#endif
521 }
522 }
523
524#ifdef RT_OS_WINDOWS
525 /*
526 * Close the event.
527 */
528 WSAEVENT hEvent = pThis->hEvent;
529 if (hEvent == WSA_INVALID_EVENT)
530 {
531 pThis->hEvent = WSA_INVALID_EVENT;
532 WSACloseEvent(hEvent);
533 }
534#endif
535 }
536
537 return rc;
538}
539
540
541RTDECL(uint32_t) RTSocketRelease(RTSOCKET hSocket)
542{
543 RTSOCKETINT *pThis = hSocket;
544 if (pThis == NIL_RTSOCKET)
545 return 0;
546 AssertPtrReturn(pThis, UINT32_MAX);
547 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, UINT32_MAX);
548
549 /* get the refcount without killing it... */
550 uint32_t cRefs = RTMemPoolRefCount(pThis);
551 AssertReturn(cRefs != UINT32_MAX, UINT32_MAX);
552 if (cRefs == 1)
553 rtSocketCloseIt(pThis, true);
554
555 return RTMemPoolRelease(RTMEMPOOL_DEFAULT, pThis);
556}
557
558
559RTDECL(int) RTSocketClose(RTSOCKET hSocket)
560{
561 RTSOCKETINT *pThis = hSocket;
562 if (pThis == NIL_RTSOCKET)
563 return VINF_SUCCESS;
564 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
565 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
566
567 uint32_t cRefs = RTMemPoolRefCount(pThis);
568 AssertReturn(cRefs != UINT32_MAX, UINT32_MAX);
569
570 int rc = rtSocketCloseIt(pThis, cRefs == 1);
571
572 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pThis);
573 return rc;
574}
575
576
577RTDECL(RTHCUINTPTR) RTSocketToNative(RTSOCKET hSocket)
578{
579 RTSOCKETINT *pThis = hSocket;
580 AssertPtrReturn(pThis, RTHCUINTPTR_MAX);
581 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, RTHCUINTPTR_MAX);
582 return (RTHCUINTPTR)pThis->hNative;
583}
584
585
586RTDECL(int) RTSocketSetInheritance(RTSOCKET hSocket, bool fInheritable)
587{
588 RTSOCKETINT *pThis = hSocket;
589 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
590 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
591 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
592
593 int rc = VINF_SUCCESS;
594#ifdef RT_OS_WINDOWS
595 if (!SetHandleInformation((HANDLE)pThis->hNative, HANDLE_FLAG_INHERIT, fInheritable ? HANDLE_FLAG_INHERIT : 0))
596 rc = RTErrConvertFromWin32(GetLastError());
597#else
598 if (fcntl(pThis->hNative, F_SETFD, fInheritable ? 0 : FD_CLOEXEC) < 0)
599 rc = RTErrConvertFromErrno(errno);
600#endif
601
602 return rc;
603}
604
605
606static bool rtSocketIsIPv4Numerical(const char *pszAddress, PRTNETADDRIPV4 pAddr)
607{
608
609 /* Empty address resolves to the INADDR_ANY address (good for bind). */
610 if (!pszAddress || !*pszAddress)
611 {
612 pAddr->u = INADDR_ANY;
613 return true;
614 }
615
616 /* Four quads? */
617 char *psz = (char *)pszAddress;
618 for (int i = 0; i < 4; i++)
619 {
620 uint8_t u8;
621 int rc = RTStrToUInt8Ex(psz, &psz, 0, &u8);
622 if (rc != VINF_SUCCESS && rc != VWRN_TRAILING_CHARS)
623 return false;
624 if (*psz != (i < 3 ? '.' : '\0'))
625 return false;
626 psz++;
627
628 pAddr->au8[i] = u8; /* big endian */
629 }
630
631 return true;
632}
633
634RTDECL(int) RTSocketParseInetAddress(const char *pszAddress, unsigned uPort, PRTNETADDR pAddr)
635{
636 int rc;
637
638 /*
639 * Validate input.
640 */
641 AssertReturn(uPort > 0, VERR_INVALID_PARAMETER);
642 AssertPtrNullReturn(pszAddress, VERR_INVALID_POINTER);
643
644#ifdef RT_OS_WINDOWS
645 /*
646 * Initialize WinSock and check version.
647 */
648 WORD wVersionRequested = MAKEWORD(1, 1);
649 WSADATA wsaData;
650 rc = WSAStartup(wVersionRequested, &wsaData);
651 if (wsaData.wVersion != wVersionRequested)
652 {
653 AssertMsgFailed(("Wrong winsock version\n"));
654 return VERR_NOT_SUPPORTED;
655 }
656#endif
657
658 /*
659 * Resolve the address. Pretty crude at the moment, but we have to make
660 * sure to not ask the NT 4 gethostbyname about an IPv4 address as it may
661 * give a wrong answer.
662 */
663 /** @todo this only supports IPv4, and IPv6 support needs to be added.
664 * It probably needs to be converted to getaddrinfo(). */
665 RTNETADDRIPV4 IPv4Quad;
666 if (rtSocketIsIPv4Numerical(pszAddress, &IPv4Quad))
667 {
668 Log3(("rtSocketIsIPv4Numerical: %#x (%RTnaipv4)\n", pszAddress, IPv4Quad.u, IPv4Quad));
669 RT_ZERO(*pAddr);
670 pAddr->enmType = RTNETADDRTYPE_IPV4;
671 pAddr->uPort = uPort;
672 pAddr->uAddr.IPv4 = IPv4Quad;
673 return VINF_SUCCESS;
674 }
675
676 struct hostent *pHostEnt;
677 pHostEnt = gethostbyname(pszAddress);
678 if (!pHostEnt)
679 {
680 rc = rtSocketResolverError();
681 AssertMsgFailed(("Could not resolve '%s', rc=%Rrc\n", pszAddress, rc));
682 return rc;
683 }
684
685 if (pHostEnt->h_addrtype == AF_INET)
686 {
687 RT_ZERO(*pAddr);
688 pAddr->enmType = RTNETADDRTYPE_IPV4;
689 pAddr->uPort = uPort;
690 pAddr->uAddr.IPv4.u = ((struct in_addr *)pHostEnt->h_addr)->s_addr;
691 Log3(("gethostbyname: %s -> %#x (%RTnaipv4)\n", pszAddress, pAddr->uAddr.IPv4.u, pAddr->uAddr.IPv4));
692 }
693 else
694 return VERR_NET_ADDRESS_FAMILY_NOT_SUPPORTED;
695
696 return VINF_SUCCESS;
697}
698
699
700/*
701 * New function to allow both ipv4 and ipv6 addresses to be resolved.
702 * Breaks compatibility with windows before 2000.
703 */
704RTDECL(int) RTSocketQueryAddressStr(const char *pszHost, char *pszResult, size_t *pcbResult, PRTNETADDRTYPE penmAddrType)
705{
706 AssertPtrReturn(pszHost, VERR_INVALID_POINTER);
707 AssertPtrReturn(pcbResult, VERR_INVALID_POINTER);
708 AssertPtrNullReturn(penmAddrType, VERR_INVALID_POINTER);
709 AssertPtrNullReturn(pszResult, VERR_INVALID_POINTER);
710
711#if defined(RT_OS_OS2) || defined(RT_OS_WINDOWS) /** @todo dynamically resolve the APIs not present in NT4! */
712 return VERR_NOT_SUPPORTED;
713
714#else
715 int rc;
716 if (*pcbResult < 16)
717 return VERR_NET_ADDRESS_NOT_AVAILABLE;
718
719 /* Setup the hint. */
720 struct addrinfo grHints;
721 RT_ZERO(grHints);
722 grHints.ai_socktype = 0;
723 grHints.ai_flags = 0;
724 grHints.ai_protocol = 0;
725 grHints.ai_family = AF_UNSPEC;
726 if (penmAddrType)
727 {
728 switch (*penmAddrType)
729 {
730 case RTNETADDRTYPE_INVALID:
731 /*grHints.ai_family = AF_UNSPEC;*/
732 break;
733 case RTNETADDRTYPE_IPV4:
734 grHints.ai_family = AF_INET;
735 break;
736 case RTNETADDRTYPE_IPV6:
737 grHints.ai_family = AF_INET6;
738 break;
739 default:
740 AssertFailedReturn(VERR_INVALID_PARAMETER);
741 }
742 }
743
744# ifdef RT_OS_WINDOWS
745 /*
746 * Winsock2 init
747 */
748 /** @todo someone should check if we really need 2, 2 here */
749 WORD wVersionRequested = MAKEWORD(2, 2);
750 WSADATA wsaData;
751 rc = WSAStartup(wVersionRequested, &wsaData);
752 if (wsaData.wVersion != wVersionRequested)
753 {
754 AssertMsgFailed(("Wrong winsock version\n"));
755 return VERR_NOT_SUPPORTED;
756 }
757# endif
758
759 /** @todo r=bird: getaddrinfo and freeaddrinfo breaks the additions on NT4. */
760 struct addrinfo *pgrResults = NULL;
761 rc = getaddrinfo(pszHost, "", &grHints, &pgrResults);
762 if (rc != 0)
763 return VERR_NET_ADDRESS_NOT_AVAILABLE;
764
765 // return data
766 // on multiple matches return only the first one
767
768 if (!pgrResults)
769 return VERR_NET_ADDRESS_NOT_AVAILABLE;
770
771 struct addrinfo const *pgrResult = pgrResults->ai_next;
772 if (!pgrResult)
773 {
774 freeaddrinfo(pgrResults);
775 return VERR_NET_ADDRESS_NOT_AVAILABLE;
776 }
777
778 uint8_t const *pbDummy;
779 RTNETADDRTYPE enmAddrType = RTNETADDRTYPE_INVALID;
780 size_t cchIpAddress;
781 char szIpAddress[48];
782 if (pgrResult->ai_family == AF_INET)
783 {
784 struct sockaddr_in const *pgrSa = (struct sockaddr_in const *)pgrResult->ai_addr;
785 pbDummy = (uint8_t const *)&pgrSa->sin_addr;
786 cchIpAddress = RTStrPrintf(szIpAddress, sizeof(szIpAddress), "%u.%u.%u.%u",
787 pbDummy[0], pbDummy[1], pbDummy[2], pbDummy[3]);
788 Assert(cchIpAddress >= 7 && cchIpAddress < sizeof(szIpAddress) - 1);
789 enmAddrType = RTNETADDRTYPE_IPV4;
790 rc = VINF_SUCCESS;
791 }
792 else if (pgrResult->ai_family == AF_INET6)
793 {
794 struct sockaddr_in6 const *pgrSa6 = (struct sockaddr_in6 const *)pgrResult->ai_addr;
795 pbDummy = (uint8_t const *) &pgrSa6->sin6_addr;
796 char szTmp[32+1];
797 size_t cchTmp = RTStrPrintf(szTmp, sizeof(szTmp),
798 "%02x%02x%02x%02x"
799 "%02x%02x%02x%02x"
800 "%02x%02x%02x%02x"
801 "%02x%02x%02x%02x",
802 pbDummy[0], pbDummy[1], pbDummy[2], pbDummy[3],
803 pbDummy[4], pbDummy[5], pbDummy[6], pbDummy[7],
804 pbDummy[8], pbDummy[9], pbDummy[10], pbDummy[11],
805 pbDummy[12], pbDummy[13], pbDummy[14], pbDummy[15]);
806 Assert(cchTmp == 32);
807 rc = rtStrToIpAddr6Str(szTmp, szIpAddress, sizeof(szIpAddress), NULL, 0, true);
808 if (RT_SUCCESS(rc))
809 cchIpAddress = strlen(szIpAddress);
810 else
811 {
812 szIpAddress[0] = '\0';
813 cchIpAddress = 0;
814 }
815 enmAddrType = RTNETADDRTYPE_IPV6;
816 }
817 else
818 {
819 rc = VERR_NET_ADDRESS_NOT_AVAILABLE;
820 szIpAddress[0] = '\0';
821 cchIpAddress = 0;
822 }
823 freeaddrinfo(pgrResults);
824
825 /*
826 * Copy out the result.
827 */
828 size_t const cbResult = *pcbResult;
829 *pcbResult = cchIpAddress + 1;
830 if (cchIpAddress < cbResult)
831 memcpy(pszResult, szIpAddress, cchIpAddress + 1);
832 else
833 {
834 RT_BZERO(pszResult, cbResult);
835 if (RT_SUCCESS(rc))
836 rc = VERR_BUFFER_OVERFLOW;
837 }
838 if (penmAddrType && RT_SUCCESS(rc))
839 *penmAddrType = enmAddrType;
840 return rc;
841#endif /* !RT_OS_OS2 */
842}
843
844
845RTDECL(int) RTSocketRead(RTSOCKET hSocket, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
846{
847 /*
848 * Validate input.
849 */
850 RTSOCKETINT *pThis = hSocket;
851 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
852 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
853 AssertReturn(cbBuffer > 0, VERR_INVALID_PARAMETER);
854 AssertPtr(pvBuffer);
855 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
856
857 int rc = rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
858 if (RT_FAILURE(rc))
859 return rc;
860
861 /*
862 * Read loop.
863 * If pcbRead is NULL we have to fill the entire buffer!
864 */
865 size_t cbRead = 0;
866 size_t cbToRead = cbBuffer;
867 for (;;)
868 {
869 rtSocketErrorReset();
870#ifdef RTSOCKET_MAX_READ
871 int cbNow = cbToRead >= RTSOCKET_MAX_READ ? RTSOCKET_MAX_READ : (int)cbToRead;
872#else
873 size_t cbNow = cbToRead;
874#endif
875 ssize_t cbBytesRead = recv(pThis->hNative, (char *)pvBuffer + cbRead, cbNow, MSG_NOSIGNAL);
876 if (cbBytesRead <= 0)
877 {
878 rc = rtSocketError();
879 Assert(RT_FAILURE_NP(rc) || cbBytesRead == 0);
880 if (RT_SUCCESS_NP(rc))
881 {
882 if (!pcbRead)
883 rc = VERR_NET_SHUTDOWN;
884 else
885 {
886 *pcbRead = 0;
887 rc = VINF_SUCCESS;
888 }
889 }
890 break;
891 }
892 if (pcbRead)
893 {
894 /* return partial data */
895 *pcbRead = cbBytesRead;
896 break;
897 }
898
899 /* read more? */
900 cbRead += cbBytesRead;
901 if (cbRead == cbBuffer)
902 break;
903
904 /* next */
905 cbToRead = cbBuffer - cbRead;
906 }
907
908 rtSocketUnlock(pThis);
909 return rc;
910}
911
912
913RTDECL(int) RTSocketReadFrom(RTSOCKET hSocket, void *pvBuffer, size_t cbBuffer, size_t *pcbRead, PRTNETADDR pSrcAddr)
914{
915 /*
916 * Validate input.
917 */
918 RTSOCKETINT *pThis = hSocket;
919 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
920 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
921 AssertReturn(cbBuffer > 0, VERR_INVALID_PARAMETER);
922 AssertPtr(pvBuffer);
923 AssertPtr(pcbRead);
924 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
925
926 int rc = rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
927 if (RT_FAILURE(rc))
928 return rc;
929
930 /*
931 * Read data.
932 */
933 size_t cbRead = 0;
934 size_t cbToRead = cbBuffer;
935 rtSocketErrorReset();
936 RTSOCKADDRUNION u;
937#ifdef RTSOCKET_MAX_READ
938 int cbNow = cbToRead >= RTSOCKET_MAX_READ ? RTSOCKET_MAX_READ : (int)cbToRead;
939 int cbAddr = sizeof(u);
940#else
941 size_t cbNow = cbToRead;
942 socklen_t cbAddr = sizeof(u);
943#endif
944 ssize_t cbBytesRead = recvfrom(pThis->hNative, (char *)pvBuffer + cbRead, cbNow, MSG_NOSIGNAL, &u.Addr, &cbAddr);
945 if (cbBytesRead <= 0)
946 {
947 rc = rtSocketError();
948 Assert(RT_FAILURE_NP(rc) || cbBytesRead == 0);
949 if (RT_SUCCESS_NP(rc))
950 {
951 *pcbRead = 0;
952 rc = VINF_SUCCESS;
953 }
954 }
955 else
956 {
957 if (pSrcAddr)
958 rc = rtSocketNetAddrFromAddr(&u, cbAddr, pSrcAddr);
959 *pcbRead = cbBytesRead;
960 }
961
962 rtSocketUnlock(pThis);
963 return rc;
964}
965
966
967RTDECL(int) RTSocketWrite(RTSOCKET hSocket, const void *pvBuffer, size_t cbBuffer)
968{
969 /*
970 * Validate input.
971 */
972 RTSOCKETINT *pThis = hSocket;
973 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
974 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
975 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
976
977 int rc = rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
978 if (RT_FAILURE(rc))
979 return rc;
980
981 /*
982 * Try write all at once.
983 */
984#ifdef RTSOCKET_MAX_WRITE
985 int cbNow = cbBuffer >= RTSOCKET_MAX_WRITE ? RTSOCKET_MAX_WRITE : (int)cbBuffer;
986#else
987 size_t cbNow = cbBuffer >= SSIZE_MAX ? SSIZE_MAX : cbBuffer;
988#endif
989 ssize_t cbWritten = send(pThis->hNative, (const char *)pvBuffer, cbNow, MSG_NOSIGNAL);
990 if (RT_LIKELY((size_t)cbWritten == cbBuffer && cbWritten >= 0))
991 rc = VINF_SUCCESS;
992 else if (cbWritten < 0)
993 rc = rtSocketError();
994 else
995 {
996 /*
997 * Unfinished business, write the remainder of the request. Must ignore
998 * VERR_INTERRUPTED here if we've managed to send something.
999 */
1000 size_t cbSentSoFar = 0;
1001 for (;;)
1002 {
1003 /* advance */
1004 cbBuffer -= (size_t)cbWritten;
1005 if (!cbBuffer)
1006 break;
1007 cbSentSoFar += (size_t)cbWritten;
1008 pvBuffer = (char const *)pvBuffer + cbWritten;
1009
1010 /* send */
1011#ifdef RTSOCKET_MAX_WRITE
1012 cbNow = cbBuffer >= RTSOCKET_MAX_WRITE ? RTSOCKET_MAX_WRITE : (int)cbBuffer;
1013#else
1014 cbNow = cbBuffer >= SSIZE_MAX ? SSIZE_MAX : cbBuffer;
1015#endif
1016 cbWritten = send(pThis->hNative, (const char *)pvBuffer, cbNow, MSG_NOSIGNAL);
1017 if (cbWritten >= 0)
1018 AssertMsg(cbBuffer >= (size_t)cbWritten, ("Wrote more than we requested!!! cbWritten=%zu cbBuffer=%zu rtSocketError()=%d\n",
1019 cbWritten, cbBuffer, rtSocketError()));
1020 else
1021 {
1022 rc = rtSocketError();
1023 if (rc != VERR_INTERNAL_ERROR || cbSentSoFar == 0)
1024 break;
1025 cbWritten = 0;
1026 rc = VINF_SUCCESS;
1027 }
1028 }
1029 }
1030
1031 rtSocketUnlock(pThis);
1032 return rc;
1033}
1034
1035
1036RTDECL(int) RTSocketWriteTo(RTSOCKET hSocket, const void *pvBuffer, size_t cbBuffer, PCRTNETADDR pAddr)
1037{
1038 /*
1039 * Validate input.
1040 */
1041 RTSOCKETINT *pThis = hSocket;
1042 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1043 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1044
1045 /* no locking since UDP reads may be done concurrently to writes, and
1046 * this is the normal use case of this code. */
1047
1048 int rc = rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
1049 if (RT_FAILURE(rc))
1050 return rc;
1051
1052 /* Figure out destination address. */
1053 struct sockaddr *pSA = NULL;
1054#ifdef RT_OS_WINDOWS
1055 int cbSA = 0;
1056#else
1057 socklen_t cbSA = 0;
1058#endif
1059 RTSOCKADDRUNION u;
1060 if (pAddr)
1061 {
1062 rc = rtSocketAddrFromNetAddr(pAddr, &u, sizeof(u), NULL);
1063 if (RT_FAILURE(rc))
1064 return rc;
1065 pSA = &u.Addr;
1066 cbSA = sizeof(u);
1067 }
1068
1069 /*
1070 * Must write all at once, otherwise it is a failure.
1071 */
1072#ifdef RT_OS_WINDOWS
1073 int cbNow = cbBuffer >= RTSOCKET_MAX_WRITE ? RTSOCKET_MAX_WRITE : (int)cbBuffer;
1074#else
1075 size_t cbNow = cbBuffer >= SSIZE_MAX ? SSIZE_MAX : cbBuffer;
1076#endif
1077 ssize_t cbWritten = sendto(pThis->hNative, (const char *)pvBuffer, cbNow, MSG_NOSIGNAL, pSA, cbSA);
1078 if (RT_LIKELY((size_t)cbWritten == cbBuffer && cbWritten >= 0))
1079 rc = VINF_SUCCESS;
1080 else if (cbWritten < 0)
1081 rc = rtSocketError();
1082 else
1083 rc = VERR_TOO_MUCH_DATA;
1084
1085 rtSocketUnlock(pThis);
1086 return rc;
1087}
1088
1089
1090RTDECL(int) RTSocketSgWrite(RTSOCKET hSocket, PCRTSGBUF pSgBuf)
1091{
1092 /*
1093 * Validate input.
1094 */
1095 RTSOCKETINT *pThis = hSocket;
1096 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1097 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1098 AssertPtrReturn(pSgBuf, VERR_INVALID_PARAMETER);
1099 AssertReturn(pSgBuf->cSegs > 0, VERR_INVALID_PARAMETER);
1100 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1101
1102 int rc = rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
1103 if (RT_FAILURE(rc))
1104 return rc;
1105
1106 /*
1107 * Construct message descriptor (translate pSgBuf) and send it.
1108 */
1109 rc = VERR_NO_TMP_MEMORY;
1110#ifdef RT_OS_WINDOWS
1111 AssertCompileSize(WSABUF, sizeof(RTSGSEG));
1112 AssertCompileMemberSize(WSABUF, buf, RT_SIZEOFMEMB(RTSGSEG, pvSeg));
1113
1114 LPWSABUF paMsg = (LPWSABUF)RTMemTmpAllocZ(pSgBuf->cSegs * sizeof(WSABUF));
1115 if (paMsg)
1116 {
1117 for (unsigned i = 0; i < pSgBuf->cSegs; i++)
1118 {
1119 paMsg[i].buf = (char *)pSgBuf->paSegs[i].pvSeg;
1120 paMsg[i].len = (u_long)pSgBuf->paSegs[i].cbSeg;
1121 }
1122
1123 DWORD dwSent;
1124 int hrc = WSASend(pThis->hNative, paMsg, pSgBuf->cSegs, &dwSent,
1125 MSG_NOSIGNAL, NULL, NULL);
1126 if (!hrc)
1127 rc = VINF_SUCCESS;
1128/** @todo check for incomplete writes */
1129 else
1130 rc = rtSocketError();
1131
1132 RTMemTmpFree(paMsg);
1133 }
1134
1135#else /* !RT_OS_WINDOWS */
1136 AssertCompileSize(struct iovec, sizeof(RTSGSEG));
1137 AssertCompileMemberSize(struct iovec, iov_base, RT_SIZEOFMEMB(RTSGSEG, pvSeg));
1138 AssertCompileMemberSize(struct iovec, iov_len, RT_SIZEOFMEMB(RTSGSEG, cbSeg));
1139
1140 struct iovec *paMsg = (struct iovec *)RTMemTmpAllocZ(pSgBuf->cSegs * sizeof(struct iovec));
1141 if (paMsg)
1142 {
1143 for (unsigned i = 0; i < pSgBuf->cSegs; i++)
1144 {
1145 paMsg[i].iov_base = pSgBuf->paSegs[i].pvSeg;
1146 paMsg[i].iov_len = pSgBuf->paSegs[i].cbSeg;
1147 }
1148
1149 struct msghdr msgHdr;
1150 RT_ZERO(msgHdr);
1151 msgHdr.msg_iov = paMsg;
1152 msgHdr.msg_iovlen = pSgBuf->cSegs;
1153 ssize_t cbWritten = sendmsg(pThis->hNative, &msgHdr, MSG_NOSIGNAL);
1154 if (RT_LIKELY(cbWritten >= 0))
1155 rc = VINF_SUCCESS;
1156/** @todo check for incomplete writes */
1157 else
1158 rc = rtSocketError();
1159
1160 RTMemTmpFree(paMsg);
1161 }
1162#endif /* !RT_OS_WINDOWS */
1163
1164 rtSocketUnlock(pThis);
1165 return rc;
1166}
1167
1168
1169RTDECL(int) RTSocketSgWriteL(RTSOCKET hSocket, size_t cSegs, ...)
1170{
1171 va_list va;
1172 va_start(va, cSegs);
1173 int rc = RTSocketSgWriteLV(hSocket, cSegs, va);
1174 va_end(va);
1175 return rc;
1176}
1177
1178
1179RTDECL(int) RTSocketSgWriteLV(RTSOCKET hSocket, size_t cSegs, va_list va)
1180{
1181 /*
1182 * Set up a S/G segment array + buffer on the stack and pass it
1183 * on to RTSocketSgWrite.
1184 */
1185 Assert(cSegs <= 16);
1186 PRTSGSEG paSegs = (PRTSGSEG)alloca(cSegs * sizeof(RTSGSEG));
1187 AssertReturn(paSegs, VERR_NO_TMP_MEMORY);
1188 for (size_t i = 0; i < cSegs; i++)
1189 {
1190 paSegs[i].pvSeg = va_arg(va, void *);
1191 paSegs[i].cbSeg = va_arg(va, size_t);
1192 }
1193
1194 RTSGBUF SgBuf;
1195 RTSgBufInit(&SgBuf, paSegs, cSegs);
1196 return RTSocketSgWrite(hSocket, &SgBuf);
1197}
1198
1199
1200RTDECL(int) RTSocketReadNB(RTSOCKET hSocket, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
1201{
1202 /*
1203 * Validate input.
1204 */
1205 RTSOCKETINT *pThis = hSocket;
1206 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1207 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1208 AssertReturn(cbBuffer > 0, VERR_INVALID_PARAMETER);
1209 AssertPtr(pvBuffer);
1210 AssertPtrReturn(pcbRead, VERR_INVALID_PARAMETER);
1211 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1212
1213 int rc = rtSocketSwitchBlockingMode(pThis, false /* fBlocking */);
1214 if (RT_FAILURE(rc))
1215 return rc;
1216
1217 rtSocketErrorReset();
1218#ifdef RTSOCKET_MAX_READ
1219 int cbNow = cbBuffer >= RTSOCKET_MAX_WRITE ? RTSOCKET_MAX_WRITE : (int)cbBuffer;
1220#else
1221 size_t cbNow = cbBuffer;
1222#endif
1223
1224#ifdef RT_OS_WINDOWS
1225 int cbRead = recv(pThis->hNative, (char *)pvBuffer, cbNow, MSG_NOSIGNAL);
1226 if (cbRead >= 0)
1227 {
1228 *pcbRead = cbRead;
1229 rc = VINF_SUCCESS;
1230 }
1231 else
1232 rc = rtSocketError();
1233
1234 if (rc == VERR_TRY_AGAIN)
1235 rc = VINF_TRY_AGAIN;
1236#else
1237 ssize_t cbRead = recv(pThis->hNative, pvBuffer, cbNow, MSG_NOSIGNAL);
1238 if (cbRead >= 0)
1239 *pcbRead = cbRead;
1240 else if (errno == EAGAIN)
1241 {
1242 *pcbRead = 0;
1243 rc = VINF_TRY_AGAIN;
1244 }
1245 else
1246 rc = rtSocketError();
1247#endif
1248
1249 rtSocketUnlock(pThis);
1250 return rc;
1251}
1252
1253
1254RTDECL(int) RTSocketWriteNB(RTSOCKET hSocket, const void *pvBuffer, size_t cbBuffer, size_t *pcbWritten)
1255{
1256 /*
1257 * Validate input.
1258 */
1259 RTSOCKETINT *pThis = hSocket;
1260 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1261 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1262 AssertPtrReturn(pcbWritten, VERR_INVALID_PARAMETER);
1263 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1264
1265 int rc = rtSocketSwitchBlockingMode(pThis, false /* fBlocking */);
1266 if (RT_FAILURE(rc))
1267 return rc;
1268
1269 rtSocketErrorReset();
1270#ifdef RTSOCKET_MAX_WRITE
1271 int cbNow = cbBuffer >= RTSOCKET_MAX_WRITE ? RTSOCKET_MAX_WRITE : (int)cbBuffer;
1272#else
1273 size_t cbNow = cbBuffer;
1274#endif
1275
1276#ifdef RT_OS_WINDOWS
1277 int cbWritten = send(pThis->hNative, (const char *)pvBuffer, cbNow, MSG_NOSIGNAL);
1278 if (cbWritten >= 0)
1279 {
1280 *pcbWritten = cbWritten;
1281 rc = VINF_SUCCESS;
1282 }
1283 else
1284 rc = rtSocketError();
1285
1286 if (rc == VERR_TRY_AGAIN)
1287 rc = VINF_TRY_AGAIN;
1288#else
1289 ssize_t cbWritten = send(pThis->hNative, pvBuffer, cbBuffer, MSG_NOSIGNAL);
1290 if (cbWritten >= 0)
1291 *pcbWritten = cbWritten;
1292 else if (errno == EAGAIN)
1293 {
1294 *pcbWritten = 0;
1295 rc = VINF_TRY_AGAIN;
1296 }
1297 else
1298 rc = rtSocketError();
1299#endif
1300
1301 rtSocketUnlock(pThis);
1302 return rc;
1303}
1304
1305
1306RTDECL(int) RTSocketSgWriteNB(RTSOCKET hSocket, PCRTSGBUF pSgBuf, size_t *pcbWritten)
1307{
1308 /*
1309 * Validate input.
1310 */
1311 RTSOCKETINT *pThis = hSocket;
1312 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1313 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1314 AssertPtrReturn(pSgBuf, VERR_INVALID_PARAMETER);
1315 AssertPtrReturn(pcbWritten, VERR_INVALID_PARAMETER);
1316 AssertReturn(pSgBuf->cSegs > 0, VERR_INVALID_PARAMETER);
1317 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1318
1319 int rc = rtSocketSwitchBlockingMode(pThis, false /* fBlocking */);
1320 if (RT_FAILURE(rc))
1321 return rc;
1322
1323 unsigned cSegsToSend = 0;
1324 rc = VERR_NO_TMP_MEMORY;
1325#ifdef RT_OS_WINDOWS
1326 LPWSABUF paMsg = NULL;
1327
1328 RTSgBufMapToNative(paMsg, pSgBuf, WSABUF, buf, char *, len, u_long, cSegsToSend);
1329 if (paMsg)
1330 {
1331 DWORD dwSent = 0;
1332 int hrc = WSASend(pThis->hNative, paMsg, cSegsToSend, &dwSent,
1333 MSG_NOSIGNAL, NULL, NULL);
1334 if (!hrc)
1335 rc = VINF_SUCCESS;
1336 else
1337 rc = rtSocketError();
1338
1339 *pcbWritten = dwSent;
1340
1341 RTMemTmpFree(paMsg);
1342 }
1343
1344#else /* !RT_OS_WINDOWS */
1345 struct iovec *paMsg = NULL;
1346
1347 RTSgBufMapToNative(paMsg, pSgBuf, struct iovec, iov_base, void *, iov_len, size_t, cSegsToSend);
1348 if (paMsg)
1349 {
1350 struct msghdr msgHdr;
1351 RT_ZERO(msgHdr);
1352 msgHdr.msg_iov = paMsg;
1353 msgHdr.msg_iovlen = cSegsToSend;
1354 ssize_t cbWritten = sendmsg(pThis->hNative, &msgHdr, MSG_NOSIGNAL);
1355 if (RT_LIKELY(cbWritten >= 0))
1356 {
1357 rc = VINF_SUCCESS;
1358 *pcbWritten = cbWritten;
1359 }
1360 else
1361 rc = rtSocketError();
1362
1363 RTMemTmpFree(paMsg);
1364 }
1365#endif /* !RT_OS_WINDOWS */
1366
1367 rtSocketUnlock(pThis);
1368 return rc;
1369}
1370
1371
1372RTDECL(int) RTSocketSgWriteLNB(RTSOCKET hSocket, size_t cSegs, size_t *pcbWritten, ...)
1373{
1374 va_list va;
1375 va_start(va, pcbWritten);
1376 int rc = RTSocketSgWriteLVNB(hSocket, cSegs, pcbWritten, va);
1377 va_end(va);
1378 return rc;
1379}
1380
1381
1382RTDECL(int) RTSocketSgWriteLVNB(RTSOCKET hSocket, size_t cSegs, size_t *pcbWritten, va_list va)
1383{
1384 /*
1385 * Set up a S/G segment array + buffer on the stack and pass it
1386 * on to RTSocketSgWrite.
1387 */
1388 Assert(cSegs <= 16);
1389 PRTSGSEG paSegs = (PRTSGSEG)alloca(cSegs * sizeof(RTSGSEG));
1390 AssertReturn(paSegs, VERR_NO_TMP_MEMORY);
1391 for (size_t i = 0; i < cSegs; i++)
1392 {
1393 paSegs[i].pvSeg = va_arg(va, void *);
1394 paSegs[i].cbSeg = va_arg(va, size_t);
1395 }
1396
1397 RTSGBUF SgBuf;
1398 RTSgBufInit(&SgBuf, paSegs, cSegs);
1399 return RTSocketSgWriteNB(hSocket, &SgBuf, pcbWritten);
1400}
1401
1402
1403RTDECL(int) RTSocketSelectOne(RTSOCKET hSocket, RTMSINTERVAL cMillies)
1404{
1405 /*
1406 * Validate input.
1407 */
1408 RTSOCKETINT *pThis = hSocket;
1409 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1410 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1411 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
1412 int const fdMax = (int)pThis->hNative + 1;
1413 AssertReturn(fdMax - 1 == pThis->hNative, VERR_INTERNAL_ERROR_5);
1414
1415 /*
1416 * Set up the file descriptor sets and do the select.
1417 */
1418 fd_set fdsetR;
1419 FD_ZERO(&fdsetR);
1420 FD_SET(pThis->hNative, &fdsetR);
1421
1422 fd_set fdsetE = fdsetR;
1423
1424 int rc;
1425 if (cMillies == RT_INDEFINITE_WAIT)
1426 rc = select(fdMax, &fdsetR, NULL, &fdsetE, NULL);
1427 else
1428 {
1429 struct timeval timeout;
1430 timeout.tv_sec = cMillies / 1000;
1431 timeout.tv_usec = (cMillies % 1000) * 1000;
1432 rc = select(fdMax, &fdsetR, NULL, &fdsetE, &timeout);
1433 }
1434 if (rc > 0)
1435 rc = VINF_SUCCESS;
1436 else if (rc == 0)
1437 rc = VERR_TIMEOUT;
1438 else
1439 rc = rtSocketError();
1440
1441 return rc;
1442}
1443
1444
1445RTDECL(int) RTSocketSelectOneEx(RTSOCKET hSocket, uint32_t fEvents, uint32_t *pfEvents,
1446 RTMSINTERVAL cMillies)
1447{
1448 /*
1449 * Validate input.
1450 */
1451 RTSOCKETINT *pThis = hSocket;
1452 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1453 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1454 AssertPtrReturn(pfEvents, VERR_INVALID_PARAMETER);
1455 AssertReturn(!(fEvents & ~RTSOCKET_EVT_VALID_MASK), VERR_INVALID_PARAMETER);
1456 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
1457 int const fdMax = (int)pThis->hNative + 1;
1458 AssertReturn(fdMax - 1 == pThis->hNative, VERR_INTERNAL_ERROR_5);
1459
1460 *pfEvents = 0;
1461
1462 /*
1463 * Set up the file descriptor sets and do the select.
1464 */
1465 fd_set fdsetR;
1466 fd_set fdsetW;
1467 fd_set fdsetE;
1468 FD_ZERO(&fdsetR);
1469 FD_ZERO(&fdsetW);
1470 FD_ZERO(&fdsetE);
1471
1472 if (fEvents & RTSOCKET_EVT_READ)
1473 FD_SET(pThis->hNative, &fdsetR);
1474 if (fEvents & RTSOCKET_EVT_WRITE)
1475 FD_SET(pThis->hNative, &fdsetW);
1476 if (fEvents & RTSOCKET_EVT_ERROR)
1477 FD_SET(pThis->hNative, &fdsetE);
1478
1479 int rc;
1480 if (cMillies == RT_INDEFINITE_WAIT)
1481 rc = select(fdMax, &fdsetR, &fdsetW, &fdsetE, NULL);
1482 else
1483 {
1484 struct timeval timeout;
1485 timeout.tv_sec = cMillies / 1000;
1486 timeout.tv_usec = (cMillies % 1000) * 1000;
1487 rc = select(fdMax, &fdsetR, &fdsetW, &fdsetE, &timeout);
1488 }
1489 if (rc > 0)
1490 {
1491 if (FD_ISSET(pThis->hNative, &fdsetR))
1492 *pfEvents |= RTSOCKET_EVT_READ;
1493 if (FD_ISSET(pThis->hNative, &fdsetW))
1494 *pfEvents |= RTSOCKET_EVT_WRITE;
1495 if (FD_ISSET(pThis->hNative, &fdsetE))
1496 *pfEvents |= RTSOCKET_EVT_ERROR;
1497
1498 rc = VINF_SUCCESS;
1499 }
1500 else if (rc == 0)
1501 rc = VERR_TIMEOUT;
1502 else
1503 rc = rtSocketError();
1504
1505 return rc;
1506}
1507
1508
1509RTDECL(int) RTSocketShutdown(RTSOCKET hSocket, bool fRead, bool fWrite)
1510{
1511 /*
1512 * Validate input, don't lock it because we might want to interrupt a call
1513 * active on a different thread.
1514 */
1515 RTSOCKETINT *pThis = hSocket;
1516 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1517 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1518 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
1519 AssertReturn(fRead || fWrite, VERR_INVALID_PARAMETER);
1520
1521 /*
1522 * Do the job.
1523 */
1524 int rc = VINF_SUCCESS;
1525 int fHow;
1526 if (fRead && fWrite)
1527 fHow = SHUT_RDWR;
1528 else if (fRead)
1529 fHow = SHUT_RD;
1530 else
1531 fHow = SHUT_WR;
1532 if (shutdown(pThis->hNative, fHow) == -1)
1533 rc = rtSocketError();
1534
1535 return rc;
1536}
1537
1538
1539RTDECL(int) RTSocketGetLocalAddress(RTSOCKET hSocket, PRTNETADDR pAddr)
1540{
1541 /*
1542 * Validate input.
1543 */
1544 RTSOCKETINT *pThis = hSocket;
1545 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1546 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1547 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
1548
1549 /*
1550 * Get the address and convert it.
1551 */
1552 int rc;
1553 RTSOCKADDRUNION u;
1554#ifdef RT_OS_WINDOWS
1555 int cbAddr = sizeof(u);
1556#else
1557 socklen_t cbAddr = sizeof(u);
1558#endif
1559 RT_ZERO(u);
1560 if (getsockname(pThis->hNative, &u.Addr, &cbAddr) == 0)
1561 rc = rtSocketNetAddrFromAddr(&u, cbAddr, pAddr);
1562 else
1563 rc = rtSocketError();
1564
1565 return rc;
1566}
1567
1568
1569RTDECL(int) RTSocketGetPeerAddress(RTSOCKET hSocket, PRTNETADDR pAddr)
1570{
1571 /*
1572 * Validate input.
1573 */
1574 RTSOCKETINT *pThis = hSocket;
1575 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1576 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1577 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
1578
1579 /*
1580 * Get the address and convert it.
1581 */
1582 int rc;
1583 RTSOCKADDRUNION u;
1584#ifdef RT_OS_WINDOWS
1585 int cbAddr = sizeof(u);
1586#else
1587 socklen_t cbAddr = sizeof(u);
1588#endif
1589 RT_ZERO(u);
1590 if (getpeername(pThis->hNative, &u.Addr, &cbAddr) == 0)
1591 rc = rtSocketNetAddrFromAddr(&u, cbAddr, pAddr);
1592 else
1593 rc = rtSocketError();
1594
1595 return rc;
1596}
1597
1598
1599
1600/**
1601 * Wrapper around bind.
1602 *
1603 * @returns IPRT status code.
1604 * @param hSocket The socket handle.
1605 * @param pAddr The address to bind to.
1606 */
1607int rtSocketBind(RTSOCKET hSocket, PCRTNETADDR pAddr)
1608{
1609 /*
1610 * Validate input.
1611 */
1612 RTSOCKETINT *pThis = hSocket;
1613 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1614 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1615 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1616
1617 RTSOCKADDRUNION u;
1618 int cbAddr;
1619 int rc = rtSocketAddrFromNetAddr(pAddr, &u, sizeof(u), &cbAddr);
1620 if (RT_SUCCESS(rc))
1621 {
1622 if (bind(pThis->hNative, &u.Addr, cbAddr) != 0)
1623 rc = rtSocketError();
1624 }
1625
1626 rtSocketUnlock(pThis);
1627 return rc;
1628}
1629
1630
1631/**
1632 * Wrapper around listen.
1633 *
1634 * @returns IPRT status code.
1635 * @param hSocket The socket handle.
1636 * @param cMaxPending The max number of pending connections.
1637 */
1638int rtSocketListen(RTSOCKET hSocket, int cMaxPending)
1639{
1640 /*
1641 * Validate input.
1642 */
1643 RTSOCKETINT *pThis = hSocket;
1644 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1645 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1646 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1647
1648 int rc = VINF_SUCCESS;
1649 if (listen(pThis->hNative, cMaxPending) != 0)
1650 rc = rtSocketError();
1651
1652 rtSocketUnlock(pThis);
1653 return rc;
1654}
1655
1656
1657/**
1658 * Wrapper around accept.
1659 *
1660 * @returns IPRT status code.
1661 * @param hSocket The socket handle.
1662 * @param phClient Where to return the client socket handle on
1663 * success.
1664 * @param pAddr Where to return the client address.
1665 * @param pcbAddr On input this gives the size buffer size of what
1666 * @a pAddr point to. On return this contains the
1667 * size of what's stored at @a pAddr.
1668 */
1669int rtSocketAccept(RTSOCKET hSocket, PRTSOCKET phClient, struct sockaddr *pAddr, size_t *pcbAddr)
1670{
1671 /*
1672 * Validate input.
1673 * Only lock the socket temporarily while we get the native handle, so that
1674 * we can safely shutdown and destroy the socket from a different thread.
1675 */
1676 RTSOCKETINT *pThis = hSocket;
1677 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1678 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1679 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1680
1681 /*
1682 * Call accept().
1683 */
1684 rtSocketErrorReset();
1685 int rc = VINF_SUCCESS;
1686#ifdef RT_OS_WINDOWS
1687 int cbAddr = (int)*pcbAddr;
1688#else
1689 socklen_t cbAddr = *pcbAddr;
1690#endif
1691 RTSOCKETNATIVE hNativeClient = accept(pThis->hNative, pAddr, &cbAddr);
1692 if (hNativeClient != NIL_RTSOCKETNATIVE)
1693 {
1694 *pcbAddr = cbAddr;
1695
1696 /*
1697 * Wrap the client socket.
1698 */
1699 rc = rtSocketCreateForNative(phClient, hNativeClient);
1700 if (RT_FAILURE(rc))
1701 {
1702#ifdef RT_OS_WINDOWS
1703 closesocket(hNativeClient);
1704#else
1705 close(hNativeClient);
1706#endif
1707 }
1708 }
1709 else
1710 rc = rtSocketError();
1711
1712 rtSocketUnlock(pThis);
1713 return rc;
1714}
1715
1716
1717/**
1718 * Wrapper around connect.
1719 *
1720 * @returns IPRT status code.
1721 * @param hSocket The socket handle.
1722 * @param pAddr The socket address to connect to.
1723 */
1724int rtSocketConnect(RTSOCKET hSocket, PCRTNETADDR pAddr)
1725{
1726 /*
1727 * Validate input.
1728 */
1729 RTSOCKETINT *pThis = hSocket;
1730 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1731 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1732 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1733
1734 RTSOCKADDRUNION u;
1735 int cbAddr;
1736 int rc = rtSocketAddrFromNetAddr(pAddr, &u, sizeof(u), &cbAddr);
1737 if (RT_SUCCESS(rc))
1738 {
1739 if (connect(pThis->hNative, &u.Addr, cbAddr) != 0)
1740 rc = rtSocketError();
1741 }
1742
1743 rtSocketUnlock(pThis);
1744 return rc;
1745}
1746
1747
1748/**
1749 * Wrapper around setsockopt.
1750 *
1751 * @returns IPRT status code.
1752 * @param hSocket The socket handle.
1753 * @param iLevel The protocol level, e.g. IPPORTO_TCP.
1754 * @param iOption The option, e.g. TCP_NODELAY.
1755 * @param pvValue The value buffer.
1756 * @param cbValue The size of the value pointed to by pvValue.
1757 */
1758int rtSocketSetOpt(RTSOCKET hSocket, int iLevel, int iOption, void const *pvValue, int cbValue)
1759{
1760 /*
1761 * Validate input.
1762 */
1763 RTSOCKETINT *pThis = hSocket;
1764 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1765 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1766 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1767
1768 int rc = VINF_SUCCESS;
1769 if (setsockopt(pThis->hNative, iLevel, iOption, (const char *)pvValue, cbValue) != 0)
1770 rc = rtSocketError();
1771
1772 rtSocketUnlock(pThis);
1773 return rc;
1774}
1775
1776
1777/**
1778 * Internal RTPollSetAdd helper that returns the handle that should be added to
1779 * the pollset.
1780 *
1781 * @returns Valid handle on success, INVALID_HANDLE_VALUE on failure.
1782 * @param hSocket The socket handle.
1783 * @param fEvents The events we're polling for.
1784 * @param phNative Where to put the primary handle.
1785 */
1786int rtSocketPollGetHandle(RTSOCKET hSocket, uint32_t fEvents, PRTHCINTPTR phNative)
1787{
1788 RTSOCKETINT *pThis = hSocket;
1789 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1790 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1791#ifdef RT_OS_WINDOWS
1792 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1793
1794 int rc = VINF_SUCCESS;
1795 if (pThis->hEvent != WSA_INVALID_EVENT)
1796 *phNative = (RTHCINTPTR)pThis->hEvent;
1797 else
1798 {
1799 pThis->hEvent = WSACreateEvent();
1800 *phNative = (RTHCINTPTR)pThis->hEvent;
1801 if (pThis->hEvent == WSA_INVALID_EVENT)
1802 rc = rtSocketError();
1803 }
1804
1805 rtSocketUnlock(pThis);
1806 return rc;
1807
1808#else /* !RT_OS_WINDOWS */
1809 *phNative = (RTHCUINTPTR)pThis->hNative;
1810 return VINF_SUCCESS;
1811#endif /* !RT_OS_WINDOWS */
1812}
1813
1814#ifdef RT_OS_WINDOWS
1815
1816/**
1817 * Undos the harm done by WSAEventSelect.
1818 *
1819 * @returns IPRT status code.
1820 * @param pThis The socket handle.
1821 */
1822static int rtSocketPollClearEventAndRestoreBlocking(RTSOCKETINT *pThis)
1823{
1824 int rc = VINF_SUCCESS;
1825 if (pThis->fSubscribedEvts)
1826 {
1827 if (WSAEventSelect(pThis->hNative, WSA_INVALID_EVENT, 0) == 0)
1828 {
1829 pThis->fSubscribedEvts = 0;
1830
1831 /*
1832 * Switch back to blocking mode if that was the state before the
1833 * operation.
1834 */
1835 if (pThis->fBlocking)
1836 {
1837 u_long fNonBlocking = 0;
1838 int rc2 = ioctlsocket(pThis->hNative, FIONBIO, &fNonBlocking);
1839 if (rc2 != 0)
1840 {
1841 rc = rtSocketError();
1842 AssertMsgFailed(("%Rrc; rc2=%d\n", rc, rc2));
1843 }
1844 }
1845 }
1846 else
1847 {
1848 rc = rtSocketError();
1849 AssertMsgFailed(("%Rrc\n", rc));
1850 }
1851 }
1852 return rc;
1853}
1854
1855
1856/**
1857 * Updates the mask of events we're subscribing to.
1858 *
1859 * @returns IPRT status code.
1860 * @param pThis The socket handle.
1861 * @param fEvents The events we want to subscribe to.
1862 */
1863static int rtSocketPollUpdateEvents(RTSOCKETINT *pThis, uint32_t fEvents)
1864{
1865 LONG fNetworkEvents = 0;
1866 if (fEvents & RTPOLL_EVT_READ)
1867 fNetworkEvents |= FD_READ;
1868 if (fEvents & RTPOLL_EVT_WRITE)
1869 fNetworkEvents |= FD_WRITE;
1870 if (fEvents & RTPOLL_EVT_ERROR)
1871 fNetworkEvents |= FD_CLOSE;
1872 LogFlowFunc(("fNetworkEvents=%#x\n", fNetworkEvents));
1873 if (WSAEventSelect(pThis->hNative, pThis->hEvent, fNetworkEvents) == 0)
1874 {
1875 pThis->fSubscribedEvts = fEvents;
1876 return VINF_SUCCESS;
1877 }
1878
1879 int rc = rtSocketError();
1880 AssertMsgFailed(("fNetworkEvents=%#x rc=%Rrc\n", fNetworkEvents, rtSocketError()));
1881 return rc;
1882}
1883
1884#endif /* RT_OS_WINDOWS */
1885
1886
1887#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
1888
1889/**
1890 * Checks for pending events.
1891 *
1892 * @returns Event mask or 0.
1893 * @param pThis The socket handle.
1894 * @param fEvents The desired events.
1895 */
1896static uint32_t rtSocketPollCheck(RTSOCKETINT *pThis, uint32_t fEvents)
1897{
1898 uint32_t fRetEvents = 0;
1899
1900 LogFlowFunc(("pThis=%#p fEvents=%#x\n", pThis, fEvents));
1901
1902# ifdef RT_OS_WINDOWS
1903 /* Make sure WSAEnumNetworkEvents returns what we want. */
1904 int rc = VINF_SUCCESS;
1905 if ((pThis->fSubscribedEvts & fEvents) != fEvents)
1906 rc = rtSocketPollUpdateEvents(pThis, pThis->fSubscribedEvts | fEvents);
1907
1908 /* Get the event mask, ASSUMES that WSAEnumNetworkEvents doesn't clear stuff. */
1909 WSANETWORKEVENTS NetEvts;
1910 RT_ZERO(NetEvts);
1911 if (WSAEnumNetworkEvents(pThis->hNative, pThis->hEvent, &NetEvts) == 0)
1912 {
1913 if ( (NetEvts.lNetworkEvents & FD_READ)
1914 && (fEvents & RTPOLL_EVT_READ)
1915 && NetEvts.iErrorCode[FD_READ_BIT] == 0)
1916 fRetEvents |= RTPOLL_EVT_READ;
1917
1918 if ( (NetEvts.lNetworkEvents & FD_WRITE)
1919 && (fEvents & RTPOLL_EVT_WRITE)
1920 && NetEvts.iErrorCode[FD_WRITE_BIT] == 0)
1921 fRetEvents |= RTPOLL_EVT_WRITE;
1922
1923 if (fEvents & RTPOLL_EVT_ERROR)
1924 {
1925 if (NetEvts.lNetworkEvents & FD_CLOSE)
1926 fRetEvents |= RTPOLL_EVT_ERROR;
1927 else
1928 for (uint32_t i = 0; i < FD_MAX_EVENTS; i++)
1929 if ( (NetEvts.lNetworkEvents & (1L << i))
1930 && NetEvts.iErrorCode[i] != 0)
1931 fRetEvents |= RTPOLL_EVT_ERROR;
1932 }
1933 }
1934 else
1935 rc = rtSocketError();
1936
1937 /* Fall back on select if we hit an error above. */
1938 if (RT_FAILURE(rc))
1939 {
1940
1941 }
1942
1943#else /* RT_OS_OS2 */
1944 int aFds[4] = { pThis->hNative, pThis->hNative, pThis->hNative, -1 };
1945 int rc = os2_select(aFds, 1, 1, 1, 0);
1946 if (rc > 0)
1947 {
1948 if (aFds[0] == pThis->hNative)
1949 fRetEvents |= RTPOLL_EVT_READ;
1950 if (aFds[1] == pThis->hNative)
1951 fRetEvents |= RTPOLL_EVT_WRITE;
1952 if (aFds[2] == pThis->hNative)
1953 fRetEvents |= RTPOLL_EVT_ERROR;
1954 fRetEvents &= fEvents;
1955 }
1956#endif /* RT_OS_OS2 */
1957
1958 LogFlowFunc(("fRetEvents=%#x\n", fRetEvents));
1959 return fRetEvents;
1960}
1961
1962
1963/**
1964 * Internal RTPoll helper that polls the socket handle and, if @a fNoWait is
1965 * clear, starts whatever actions we've got running during the poll call.
1966 *
1967 * @returns 0 if no pending events, actions initiated if @a fNoWait is clear.
1968 * Event mask (in @a fEvents) and no actions if the handle is ready
1969 * already.
1970 * UINT32_MAX (asserted) if the socket handle is busy in I/O or a
1971 * different poll set.
1972 *
1973 * @param hSocket The socket handle.
1974 * @param hPollSet The poll set handle (for access checks).
1975 * @param fEvents The events we're polling for.
1976 * @param fFinalEntry Set if this is the final entry for this handle
1977 * in this poll set. This can be used for dealing
1978 * with duplicate entries.
1979 * @param fNoWait Set if it's a zero-wait poll call. Clear if
1980 * we'll wait for an event to occur.
1981 *
1982 * @remarks There is a potential race wrt duplicate handles when @a fNoWait is
1983 * @c true, we don't currently care about that oddity...
1984 */
1985uint32_t rtSocketPollStart(RTSOCKET hSocket, RTPOLLSET hPollSet, uint32_t fEvents, bool fFinalEntry, bool fNoWait)
1986{
1987 RTSOCKETINT *pThis = hSocket;
1988 AssertPtrReturn(pThis, UINT32_MAX);
1989 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, UINT32_MAX);
1990 /** @todo This isn't quite sane. Replace by critsect and open up concurrent
1991 * reads and writes! */
1992 if (rtSocketTryLock(pThis))
1993 pThis->hPollSet = hPollSet;
1994 else
1995 {
1996 AssertReturn(pThis->hPollSet == hPollSet, UINT32_MAX);
1997 ASMAtomicIncU32(&pThis->cUsers);
1998 }
1999
2000 /* (rtSocketPollCheck will reset the event object). */
2001# ifdef RT_OS_WINDOWS
2002 uint32_t fRetEvents = pThis->fEventsSaved;
2003 pThis->fEventsSaved = 0; /* Reset */
2004 fRetEvents |= rtSocketPollCheck(pThis, fEvents);
2005
2006 if ( !fRetEvents
2007 && !fNoWait)
2008 {
2009 pThis->fPollEvts |= fEvents;
2010 if ( fFinalEntry
2011 && pThis->fSubscribedEvts != pThis->fPollEvts)
2012 {
2013 int rc = rtSocketPollUpdateEvents(pThis, pThis->fPollEvts);
2014 if (RT_FAILURE(rc))
2015 {
2016 pThis->fPollEvts = 0;
2017 fRetEvents = UINT32_MAX;
2018 }
2019 }
2020 }
2021# else
2022 uint32_t fRetEvents = rtSocketPollCheck(pThis, fEvents);
2023# endif
2024
2025 if (fRetEvents || fNoWait)
2026 {
2027 if (pThis->cUsers == 1)
2028 {
2029# ifdef RT_OS_WINDOWS
2030 rtSocketPollClearEventAndRestoreBlocking(pThis);
2031# endif
2032 pThis->hPollSet = NIL_RTPOLLSET;
2033 }
2034 ASMAtomicDecU32(&pThis->cUsers);
2035 }
2036
2037 return fRetEvents;
2038}
2039
2040
2041/**
2042 * Called after a WaitForMultipleObjects returned in order to check for pending
2043 * events and stop whatever actions that rtSocketPollStart() initiated.
2044 *
2045 * @returns Event mask or 0.
2046 *
2047 * @param hSocket The socket handle.
2048 * @param fEvents The events we're polling for.
2049 * @param fFinalEntry Set if this is the final entry for this handle
2050 * in this poll set. This can be used for dealing
2051 * with duplicate entries. Only keep in mind that
2052 * this method is called in reverse order, so the
2053 * first call will have this set (when the entire
2054 * set was processed).
2055 * @param fHarvestEvents Set if we should check for pending events.
2056 */
2057uint32_t rtSocketPollDone(RTSOCKET hSocket, uint32_t fEvents, bool fFinalEntry, bool fHarvestEvents)
2058{
2059 RTSOCKETINT *pThis = hSocket;
2060 AssertPtrReturn(pThis, 0);
2061 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, 0);
2062 Assert(pThis->cUsers > 0);
2063 Assert(pThis->hPollSet != NIL_RTPOLLSET);
2064
2065 /* Harvest events and clear the event mask for the next round of polling. */
2066 uint32_t fRetEvents = rtSocketPollCheck(pThis, fEvents);
2067# ifdef RT_OS_WINDOWS
2068 pThis->fPollEvts = 0;
2069
2070 /*
2071 * Save the write event if required.
2072 * It is only posted once and might get lost if the another source in the
2073 * pollset with a higher priority has pending events.
2074 */
2075 if ( !fHarvestEvents
2076 && fRetEvents)
2077 {
2078 pThis->fEventsSaved = fRetEvents;
2079 fRetEvents = 0;
2080 }
2081# endif
2082
2083 /* Make the socket blocking again and unlock the handle. */
2084 if (pThis->cUsers == 1)
2085 {
2086# ifdef RT_OS_WINDOWS
2087 rtSocketPollClearEventAndRestoreBlocking(pThis);
2088# endif
2089 pThis->hPollSet = NIL_RTPOLLSET;
2090 }
2091 ASMAtomicDecU32(&pThis->cUsers);
2092 return fRetEvents;
2093}
2094
2095#endif /* RT_OS_WINDOWS || RT_OS_OS2 */
2096
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette