VirtualBox

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

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

RTSocketSelectOneEx: Addendeum to r115827: Should set RTSOCKET_EVT_ERROR if the socket closed (see for example rtUdpServerListen). Need to consider possible races with rtSocketCloseIt all the way thru the function.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 66.5 KB
Line 
1/* $Id: socket.cpp 67170 2017-05-31 12:46:24Z 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.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 */
26
27
28/*********************************************************************************************************************************
29* Header Files *
30*********************************************************************************************************************************/
31#ifdef RT_OS_WINDOWS
32# include <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
1514 RTSOCKETNATIVE hNative = pThis->hNative;
1515 if (hNative == NIL_RTSOCKETNATIVE)
1516 {
1517 /* Socket is already closed? Possible we raced someone calling rtSocketCloseIt.
1518 Should we return a different status code? */
1519 *pfEvents = RTSOCKET_EVT_ERROR;
1520 return VINF_SUCCESS;
1521 }
1522
1523 int const fdMax = (int)hNative + 1;
1524 AssertReturn((RTSOCKETNATIVE)(fdMax - 1) == hNative, VERR_INTERNAL_ERROR_5);
1525
1526 *pfEvents = 0;
1527
1528 /*
1529 * Set up the file descriptor sets and do the select.
1530 */
1531 fd_set fdsetR;
1532 fd_set fdsetW;
1533 fd_set fdsetE;
1534 FD_ZERO(&fdsetR);
1535 FD_ZERO(&fdsetW);
1536 FD_ZERO(&fdsetE);
1537
1538 if (fEvents & RTSOCKET_EVT_READ)
1539 FD_SET(hNative, &fdsetR);
1540 if (fEvents & RTSOCKET_EVT_WRITE)
1541 FD_SET(hNative, &fdsetW);
1542 if (fEvents & RTSOCKET_EVT_ERROR)
1543 FD_SET(hNative, &fdsetE);
1544
1545 int rc;
1546 if (cMillies == RT_INDEFINITE_WAIT)
1547 rc = select(fdMax, &fdsetR, &fdsetW, &fdsetE, NULL);
1548 else
1549 {
1550 struct timeval timeout;
1551 timeout.tv_sec = cMillies / 1000;
1552 timeout.tv_usec = (cMillies % 1000) * 1000;
1553 rc = select(fdMax, &fdsetR, &fdsetW, &fdsetE, &timeout);
1554 }
1555 if (rc > 0)
1556 {
1557 if (pThis->hNative == hNative)
1558 {
1559 if (FD_ISSET(hNative, &fdsetR))
1560 *pfEvents |= RTSOCKET_EVT_READ;
1561 if (FD_ISSET(hNative, &fdsetW))
1562 *pfEvents |= RTSOCKET_EVT_WRITE;
1563 if (FD_ISSET(hNative, &fdsetE))
1564 *pfEvents |= RTSOCKET_EVT_ERROR;
1565 rc = VINF_SUCCESS;
1566 }
1567 else
1568 {
1569 /* Socket was closed while we waited (rtSocketCloseIt). Different status code? */
1570 *pfEvents = RTSOCKET_EVT_ERROR;
1571 rc = VINF_SUCCESS;
1572 }
1573 }
1574 else if (rc == 0)
1575 rc = VERR_TIMEOUT;
1576 else
1577 rc = rtSocketError();
1578
1579 return rc;
1580}
1581
1582
1583RTDECL(int) RTSocketShutdown(RTSOCKET hSocket, bool fRead, bool fWrite)
1584{
1585 /*
1586 * Validate input, don't lock it because we might want to interrupt a call
1587 * active on a different thread.
1588 */
1589 RTSOCKETINT *pThis = hSocket;
1590 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1591 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1592 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
1593 AssertReturn(fRead || fWrite, VERR_INVALID_PARAMETER);
1594
1595 /*
1596 * Do the job.
1597 */
1598 int rc = VINF_SUCCESS;
1599 int fHow;
1600 if (fRead && fWrite)
1601 fHow = SHUT_RDWR;
1602 else if (fRead)
1603 fHow = SHUT_RD;
1604 else
1605 fHow = SHUT_WR;
1606 if (shutdown(pThis->hNative, fHow) == -1)
1607 rc = rtSocketError();
1608
1609 return rc;
1610}
1611
1612
1613RTDECL(int) RTSocketGetLocalAddress(RTSOCKET hSocket, PRTNETADDR pAddr)
1614{
1615 /*
1616 * Validate input.
1617 */
1618 RTSOCKETINT *pThis = hSocket;
1619 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1620 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1621 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
1622
1623 /*
1624 * Get the address and convert it.
1625 */
1626 int rc;
1627 RTSOCKADDRUNION u;
1628#ifdef RT_OS_WINDOWS
1629 int cbAddr = sizeof(u);
1630#else
1631 socklen_t cbAddr = sizeof(u);
1632#endif
1633 RT_ZERO(u);
1634 if (getsockname(pThis->hNative, &u.Addr, &cbAddr) == 0)
1635 rc = rtSocketNetAddrFromAddr(&u, cbAddr, pAddr);
1636 else
1637 rc = rtSocketError();
1638
1639 return rc;
1640}
1641
1642
1643RTDECL(int) RTSocketGetPeerAddress(RTSOCKET hSocket, PRTNETADDR pAddr)
1644{
1645 /*
1646 * Validate input.
1647 */
1648 RTSOCKETINT *pThis = hSocket;
1649 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1650 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1651 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
1652
1653 /*
1654 * Get the address and convert it.
1655 */
1656 int rc;
1657 RTSOCKADDRUNION u;
1658#ifdef RT_OS_WINDOWS
1659 int cbAddr = sizeof(u);
1660#else
1661 socklen_t cbAddr = sizeof(u);
1662#endif
1663 RT_ZERO(u);
1664 if (getpeername(pThis->hNative, &u.Addr, &cbAddr) == 0)
1665 rc = rtSocketNetAddrFromAddr(&u, cbAddr, pAddr);
1666 else
1667 rc = rtSocketError();
1668
1669 return rc;
1670}
1671
1672
1673
1674/**
1675 * Wrapper around bind.
1676 *
1677 * @returns IPRT status code.
1678 * @param hSocket The socket handle.
1679 * @param pAddr The address to bind to.
1680 */
1681DECLHIDDEN(int) rtSocketBind(RTSOCKET hSocket, PCRTNETADDR pAddr)
1682{
1683 RTSOCKADDRUNION u;
1684 int cbAddr;
1685 int rc = rtSocketAddrFromNetAddr(pAddr, &u, sizeof(u), &cbAddr);
1686 if (RT_SUCCESS(rc))
1687 rc = rtSocketBindRawAddr(hSocket, &u.Addr, cbAddr);
1688 return rc;
1689}
1690
1691
1692/**
1693 * Very thin wrapper around bind.
1694 *
1695 * @returns IPRT status code.
1696 * @param hSocket The socket handle.
1697 * @param pvAddr The address to bind to (struct sockaddr and
1698 * friends).
1699 * @param cbAddr The size of the address.
1700 */
1701DECLHIDDEN(int) rtSocketBindRawAddr(RTSOCKET hSocket, void const *pvAddr, size_t cbAddr)
1702{
1703 /*
1704 * Validate input.
1705 */
1706 RTSOCKETINT *pThis = hSocket;
1707 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1708 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1709 AssertPtrReturn(pvAddr, VERR_INVALID_POINTER);
1710 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1711
1712 int rc;
1713 if (bind(pThis->hNative, (struct sockaddr const *)pvAddr, (int)cbAddr) == 0)
1714 rc = VINF_SUCCESS;
1715 else
1716 rc = rtSocketError();
1717
1718 rtSocketUnlock(pThis);
1719 return rc;
1720}
1721
1722
1723
1724/**
1725 * Wrapper around listen.
1726 *
1727 * @returns IPRT status code.
1728 * @param hSocket The socket handle.
1729 * @param cMaxPending The max number of pending connections.
1730 */
1731DECLHIDDEN(int) rtSocketListen(RTSOCKET hSocket, int cMaxPending)
1732{
1733 /*
1734 * Validate input.
1735 */
1736 RTSOCKETINT *pThis = hSocket;
1737 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1738 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1739 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1740
1741 int rc = VINF_SUCCESS;
1742 if (listen(pThis->hNative, cMaxPending) != 0)
1743 rc = rtSocketError();
1744
1745 rtSocketUnlock(pThis);
1746 return rc;
1747}
1748
1749
1750/**
1751 * Wrapper around accept.
1752 *
1753 * @returns IPRT status code.
1754 * @param hSocket The socket handle.
1755 * @param phClient Where to return the client socket handle on
1756 * success.
1757 * @param pAddr Where to return the client address.
1758 * @param pcbAddr On input this gives the size buffer size of what
1759 * @a pAddr point to. On return this contains the
1760 * size of what's stored at @a pAddr.
1761 */
1762DECLHIDDEN(int) rtSocketAccept(RTSOCKET hSocket, PRTSOCKET phClient, struct sockaddr *pAddr, size_t *pcbAddr)
1763{
1764 /*
1765 * Validate input.
1766 * Only lock the socket temporarily while we get the native handle, so that
1767 * we can safely shutdown and destroy the socket from a different thread.
1768 */
1769 RTSOCKETINT *pThis = hSocket;
1770 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1771 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1772 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1773
1774 /*
1775 * Call accept().
1776 */
1777 rtSocketErrorReset();
1778 int rc = VINF_SUCCESS;
1779#ifdef RT_OS_WINDOWS
1780 int cbAddr = (int)*pcbAddr;
1781#else
1782 socklen_t cbAddr = *pcbAddr;
1783#endif
1784 RTSOCKETNATIVE hNativeClient = accept(pThis->hNative, pAddr, &cbAddr);
1785 if (hNativeClient != NIL_RTSOCKETNATIVE)
1786 {
1787 *pcbAddr = cbAddr;
1788
1789 /*
1790 * Wrap the client socket.
1791 */
1792 rc = rtSocketCreateForNative(phClient, hNativeClient);
1793 if (RT_FAILURE(rc))
1794 {
1795#ifdef RT_OS_WINDOWS
1796 closesocket(hNativeClient);
1797#else
1798 close(hNativeClient);
1799#endif
1800 }
1801 }
1802 else
1803 rc = rtSocketError();
1804
1805 rtSocketUnlock(pThis);
1806 return rc;
1807}
1808
1809
1810/**
1811 * Wrapper around connect.
1812 *
1813 * @returns IPRT status code.
1814 * @param hSocket The socket handle.
1815 * @param pAddr The socket address to connect to.
1816 * @param cMillies Number of milliseconds to wait for the connect attempt to complete.
1817 * Use RT_INDEFINITE_WAIT to wait for ever.
1818 * Use RT_TCPCLIENTCONNECT_DEFAULT_WAIT to wait for the default time
1819 * configured on the running system.
1820 */
1821DECLHIDDEN(int) rtSocketConnect(RTSOCKET hSocket, PCRTNETADDR pAddr, RTMSINTERVAL cMillies)
1822{
1823 /*
1824 * Validate input.
1825 */
1826 RTSOCKETINT *pThis = hSocket;
1827 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1828 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1829 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1830
1831 RTSOCKADDRUNION u;
1832 int cbAddr;
1833 int rc = rtSocketAddrFromNetAddr(pAddr, &u, sizeof(u), &cbAddr);
1834 if (RT_SUCCESS(rc))
1835 {
1836 if (cMillies == RT_SOCKETCONNECT_DEFAULT_WAIT)
1837 {
1838 if (connect(pThis->hNative, &u.Addr, cbAddr) != 0)
1839 rc = rtSocketError();
1840 }
1841 else
1842 {
1843 /*
1844 * Switch the socket to nonblocking mode, initiate the connect
1845 * and wait for the socket to become writable or until the timeout
1846 * expires.
1847 */
1848 rc = rtSocketSwitchBlockingMode(pThis, false /* fBlocking */);
1849 if (RT_SUCCESS(rc))
1850 {
1851 if (connect(pThis->hNative, &u.Addr, cbAddr) != 0)
1852 {
1853 rc = rtSocketError();
1854 if (rc == VERR_TRY_AGAIN || rc == VERR_NET_IN_PROGRESS)
1855 {
1856 int rcSock = 0;
1857 fd_set FdSetWriteable;
1858 struct timeval TvTimeout;
1859
1860 TvTimeout.tv_sec = cMillies / RT_MS_1SEC;
1861 TvTimeout.tv_usec = (cMillies % RT_MS_1SEC) * RT_US_1MS;
1862
1863 FD_ZERO(&FdSetWriteable);
1864 FD_SET(pThis->hNative, &FdSetWriteable);
1865 do
1866 {
1867 rcSock = select(pThis->hNative + 1, NULL, &FdSetWriteable, NULL,
1868 cMillies == RT_INDEFINITE_WAIT || cMillies >= INT_MAX
1869 ? NULL
1870 : &TvTimeout);
1871 if (rcSock > 0)
1872 {
1873 int iSockError = 0;
1874 socklen_t cbSockOpt = sizeof(iSockError);
1875 rcSock = getsockopt(pThis->hNative, SOL_SOCKET, SO_ERROR, (char *)&iSockError, &cbSockOpt);
1876 if (rcSock == 0)
1877 {
1878 if (iSockError == 0)
1879 rc = VINF_SUCCESS;
1880 else
1881 {
1882#ifdef RT_OS_WINDOWS
1883 rc = RTErrConvertFromWin32(iSockError);
1884#else
1885 rc = RTErrConvertFromErrno(iSockError);
1886#endif
1887 }
1888 }
1889 else
1890 rc = rtSocketError();
1891 }
1892 else if (rcSock == 0)
1893 rc = VERR_TIMEOUT;
1894 else
1895 rc = rtSocketError();
1896 } while (rc == VERR_INTERRUPTED);
1897 }
1898 }
1899
1900 rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
1901 }
1902 }
1903 }
1904
1905 rtSocketUnlock(pThis);
1906 return rc;
1907}
1908
1909
1910/**
1911 * Wrapper around connect, raw address, no timeout.
1912 *
1913 * @returns IPRT status code.
1914 * @param hSocket The socket handle.
1915 * @param pvAddr The raw socket address to connect to.
1916 * @param cbAddr The size of the raw address.
1917 */
1918DECLHIDDEN(int) rtSocketConnectRaw(RTSOCKET hSocket, void const *pvAddr, size_t cbAddr)
1919{
1920 /*
1921 * Validate input.
1922 */
1923 RTSOCKETINT *pThis = hSocket;
1924 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1925 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1926 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1927
1928 int rc;
1929 if (connect(pThis->hNative, (const struct sockaddr *)pvAddr, (int)cbAddr) == 0)
1930 rc = VINF_SUCCESS;
1931 else
1932 rc = rtSocketError();
1933
1934 rtSocketUnlock(pThis);
1935 return rc;
1936}
1937
1938
1939/**
1940 * Wrapper around setsockopt.
1941 *
1942 * @returns IPRT status code.
1943 * @param hSocket The socket handle.
1944 * @param iLevel The protocol level, e.g. IPPORTO_TCP.
1945 * @param iOption The option, e.g. TCP_NODELAY.
1946 * @param pvValue The value buffer.
1947 * @param cbValue The size of the value pointed to by pvValue.
1948 */
1949DECLHIDDEN(int) rtSocketSetOpt(RTSOCKET hSocket, int iLevel, int iOption, void const *pvValue, int cbValue)
1950{
1951 /*
1952 * Validate input.
1953 */
1954 RTSOCKETINT *pThis = hSocket;
1955 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1956 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1957 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1958
1959 int rc = VINF_SUCCESS;
1960 if (setsockopt(pThis->hNative, iLevel, iOption, (const char *)pvValue, cbValue) != 0)
1961 rc = rtSocketError();
1962
1963 rtSocketUnlock(pThis);
1964 return rc;
1965}
1966
1967
1968/**
1969 * Internal RTPollSetAdd helper that returns the handle that should be added to
1970 * the pollset.
1971 *
1972 * @returns Valid handle on success, INVALID_HANDLE_VALUE on failure.
1973 * @param hSocket The socket handle.
1974 * @param fEvents The events we're polling for.
1975 * @param phNative Where to put the primary handle.
1976 */
1977DECLHIDDEN(int) rtSocketPollGetHandle(RTSOCKET hSocket, uint32_t fEvents, PRTHCINTPTR phNative)
1978{
1979 RTSOCKETINT *pThis = hSocket;
1980 RT_NOREF_PV(fEvents);
1981 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1982 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1983#ifdef RT_OS_WINDOWS
1984 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1985
1986 int rc = VINF_SUCCESS;
1987 if (pThis->hEvent != WSA_INVALID_EVENT)
1988 *phNative = (RTHCINTPTR)pThis->hEvent;
1989 else
1990 {
1991 pThis->hEvent = WSACreateEvent();
1992 *phNative = (RTHCINTPTR)pThis->hEvent;
1993 if (pThis->hEvent == WSA_INVALID_EVENT)
1994 rc = rtSocketError();
1995 }
1996
1997 rtSocketUnlock(pThis);
1998 return rc;
1999
2000#else /* !RT_OS_WINDOWS */
2001 *phNative = (RTHCUINTPTR)pThis->hNative;
2002 return VINF_SUCCESS;
2003#endif /* !RT_OS_WINDOWS */
2004}
2005
2006#ifdef RT_OS_WINDOWS
2007
2008/**
2009 * Undos the harm done by WSAEventSelect.
2010 *
2011 * @returns IPRT status code.
2012 * @param pThis The socket handle.
2013 */
2014static int rtSocketPollClearEventAndRestoreBlocking(RTSOCKETINT *pThis)
2015{
2016 int rc = VINF_SUCCESS;
2017 if (pThis->fSubscribedEvts)
2018 {
2019 if (WSAEventSelect(pThis->hNative, WSA_INVALID_EVENT, 0) == 0)
2020 {
2021 pThis->fSubscribedEvts = 0;
2022
2023 /*
2024 * Switch back to blocking mode if that was the state before the
2025 * operation.
2026 */
2027 if (pThis->fBlocking)
2028 {
2029 u_long fNonBlocking = 0;
2030 int rc2 = ioctlsocket(pThis->hNative, FIONBIO, &fNonBlocking);
2031 if (rc2 != 0)
2032 {
2033 rc = rtSocketError();
2034 AssertMsgFailed(("%Rrc; rc2=%d\n", rc, rc2));
2035 }
2036 }
2037 }
2038 else
2039 {
2040 rc = rtSocketError();
2041 AssertMsgFailed(("%Rrc\n", rc));
2042 }
2043 }
2044 return rc;
2045}
2046
2047
2048/**
2049 * Updates the mask of events we're subscribing to.
2050 *
2051 * @returns IPRT status code.
2052 * @param pThis The socket handle.
2053 * @param fEvents The events we want to subscribe to.
2054 */
2055static int rtSocketPollUpdateEvents(RTSOCKETINT *pThis, uint32_t fEvents)
2056{
2057 LONG fNetworkEvents = 0;
2058 if (fEvents & RTPOLL_EVT_READ)
2059 fNetworkEvents |= FD_READ;
2060 if (fEvents & RTPOLL_EVT_WRITE)
2061 fNetworkEvents |= FD_WRITE;
2062 if (fEvents & RTPOLL_EVT_ERROR)
2063 fNetworkEvents |= FD_CLOSE;
2064 LogFlowFunc(("fNetworkEvents=%#x\n", fNetworkEvents));
2065 if (WSAEventSelect(pThis->hNative, pThis->hEvent, fNetworkEvents) == 0)
2066 {
2067 pThis->fSubscribedEvts = fEvents;
2068 return VINF_SUCCESS;
2069 }
2070
2071 int rc = rtSocketError();
2072 AssertMsgFailed(("fNetworkEvents=%#x rc=%Rrc\n", fNetworkEvents, rtSocketError()));
2073 return rc;
2074}
2075
2076#endif /* RT_OS_WINDOWS */
2077
2078
2079#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
2080
2081/**
2082 * Checks for pending events.
2083 *
2084 * @returns Event mask or 0.
2085 * @param pThis The socket handle.
2086 * @param fEvents The desired events.
2087 */
2088static uint32_t rtSocketPollCheck(RTSOCKETINT *pThis, uint32_t fEvents)
2089{
2090 uint32_t fRetEvents = 0;
2091
2092 LogFlowFunc(("pThis=%#p fEvents=%#x\n", pThis, fEvents));
2093
2094# ifdef RT_OS_WINDOWS
2095 /* Make sure WSAEnumNetworkEvents returns what we want. */
2096 int rc = VINF_SUCCESS;
2097 if ((pThis->fSubscribedEvts & fEvents) != fEvents)
2098 rc = rtSocketPollUpdateEvents(pThis, pThis->fSubscribedEvts | fEvents);
2099
2100 /* Get the event mask, ASSUMES that WSAEnumNetworkEvents doesn't clear stuff. */
2101 WSANETWORKEVENTS NetEvts;
2102 RT_ZERO(NetEvts);
2103 if (WSAEnumNetworkEvents(pThis->hNative, pThis->hEvent, &NetEvts) == 0)
2104 {
2105 if ( (NetEvts.lNetworkEvents & FD_READ)
2106 && (fEvents & RTPOLL_EVT_READ)
2107 && NetEvts.iErrorCode[FD_READ_BIT] == 0)
2108 fRetEvents |= RTPOLL_EVT_READ;
2109
2110 if ( (NetEvts.lNetworkEvents & FD_WRITE)
2111 && (fEvents & RTPOLL_EVT_WRITE)
2112 && NetEvts.iErrorCode[FD_WRITE_BIT] == 0)
2113 fRetEvents |= RTPOLL_EVT_WRITE;
2114
2115 if (fEvents & RTPOLL_EVT_ERROR)
2116 {
2117 if (NetEvts.lNetworkEvents & FD_CLOSE)
2118 fRetEvents |= RTPOLL_EVT_ERROR;
2119 else
2120 for (uint32_t i = 0; i < FD_MAX_EVENTS; i++)
2121 if ( (NetEvts.lNetworkEvents & (1L << i))
2122 && NetEvts.iErrorCode[i] != 0)
2123 fRetEvents |= RTPOLL_EVT_ERROR;
2124 }
2125 }
2126 else
2127 rc = rtSocketError();
2128
2129 /* Fall back on select if we hit an error above. */
2130 if (RT_FAILURE(rc))
2131 {
2132
2133 }
2134
2135#else /* RT_OS_OS2 */
2136 int aFds[4] = { pThis->hNative, pThis->hNative, pThis->hNative, -1 };
2137 int rc = os2_select(aFds, 1, 1, 1, 0);
2138 if (rc > 0)
2139 {
2140 if (aFds[0] == pThis->hNative)
2141 fRetEvents |= RTPOLL_EVT_READ;
2142 if (aFds[1] == pThis->hNative)
2143 fRetEvents |= RTPOLL_EVT_WRITE;
2144 if (aFds[2] == pThis->hNative)
2145 fRetEvents |= RTPOLL_EVT_ERROR;
2146 fRetEvents &= fEvents;
2147 }
2148#endif /* RT_OS_OS2 */
2149
2150 LogFlowFunc(("fRetEvents=%#x\n", fRetEvents));
2151 return fRetEvents;
2152}
2153
2154
2155/**
2156 * Internal RTPoll helper that polls the socket handle and, if @a fNoWait is
2157 * clear, starts whatever actions we've got running during the poll call.
2158 *
2159 * @returns 0 if no pending events, actions initiated if @a fNoWait is clear.
2160 * Event mask (in @a fEvents) and no actions if the handle is ready
2161 * already.
2162 * UINT32_MAX (asserted) if the socket handle is busy in I/O or a
2163 * different poll set.
2164 *
2165 * @param hSocket The socket handle.
2166 * @param hPollSet The poll set handle (for access checks).
2167 * @param fEvents The events we're polling for.
2168 * @param fFinalEntry Set if this is the final entry for this handle
2169 * in this poll set. This can be used for dealing
2170 * with duplicate entries.
2171 * @param fNoWait Set if it's a zero-wait poll call. Clear if
2172 * we'll wait for an event to occur.
2173 *
2174 * @remarks There is a potential race wrt duplicate handles when @a fNoWait is
2175 * @c true, we don't currently care about that oddity...
2176 */
2177DECLHIDDEN(uint32_t) rtSocketPollStart(RTSOCKET hSocket, RTPOLLSET hPollSet, uint32_t fEvents, bool fFinalEntry, bool fNoWait)
2178{
2179 RTSOCKETINT *pThis = hSocket;
2180 AssertPtrReturn(pThis, UINT32_MAX);
2181 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, UINT32_MAX);
2182 /** @todo This isn't quite sane. Replace by critsect and open up concurrent
2183 * reads and writes! */
2184 if (rtSocketTryLock(pThis))
2185 pThis->hPollSet = hPollSet;
2186 else
2187 {
2188 AssertReturn(pThis->hPollSet == hPollSet, UINT32_MAX);
2189 ASMAtomicIncU32(&pThis->cUsers);
2190 }
2191
2192 /* (rtSocketPollCheck will reset the event object). */
2193# ifdef RT_OS_WINDOWS
2194 uint32_t fRetEvents = pThis->fEventsSaved;
2195 pThis->fEventsSaved = 0; /* Reset */
2196 fRetEvents |= rtSocketPollCheck(pThis, fEvents);
2197
2198 if ( !fRetEvents
2199 && !fNoWait)
2200 {
2201 pThis->fPollEvts |= fEvents;
2202 if ( fFinalEntry
2203 && pThis->fSubscribedEvts != pThis->fPollEvts)
2204 {
2205 int rc = rtSocketPollUpdateEvents(pThis, pThis->fPollEvts);
2206 if (RT_FAILURE(rc))
2207 {
2208 pThis->fPollEvts = 0;
2209 fRetEvents = UINT32_MAX;
2210 }
2211 }
2212 }
2213# else
2214 uint32_t fRetEvents = rtSocketPollCheck(pThis, fEvents);
2215# endif
2216
2217 if (fRetEvents || fNoWait)
2218 {
2219 if (pThis->cUsers == 1)
2220 {
2221# ifdef RT_OS_WINDOWS
2222 rtSocketPollClearEventAndRestoreBlocking(pThis);
2223# endif
2224 pThis->hPollSet = NIL_RTPOLLSET;
2225 }
2226 ASMAtomicDecU32(&pThis->cUsers);
2227 }
2228
2229 return fRetEvents;
2230}
2231
2232
2233/**
2234 * Called after a WaitForMultipleObjects returned in order to check for pending
2235 * events and stop whatever actions that rtSocketPollStart() initiated.
2236 *
2237 * @returns Event mask or 0.
2238 *
2239 * @param hSocket The socket handle.
2240 * @param fEvents The events we're polling for.
2241 * @param fFinalEntry Set if this is the final entry for this handle
2242 * in this poll set. This can be used for dealing
2243 * with duplicate entries. Only keep in mind that
2244 * this method is called in reverse order, so the
2245 * first call will have this set (when the entire
2246 * set was processed).
2247 * @param fHarvestEvents Set if we should check for pending events.
2248 */
2249DECLHIDDEN(uint32_t) rtSocketPollDone(RTSOCKET hSocket, uint32_t fEvents, bool fFinalEntry, bool fHarvestEvents)
2250{
2251 RTSOCKETINT *pThis = hSocket;
2252 AssertPtrReturn(pThis, 0);
2253 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, 0);
2254 Assert(pThis->cUsers > 0);
2255 Assert(pThis->hPollSet != NIL_RTPOLLSET);
2256 RT_NOREF_PV(fFinalEntry);
2257
2258 /* Harvest events and clear the event mask for the next round of polling. */
2259 uint32_t fRetEvents = rtSocketPollCheck(pThis, fEvents);
2260# ifdef RT_OS_WINDOWS
2261 pThis->fPollEvts = 0;
2262
2263 /*
2264 * Save the write event if required.
2265 * It is only posted once and might get lost if the another source in the
2266 * pollset with a higher priority has pending events.
2267 */
2268 if ( !fHarvestEvents
2269 && fRetEvents)
2270 {
2271 pThis->fEventsSaved = fRetEvents;
2272 fRetEvents = 0;
2273 }
2274# endif
2275
2276 /* Make the socket blocking again and unlock the handle. */
2277 if (pThis->cUsers == 1)
2278 {
2279# ifdef RT_OS_WINDOWS
2280 rtSocketPollClearEventAndRestoreBlocking(pThis);
2281# endif
2282 pThis->hPollSet = NIL_RTPOLLSET;
2283 }
2284 ASMAtomicDecU32(&pThis->cUsers);
2285 return fRetEvents;
2286}
2287
2288#endif /* RT_OS_WINDOWS || RT_OS_OS2 */
2289
Note: See TracBrowser for help on using the repository browser.

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