VirtualBox

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

Last change on this file since 67151 was 67151, checked in by vboxsync, 8 years ago

Runtime/r3/socket: when checking for select() results it is possible that pThis->hNative became invalid in the meantimebecause the socket was closed, see rtSocketCloseIt() where we invalid pThis->hNative first and then close the socket. We could also remember hNative for the correct test after select() but I don't think we really care about the RTSOCKET_EVT_READ result on closed sockets.

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