VirtualBox

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

Last change on this file since 43176 was 43176, checked in by vboxsync, 13 years ago

more windows build fixes

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

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