VirtualBox

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

Last change on this file since 61009 was 60910, checked in by vboxsync, 9 years ago

iprt/socket.cpp: set *pcbWritten to 0 on windows too when returning VINF_TRY_AGAIN. Don't bother check whether VINF_SUCCESS is VERR_TRY_AGAIN! Makes the code harder to read and potentially slower.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 65.8 KB
Line 
1/* $Id: socket.cpp 60910 2016-05-09 21:00:28Z vboxsync $ */
2/** @file
3 * IPRT - Network Sockets.
4 */
5
6/*
7 * Copyright (C) 2006-2015 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 */
26
27
28/*********************************************************************************************************************************
29* Header Files *
30*********************************************************************************************************************************/
31#ifdef RT_OS_WINDOWS
32# include <winsock2.h>
33# include <ws2tcpip.h>
34#else /* !RT_OS_WINDOWS */
35# include <errno.h>
36# include <sys/select.h>
37# include <sys/stat.h>
38# include <sys/socket.h>
39# include <netinet/in.h>
40# include <netinet/tcp.h>
41# include <arpa/inet.h>
42# ifdef IPRT_WITH_TCPIP_V6
43# include <netinet6/in6.h>
44# endif
45# include <sys/un.h>
46# include <netdb.h>
47# include <unistd.h>
48# include <fcntl.h>
49# include <sys/uio.h>
50#endif /* !RT_OS_WINDOWS */
51#include <limits.h>
52
53#include "internal/iprt.h"
54#include <iprt/socket.h>
55
56#include <iprt/alloca.h>
57#include <iprt/asm.h>
58#include <iprt/assert.h>
59#include <iprt/ctype.h>
60#include <iprt/err.h>
61#include <iprt/mempool.h>
62#include <iprt/poll.h>
63#include <iprt/string.h>
64#include <iprt/thread.h>
65#include <iprt/time.h>
66#include <iprt/mem.h>
67#include <iprt/sg.h>
68#include <iprt/log.h>
69
70#include "internal/magics.h"
71#include "internal/socket.h"
72#include "internal/string.h"
73
74
75/*********************************************************************************************************************************
76* Defined Constants And Macros *
77*********************************************************************************************************************************/
78/* non-standard linux stuff (it seems). */
79#ifndef MSG_NOSIGNAL
80# define MSG_NOSIGNAL 0
81#endif
82
83/* Windows has different names for SHUT_XXX. */
84#ifndef SHUT_RDWR
85# ifdef SD_BOTH
86# define SHUT_RDWR SD_BOTH
87# else
88# define SHUT_RDWR 2
89# endif
90#endif
91#ifndef SHUT_WR
92# ifdef SD_SEND
93# define SHUT_WR SD_SEND
94# else
95# define SHUT_WR 1
96# endif
97#endif
98#ifndef SHUT_RD
99# ifdef SD_RECEIVE
100# define SHUT_RD SD_RECEIVE
101# else
102# define SHUT_RD 0
103# endif
104#endif
105
106/* fixup backlevel OSes. */
107#if defined(RT_OS_OS2) || defined(RT_OS_WINDOWS)
108# define socklen_t int
109#endif
110
111/** How many pending connection. */
112#define RTTCP_SERVER_BACKLOG 10
113
114/* Limit read and write sizes on Windows and OS/2. */
115#ifdef RT_OS_WINDOWS
116# define RTSOCKET_MAX_WRITE (INT_MAX / 2)
117# define RTSOCKET_MAX_READ (INT_MAX / 2)
118#elif defined(RT_OS_OS2)
119# define RTSOCKET_MAX_WRITE 0x10000
120# define RTSOCKET_MAX_READ 0x10000
121#endif
122
123
124/*********************************************************************************************************************************
125* Structures and Typedefs *
126*********************************************************************************************************************************/
127/**
128 * Socket handle data.
129 *
130 * This is mainly required for implementing RTPollSet on Windows.
131 */
132typedef struct RTSOCKETINT
133{
134 /** Magic number (RTSOCKET_MAGIC). */
135 uint32_t u32Magic;
136 /** Exclusive user count.
137 * This is used to prevent two threads from accessing the handle concurrently.
138 * It can be higher than 1 if this handle is reference multiple times in a
139 * polling set (Windows). */
140 uint32_t volatile cUsers;
141 /** The native socket handle. */
142 RTSOCKETNATIVE hNative;
143 /** Indicates whether the handle has been closed or not. */
144 bool volatile fClosed;
145 /** Indicates whether the socket is operating in blocking or non-blocking mode
146 * currently. */
147 bool fBlocking;
148#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
149 /** The pollset currently polling this socket. This is NIL if no one is
150 * polling. */
151 RTPOLLSET hPollSet;
152#endif
153#ifdef RT_OS_WINDOWS
154 /** The event semaphore we've associated with the socket handle.
155 * This is WSA_INVALID_EVENT if not done. */
156 WSAEVENT hEvent;
157 /** The events we're polling for. */
158 uint32_t fPollEvts;
159 /** The events we're currently subscribing to with WSAEventSelect.
160 * This is ZERO if we're currently not subscribing to anything. */
161 uint32_t fSubscribedEvts;
162 /** Saved events which are only posted once. */
163 uint32_t fEventsSaved;
164#endif /* RT_OS_WINDOWS */
165} RTSOCKETINT;
166
167
168/**
169 * Address union used internally for things like getpeername and getsockname.
170 */
171typedef union RTSOCKADDRUNION
172{
173 struct sockaddr Addr;
174 struct sockaddr_in IPv4;
175#ifdef IPRT_WITH_TCPIP_V6
176 struct sockaddr_in6 IPv6;
177#endif
178} RTSOCKADDRUNION;
179
180
181/**
182 * Get the last error as an iprt status code.
183 *
184 * @returns IPRT status code.
185 */
186DECLINLINE(int) rtSocketError(void)
187{
188#ifdef RT_OS_WINDOWS
189 return RTErrConvertFromWin32(WSAGetLastError());
190#else
191 return RTErrConvertFromErrno(errno);
192#endif
193}
194
195
196/**
197 * Resets the last error.
198 */
199DECLINLINE(void) rtSocketErrorReset(void)
200{
201#ifdef RT_OS_WINDOWS
202 WSASetLastError(0);
203#else
204 errno = 0;
205#endif
206}
207
208
209/**
210 * Get the last resolver error as an iprt status code.
211 *
212 * @returns iprt status code.
213 */
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 return VERR_UNRESOLVED_ERROR;
232 }
233#endif
234}
235
236
237/**
238 * Converts from a native socket address to a generic IPRT network address.
239 *
240 * @returns IPRT status code.
241 * @param pSrc The source address.
242 * @param cbSrc The size of the source address.
243 * @param pAddr Where to return the generic IPRT network
244 * address.
245 */
246static int rtSocketNetAddrFromAddr(RTSOCKADDRUNION const *pSrc, size_t cbSrc, PRTNETADDR pAddr)
247{
248 /*
249 * Convert the address.
250 */
251 if ( cbSrc == sizeof(struct sockaddr_in)
252 && pSrc->Addr.sa_family == AF_INET)
253 {
254 RT_ZERO(*pAddr);
255 pAddr->enmType = RTNETADDRTYPE_IPV4;
256 pAddr->uPort = RT_N2H_U16(pSrc->IPv4.sin_port);
257 pAddr->uAddr.IPv4.u = pSrc->IPv4.sin_addr.s_addr;
258 }
259#ifdef IPRT_WITH_TCPIP_V6
260 else if ( cbSrc == sizeof(struct sockaddr_in6)
261 && pSrc->Addr.sa_family == AF_INET6)
262 {
263 RT_ZERO(*pAddr);
264 pAddr->enmType = RTNETADDRTYPE_IPV6;
265 pAddr->uPort = RT_N2H_U16(pSrc->IPv6.sin6_port);
266 pAddr->uAddr.IPv6.au32[0] = pSrc->IPv6.sin6_addr.s6_addr32[0];
267 pAddr->uAddr.IPv6.au32[1] = pSrc->IPv6.sin6_addr.s6_addr32[1];
268 pAddr->uAddr.IPv6.au32[2] = pSrc->IPv6.sin6_addr.s6_addr32[2];
269 pAddr->uAddr.IPv6.au32[3] = pSrc->IPv6.sin6_addr.s6_addr32[3];
270 }
271#endif
272 else
273 return VERR_NET_ADDRESS_FAMILY_NOT_SUPPORTED;
274 return VINF_SUCCESS;
275}
276
277
278/**
279 * Converts from a generic IPRT network address to a native socket address.
280 *
281 * @returns IPRT status code.
282 * @param pAddr Pointer to the generic IPRT network address.
283 * @param pDst The source address.
284 * @param cbDst The size of the source address.
285 * @param pcbAddr Where to store the size of the returned address.
286 * Optional
287 */
288static int rtSocketAddrFromNetAddr(PCRTNETADDR pAddr, RTSOCKADDRUNION *pDst, size_t cbDst, int *pcbAddr)
289{
290 RT_BZERO(pDst, cbDst);
291 if ( pAddr->enmType == RTNETADDRTYPE_IPV4
292 && cbDst >= sizeof(struct sockaddr_in))
293 {
294 pDst->Addr.sa_family = AF_INET;
295 pDst->IPv4.sin_port = RT_H2N_U16(pAddr->uPort);
296 pDst->IPv4.sin_addr.s_addr = pAddr->uAddr.IPv4.u;
297 if (pcbAddr)
298 *pcbAddr = sizeof(pDst->IPv4);
299 }
300#ifdef IPRT_WITH_TCPIP_V6
301 else if ( pAddr->enmType == RTNETADDRTYPE_IPV6
302 && cbDst >= sizeof(struct sockaddr_in6))
303 {
304 pDst->Addr.sa_family = AF_INET6;
305 pDst->IPv6.sin6_port = RT_H2N_U16(pAddr->uPort);
306 pSrc->IPv6.sin6_addr.s6_addr32[0] = pAddr->uAddr.IPv6.au32[0];
307 pSrc->IPv6.sin6_addr.s6_addr32[1] = pAddr->uAddr.IPv6.au32[1];
308 pSrc->IPv6.sin6_addr.s6_addr32[2] = pAddr->uAddr.IPv6.au32[2];
309 pSrc->IPv6.sin6_addr.s6_addr32[3] = pAddr->uAddr.IPv6.au32[3];
310 if (pcbAddr)
311 *pcbAddr = sizeof(pDst->IPv6);
312 }
313#endif
314 else
315 return VERR_NET_ADDRESS_FAMILY_NOT_SUPPORTED;
316 return VINF_SUCCESS;
317}
318
319
320/**
321 * Tries to lock the socket for exclusive usage by the calling thread.
322 *
323 * Call rtSocketUnlock() to unlock.
324 *
325 * @returns @c true if locked, @c false if not.
326 * @param pThis The socket structure.
327 */
328DECLINLINE(bool) rtSocketTryLock(RTSOCKETINT *pThis)
329{
330 return ASMAtomicCmpXchgU32(&pThis->cUsers, 1, 0);
331}
332
333
334/**
335 * Unlocks the socket.
336 *
337 * @param pThis The socket structure.
338 */
339DECLINLINE(void) rtSocketUnlock(RTSOCKETINT *pThis)
340{
341 ASMAtomicCmpXchgU32(&pThis->cUsers, 0, 1);
342}
343
344
345/**
346 * The slow path of rtSocketSwitchBlockingMode that does the actual switching.
347 *
348 * @returns IPRT status code.
349 * @param pThis The socket structure.
350 * @param fBlocking The desired mode of operation.
351 * @remarks Do not call directly.
352 */
353static int rtSocketSwitchBlockingModeSlow(RTSOCKETINT *pThis, bool fBlocking)
354{
355#ifdef RT_OS_WINDOWS
356 u_long uBlocking = fBlocking ? 0 : 1;
357 if (ioctlsocket(pThis->hNative, FIONBIO, &uBlocking))
358 return rtSocketError();
359
360#else
361 int fFlags = fcntl(pThis->hNative, F_GETFL, 0);
362 if (fFlags == -1)
363 return rtSocketError();
364
365 if (fBlocking)
366 fFlags &= ~O_NONBLOCK;
367 else
368 fFlags |= O_NONBLOCK;
369 if (fcntl(pThis->hNative, F_SETFL, fFlags) == -1)
370 return rtSocketError();
371#endif
372
373 pThis->fBlocking = fBlocking;
374 return VINF_SUCCESS;
375}
376
377
378/**
379 * Switches the socket to the desired blocking mode if necessary.
380 *
381 * The socket must be locked.
382 *
383 * @returns IPRT status code.
384 * @param pThis The socket structure.
385 * @param fBlocking The desired mode of operation.
386 */
387DECLINLINE(int) rtSocketSwitchBlockingMode(RTSOCKETINT *pThis, bool fBlocking)
388{
389 if (pThis->fBlocking != fBlocking)
390 return rtSocketSwitchBlockingModeSlow(pThis, fBlocking);
391 return VINF_SUCCESS;
392}
393
394
395/**
396 * Creates an IPRT socket handle for a native one.
397 *
398 * @returns IPRT status code.
399 * @param ppSocket Where to return the IPRT socket handle.
400 * @param hNative The native handle.
401 */
402DECLHIDDEN(int) rtSocketCreateForNative(RTSOCKETINT **ppSocket, RTSOCKETNATIVE hNative)
403{
404 RTSOCKETINT *pThis = (RTSOCKETINT *)RTMemPoolAlloc(RTMEMPOOL_DEFAULT, sizeof(*pThis));
405 if (!pThis)
406 return VERR_NO_MEMORY;
407 pThis->u32Magic = RTSOCKET_MAGIC;
408 pThis->cUsers = 0;
409 pThis->hNative = hNative;
410 pThis->fClosed = false;
411 pThis->fBlocking = true;
412#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
413 pThis->hPollSet = NIL_RTPOLLSET;
414#endif
415#ifdef RT_OS_WINDOWS
416 pThis->hEvent = WSA_INVALID_EVENT;
417 pThis->fPollEvts = 0;
418 pThis->fSubscribedEvts = 0;
419 pThis->fEventsSaved = 0;
420#endif
421 *ppSocket = pThis;
422 return VINF_SUCCESS;
423}
424
425
426RTDECL(int) RTSocketFromNative(PRTSOCKET phSocket, RTHCINTPTR uNative)
427{
428 AssertReturn(uNative != NIL_RTSOCKETNATIVE, VERR_INVALID_PARAMETER);
429#ifndef RT_OS_WINDOWS
430 AssertReturn(uNative >= 0, VERR_INVALID_PARAMETER);
431#endif
432 AssertPtrReturn(phSocket, VERR_INVALID_POINTER);
433 return rtSocketCreateForNative(phSocket, uNative);
434}
435
436
437/**
438 * Wrapper around socket().
439 *
440 * @returns IPRT status code.
441 * @param phSocket Where to store the handle to the socket on
442 * success.
443 * @param iDomain The protocol family (PF_XXX).
444 * @param iType The socket type (SOCK_XXX).
445 * @param iProtocol Socket parameter, usually 0.
446 */
447DECLHIDDEN(int) rtSocketCreate(PRTSOCKET phSocket, int iDomain, int iType, int iProtocol)
448{
449 /*
450 * Create the socket.
451 */
452 RTSOCKETNATIVE hNative = socket(iDomain, iType, iProtocol);
453 if (hNative == NIL_RTSOCKETNATIVE)
454 return rtSocketError();
455
456 /*
457 * Wrap it.
458 */
459 int rc = rtSocketCreateForNative(phSocket, hNative);
460 if (RT_FAILURE(rc))
461 {
462#ifdef RT_OS_WINDOWS
463 closesocket(hNative);
464#else
465 close(hNative);
466#endif
467 }
468 return rc;
469}
470
471
472RTDECL(uint32_t) RTSocketRetain(RTSOCKET hSocket)
473{
474 RTSOCKETINT *pThis = hSocket;
475 AssertPtrReturn(pThis, UINT32_MAX);
476 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, UINT32_MAX);
477 return RTMemPoolRetain(pThis);
478}
479
480
481/**
482 * Worker for RTSocketRelease and RTSocketClose.
483 *
484 * @returns IPRT status code.
485 * @param pThis The socket handle instance data.
486 * @param fDestroy Whether we're reaching ref count zero.
487 */
488static int rtSocketCloseIt(RTSOCKETINT *pThis, bool fDestroy)
489{
490 /*
491 * Invalidate the handle structure on destroy.
492 */
493 if (fDestroy)
494 {
495 Assert(ASMAtomicReadU32(&pThis->u32Magic) == RTSOCKET_MAGIC);
496 ASMAtomicWriteU32(&pThis->u32Magic, RTSOCKET_MAGIC_DEAD);
497 }
498
499 int rc = VINF_SUCCESS;
500 if (ASMAtomicCmpXchgBool(&pThis->fClosed, true, false))
501 {
502 /*
503 * Close the native handle.
504 */
505 RTSOCKETNATIVE hNative = pThis->hNative;
506 if (hNative != NIL_RTSOCKETNATIVE)
507 {
508 pThis->hNative = NIL_RTSOCKETNATIVE;
509
510#ifdef RT_OS_WINDOWS
511 if (closesocket(hNative))
512#else
513 if (close(hNative))
514#endif
515 {
516 rc = rtSocketError();
517#ifdef RT_OS_WINDOWS
518 AssertMsgFailed(("closesocket(%p) -> %Rrc\n", (uintptr_t)hNative, rc));
519#else
520 AssertMsgFailed(("close(%d) -> %Rrc\n", hNative, rc));
521#endif
522 }
523 }
524
525#ifdef RT_OS_WINDOWS
526 /*
527 * Close the event.
528 */
529 WSAEVENT hEvent = pThis->hEvent;
530 if (hEvent == WSA_INVALID_EVENT)
531 {
532 pThis->hEvent = WSA_INVALID_EVENT;
533 WSACloseEvent(hEvent);
534 }
535#endif
536 }
537
538 return rc;
539}
540
541
542RTDECL(uint32_t) RTSocketRelease(RTSOCKET hSocket)
543{
544 RTSOCKETINT *pThis = hSocket;
545 if (pThis == NIL_RTSOCKET)
546 return 0;
547 AssertPtrReturn(pThis, UINT32_MAX);
548 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, UINT32_MAX);
549
550 /* get the refcount without killing it... */
551 uint32_t cRefs = RTMemPoolRefCount(pThis);
552 AssertReturn(cRefs != UINT32_MAX, UINT32_MAX);
553 if (cRefs == 1)
554 rtSocketCloseIt(pThis, true);
555
556 return RTMemPoolRelease(RTMEMPOOL_DEFAULT, pThis);
557}
558
559
560RTDECL(int) RTSocketClose(RTSOCKET hSocket)
561{
562 RTSOCKETINT *pThis = hSocket;
563 if (pThis == NIL_RTSOCKET)
564 return VINF_SUCCESS;
565 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
566 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
567
568 uint32_t cRefs = RTMemPoolRefCount(pThis);
569 AssertReturn(cRefs != UINT32_MAX, UINT32_MAX);
570
571 int rc = rtSocketCloseIt(pThis, cRefs == 1);
572
573 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pThis);
574 return rc;
575}
576
577
578RTDECL(RTHCUINTPTR) RTSocketToNative(RTSOCKET hSocket)
579{
580 RTSOCKETINT *pThis = hSocket;
581 AssertPtrReturn(pThis, RTHCUINTPTR_MAX);
582 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, RTHCUINTPTR_MAX);
583 return (RTHCUINTPTR)pThis->hNative;
584}
585
586
587RTDECL(int) RTSocketSetInheritance(RTSOCKET hSocket, bool fInheritable)
588{
589 RTSOCKETINT *pThis = hSocket;
590 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
591 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
592 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
593
594 int rc = VINF_SUCCESS;
595#ifdef RT_OS_WINDOWS
596 if (!SetHandleInformation((HANDLE)pThis->hNative, HANDLE_FLAG_INHERIT, fInheritable ? HANDLE_FLAG_INHERIT : 0))
597 rc = RTErrConvertFromWin32(GetLastError());
598#else
599 if (fcntl(pThis->hNative, F_SETFD, fInheritable ? 0 : FD_CLOEXEC) < 0)
600 rc = RTErrConvertFromErrno(errno);
601#endif
602
603 return rc;
604}
605
606
607static bool rtSocketIsIPv4Numerical(const char *pszAddress, PRTNETADDRIPV4 pAddr)
608{
609
610 /* Empty address resolves to the INADDR_ANY address (good for bind). */
611 if (!pszAddress || !*pszAddress)
612 {
613 pAddr->u = INADDR_ANY;
614 return true;
615 }
616
617 /* Four quads? */
618 char *psz = (char *)pszAddress;
619 for (int i = 0; i < 4; i++)
620 {
621 uint8_t u8;
622 int rc = RTStrToUInt8Ex(psz, &psz, 0, &u8);
623 if (rc != VINF_SUCCESS && rc != VWRN_TRAILING_CHARS)
624 return false;
625 if (*psz != (i < 3 ? '.' : '\0'))
626 return false;
627 psz++;
628
629 pAddr->au8[i] = u8; /* big endian */
630 }
631
632 return true;
633}
634
635RTDECL(int) RTSocketParseInetAddress(const char *pszAddress, unsigned uPort, PRTNETADDR pAddr)
636{
637 int rc;
638
639 /*
640 * Validate input.
641 */
642 AssertReturn(uPort > 0, VERR_INVALID_PARAMETER);
643 AssertPtrNullReturn(pszAddress, VERR_INVALID_POINTER);
644
645#ifdef RT_OS_WINDOWS
646 /*
647 * Initialize WinSock and check version.
648 */
649 WORD wVersionRequested = MAKEWORD(1, 1);
650 WSADATA wsaData;
651 rc = WSAStartup(wVersionRequested, &wsaData);
652 if (wsaData.wVersion != wVersionRequested)
653 {
654 AssertMsgFailed(("Wrong winsock version\n"));
655 return VERR_NOT_SUPPORTED;
656 }
657#endif
658
659 /*
660 * Resolve the address. Pretty crude at the moment, but we have to make
661 * sure to not ask the NT 4 gethostbyname about an IPv4 address as it may
662 * give a wrong answer.
663 */
664 /** @todo this only supports IPv4, and IPv6 support needs to be added.
665 * It probably needs to be converted to getaddrinfo(). */
666 RTNETADDRIPV4 IPv4Quad;
667 if (rtSocketIsIPv4Numerical(pszAddress, &IPv4Quad))
668 {
669 Log3(("rtSocketIsIPv4Numerical: %s -> %#x (%RTnaipv4)\n", pszAddress, IPv4Quad.u, IPv4Quad));
670 RT_ZERO(*pAddr);
671 pAddr->enmType = RTNETADDRTYPE_IPV4;
672 pAddr->uPort = uPort;
673 pAddr->uAddr.IPv4 = IPv4Quad;
674 return VINF_SUCCESS;
675 }
676
677 struct hostent *pHostEnt;
678 pHostEnt = gethostbyname(pszAddress);
679 if (!pHostEnt)
680 {
681 rc = rtSocketResolverError();
682 AssertMsgFailed(("Could not resolve '%s', rc=%Rrc\n", pszAddress, rc));
683 return rc;
684 }
685
686 if (pHostEnt->h_addrtype == AF_INET)
687 {
688 RT_ZERO(*pAddr);
689 pAddr->enmType = RTNETADDRTYPE_IPV4;
690 pAddr->uPort = uPort;
691 pAddr->uAddr.IPv4.u = ((struct in_addr *)pHostEnt->h_addr)->s_addr;
692 Log3(("gethostbyname: %s -> %#x (%RTnaipv4)\n", pszAddress, pAddr->uAddr.IPv4.u, pAddr->uAddr.IPv4));
693 }
694 else
695 return VERR_NET_ADDRESS_FAMILY_NOT_SUPPORTED;
696
697 return VINF_SUCCESS;
698}
699
700
701/*
702 * New function to allow both ipv4 and ipv6 addresses to be resolved.
703 * Breaks compatibility with windows before 2000.
704 */
705RTDECL(int) RTSocketQueryAddressStr(const char *pszHost, char *pszResult, size_t *pcbResult, PRTNETADDRTYPE penmAddrType)
706{
707 AssertPtrReturn(pszHost, VERR_INVALID_POINTER);
708 AssertPtrReturn(pcbResult, VERR_INVALID_POINTER);
709 AssertPtrNullReturn(penmAddrType, VERR_INVALID_POINTER);
710 AssertPtrNullReturn(pszResult, VERR_INVALID_POINTER);
711
712#if defined(RT_OS_OS2) || defined(RT_OS_WINDOWS) /** @todo dynamically resolve the APIs not present in NT4! */
713 return VERR_NOT_SUPPORTED;
714
715#else
716 int rc;
717 if (*pcbResult < 16)
718 return VERR_NET_ADDRESS_NOT_AVAILABLE;
719
720 /* Setup the hint. */
721 struct addrinfo grHints;
722 RT_ZERO(grHints);
723 grHints.ai_socktype = 0;
724 grHints.ai_flags = 0;
725 grHints.ai_protocol = 0;
726 grHints.ai_family = AF_UNSPEC;
727 if (penmAddrType)
728 {
729 switch (*penmAddrType)
730 {
731 case RTNETADDRTYPE_INVALID:
732 /*grHints.ai_family = AF_UNSPEC;*/
733 break;
734 case RTNETADDRTYPE_IPV4:
735 grHints.ai_family = AF_INET;
736 break;
737 case RTNETADDRTYPE_IPV6:
738 grHints.ai_family = AF_INET6;
739 break;
740 default:
741 AssertFailedReturn(VERR_INVALID_PARAMETER);
742 }
743 }
744
745# ifdef RT_OS_WINDOWS
746 /*
747 * Winsock2 init
748 */
749 /** @todo someone should check if we really need 2, 2 here */
750 WORD wVersionRequested = MAKEWORD(2, 2);
751 WSADATA wsaData;
752 rc = WSAStartup(wVersionRequested, &wsaData);
753 if (wsaData.wVersion != wVersionRequested)
754 {
755 AssertMsgFailed(("Wrong winsock version\n"));
756 return VERR_NOT_SUPPORTED;
757 }
758# endif
759
760 /** @todo r=bird: getaddrinfo and freeaddrinfo breaks the additions on NT4. */
761 struct addrinfo *pgrResults = NULL;
762 rc = getaddrinfo(pszHost, "", &grHints, &pgrResults);
763 if (rc != 0)
764 return VERR_NET_ADDRESS_NOT_AVAILABLE;
765
766 // return data
767 // on multiple matches return only the first one
768
769 if (!pgrResults)
770 return VERR_NET_ADDRESS_NOT_AVAILABLE;
771
772 struct addrinfo const *pgrResult = pgrResults->ai_next;
773 if (!pgrResult)
774 {
775 freeaddrinfo(pgrResults);
776 return VERR_NET_ADDRESS_NOT_AVAILABLE;
777 }
778
779 uint8_t const *pbDummy;
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 RTSOCKET_MAX_WRITE
1319 int cbNow = cbBuffer >= RTSOCKET_MAX_WRITE ? RTSOCKET_MAX_WRITE : (int)cbBuffer;
1320#else
1321 size_t cbNow = cbBuffer;
1322#endif
1323
1324#ifdef RT_OS_WINDOWS
1325 int cbWritten = send(pThis->hNative, (const char *)pvBuffer, cbNow, MSG_NOSIGNAL);
1326 if (cbWritten >= 0)
1327 {
1328 *pcbWritten = cbWritten;
1329 rc = VINF_SUCCESS;
1330 }
1331 else
1332 {
1333 rc = rtSocketError();
1334 if (rc == VERR_TRY_AGAIN)
1335 {
1336 *pcbWritten = 0;
1337 rc = VINF_TRY_AGAIN;
1338 }
1339 }
1340#else
1341 ssize_t cbWritten = send(pThis->hNative, pvBuffer, cbBuffer, MSG_NOSIGNAL);
1342 if (cbWritten >= 0)
1343 *pcbWritten = cbWritten;
1344 else if ( errno == EAGAIN
1345# ifdef EWOULDBLOCK
1346# if EWOULDBLOCK != EAGAIN
1347 || errno == EWOULDBLOCK
1348# endif
1349# endif
1350 )
1351 {
1352 *pcbWritten = 0;
1353 rc = VINF_TRY_AGAIN;
1354 }
1355 else
1356 rc = rtSocketError();
1357#endif
1358
1359 rtSocketUnlock(pThis);
1360 return rc;
1361}
1362
1363
1364RTDECL(int) RTSocketSgWriteNB(RTSOCKET hSocket, PCRTSGBUF pSgBuf, size_t *pcbWritten)
1365{
1366 /*
1367 * Validate input.
1368 */
1369 RTSOCKETINT *pThis = hSocket;
1370 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1371 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1372 AssertPtrReturn(pSgBuf, VERR_INVALID_PARAMETER);
1373 AssertPtrReturn(pcbWritten, VERR_INVALID_PARAMETER);
1374 AssertReturn(pSgBuf->cSegs > 0, VERR_INVALID_PARAMETER);
1375 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1376
1377 int rc = rtSocketSwitchBlockingMode(pThis, false /* fBlocking */);
1378 if (RT_FAILURE(rc))
1379 return rc;
1380
1381 unsigned cSegsToSend = 0;
1382 rc = VERR_NO_TMP_MEMORY;
1383#ifdef RT_OS_WINDOWS
1384 LPWSABUF paMsg = NULL;
1385
1386 RTSgBufMapToNative(paMsg, pSgBuf, WSABUF, buf, char *, len, u_long, cSegsToSend);
1387 if (paMsg)
1388 {
1389 DWORD dwSent = 0;
1390 int hrc = WSASend(pThis->hNative, paMsg, cSegsToSend, &dwSent,
1391 MSG_NOSIGNAL, NULL, NULL);
1392 if (!hrc)
1393 rc = VINF_SUCCESS;
1394 else
1395 rc = rtSocketError();
1396
1397 *pcbWritten = dwSent;
1398
1399 RTMemTmpFree(paMsg);
1400 }
1401
1402#else /* !RT_OS_WINDOWS */
1403 struct iovec *paMsg = NULL;
1404
1405 RTSgBufMapToNative(paMsg, pSgBuf, struct iovec, iov_base, void *, iov_len, size_t, cSegsToSend);
1406 if (paMsg)
1407 {
1408 struct msghdr msgHdr;
1409 RT_ZERO(msgHdr);
1410 msgHdr.msg_iov = paMsg;
1411 msgHdr.msg_iovlen = cSegsToSend;
1412 ssize_t cbWritten = sendmsg(pThis->hNative, &msgHdr, MSG_NOSIGNAL);
1413 if (RT_LIKELY(cbWritten >= 0))
1414 {
1415 rc = VINF_SUCCESS;
1416 *pcbWritten = cbWritten;
1417 }
1418 else
1419 rc = rtSocketError();
1420
1421 RTMemTmpFree(paMsg);
1422 }
1423#endif /* !RT_OS_WINDOWS */
1424
1425 rtSocketUnlock(pThis);
1426 return rc;
1427}
1428
1429
1430RTDECL(int) RTSocketSgWriteLNB(RTSOCKET hSocket, size_t cSegs, size_t *pcbWritten, ...)
1431{
1432 va_list va;
1433 va_start(va, pcbWritten);
1434 int rc = RTSocketSgWriteLVNB(hSocket, cSegs, pcbWritten, va);
1435 va_end(va);
1436 return rc;
1437}
1438
1439
1440RTDECL(int) RTSocketSgWriteLVNB(RTSOCKET hSocket, size_t cSegs, size_t *pcbWritten, va_list va)
1441{
1442 /*
1443 * Set up a S/G segment array + buffer on the stack and pass it
1444 * on to RTSocketSgWrite.
1445 */
1446 Assert(cSegs <= 16);
1447 PRTSGSEG paSegs = (PRTSGSEG)alloca(cSegs * sizeof(RTSGSEG));
1448 AssertReturn(paSegs, VERR_NO_TMP_MEMORY);
1449 for (size_t i = 0; i < cSegs; i++)
1450 {
1451 paSegs[i].pvSeg = va_arg(va, void *);
1452 paSegs[i].cbSeg = va_arg(va, size_t);
1453 }
1454
1455 RTSGBUF SgBuf;
1456 RTSgBufInit(&SgBuf, paSegs, cSegs);
1457 return RTSocketSgWriteNB(hSocket, &SgBuf, pcbWritten);
1458}
1459
1460
1461RTDECL(int) RTSocketSelectOne(RTSOCKET hSocket, RTMSINTERVAL cMillies)
1462{
1463 /*
1464 * Validate input.
1465 */
1466 RTSOCKETINT *pThis = hSocket;
1467 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1468 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1469 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
1470 int const fdMax = (int)pThis->hNative + 1;
1471 AssertReturn(fdMax - 1 == pThis->hNative, VERR_INTERNAL_ERROR_5);
1472
1473 /*
1474 * Set up the file descriptor sets and do the select.
1475 */
1476 fd_set fdsetR;
1477 FD_ZERO(&fdsetR);
1478 FD_SET(pThis->hNative, &fdsetR);
1479
1480 fd_set fdsetE = fdsetR;
1481
1482 int rc;
1483 if (cMillies == RT_INDEFINITE_WAIT)
1484 rc = select(fdMax, &fdsetR, NULL, &fdsetE, NULL);
1485 else
1486 {
1487 struct timeval timeout;
1488 timeout.tv_sec = cMillies / 1000;
1489 timeout.tv_usec = (cMillies % 1000) * 1000;
1490 rc = select(fdMax, &fdsetR, NULL, &fdsetE, &timeout);
1491 }
1492 if (rc > 0)
1493 rc = VINF_SUCCESS;
1494 else if (rc == 0)
1495 rc = VERR_TIMEOUT;
1496 else
1497 rc = rtSocketError();
1498
1499 return rc;
1500}
1501
1502
1503RTDECL(int) RTSocketSelectOneEx(RTSOCKET hSocket, uint32_t fEvents, uint32_t *pfEvents, RTMSINTERVAL cMillies)
1504{
1505 /*
1506 * Validate input.
1507 */
1508 RTSOCKETINT *pThis = hSocket;
1509 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1510 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1511 AssertPtrReturn(pfEvents, VERR_INVALID_PARAMETER);
1512 AssertReturn(!(fEvents & ~RTSOCKET_EVT_VALID_MASK), VERR_INVALID_PARAMETER);
1513 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
1514 int const fdMax = (int)pThis->hNative + 1;
1515 AssertReturn(fdMax - 1 == pThis->hNative, VERR_INTERNAL_ERROR_5);
1516
1517 *pfEvents = 0;
1518
1519 /*
1520 * Set up the file descriptor sets and do the select.
1521 */
1522 fd_set fdsetR;
1523 fd_set fdsetW;
1524 fd_set fdsetE;
1525 FD_ZERO(&fdsetR);
1526 FD_ZERO(&fdsetW);
1527 FD_ZERO(&fdsetE);
1528
1529 if (fEvents & RTSOCKET_EVT_READ)
1530 FD_SET(pThis->hNative, &fdsetR);
1531 if (fEvents & RTSOCKET_EVT_WRITE)
1532 FD_SET(pThis->hNative, &fdsetW);
1533 if (fEvents & RTSOCKET_EVT_ERROR)
1534 FD_SET(pThis->hNative, &fdsetE);
1535
1536 int rc;
1537 if (cMillies == RT_INDEFINITE_WAIT)
1538 rc = select(fdMax, &fdsetR, &fdsetW, &fdsetE, NULL);
1539 else
1540 {
1541 struct timeval timeout;
1542 timeout.tv_sec = cMillies / 1000;
1543 timeout.tv_usec = (cMillies % 1000) * 1000;
1544 rc = select(fdMax, &fdsetR, &fdsetW, &fdsetE, &timeout);
1545 }
1546 if (rc > 0)
1547 {
1548 if (FD_ISSET(pThis->hNative, &fdsetR))
1549 *pfEvents |= RTSOCKET_EVT_READ;
1550 if (FD_ISSET(pThis->hNative, &fdsetW))
1551 *pfEvents |= RTSOCKET_EVT_WRITE;
1552 if (FD_ISSET(pThis->hNative, &fdsetE))
1553 *pfEvents |= RTSOCKET_EVT_ERROR;
1554
1555 rc = VINF_SUCCESS;
1556 }
1557 else if (rc == 0)
1558 rc = VERR_TIMEOUT;
1559 else
1560 rc = rtSocketError();
1561
1562 return rc;
1563}
1564
1565
1566RTDECL(int) RTSocketShutdown(RTSOCKET hSocket, bool fRead, bool fWrite)
1567{
1568 /*
1569 * Validate input, don't lock it because we might want to interrupt a call
1570 * active on a different thread.
1571 */
1572 RTSOCKETINT *pThis = hSocket;
1573 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1574 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1575 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
1576 AssertReturn(fRead || fWrite, VERR_INVALID_PARAMETER);
1577
1578 /*
1579 * Do the job.
1580 */
1581 int rc = VINF_SUCCESS;
1582 int fHow;
1583 if (fRead && fWrite)
1584 fHow = SHUT_RDWR;
1585 else if (fRead)
1586 fHow = SHUT_RD;
1587 else
1588 fHow = SHUT_WR;
1589 if (shutdown(pThis->hNative, fHow) == -1)
1590 rc = rtSocketError();
1591
1592 return rc;
1593}
1594
1595
1596RTDECL(int) RTSocketGetLocalAddress(RTSOCKET hSocket, PRTNETADDR pAddr)
1597{
1598 /*
1599 * Validate input.
1600 */
1601 RTSOCKETINT *pThis = hSocket;
1602 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1603 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1604 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
1605
1606 /*
1607 * Get the address and convert it.
1608 */
1609 int rc;
1610 RTSOCKADDRUNION u;
1611#ifdef RT_OS_WINDOWS
1612 int cbAddr = sizeof(u);
1613#else
1614 socklen_t cbAddr = sizeof(u);
1615#endif
1616 RT_ZERO(u);
1617 if (getsockname(pThis->hNative, &u.Addr, &cbAddr) == 0)
1618 rc = rtSocketNetAddrFromAddr(&u, cbAddr, pAddr);
1619 else
1620 rc = rtSocketError();
1621
1622 return rc;
1623}
1624
1625
1626RTDECL(int) RTSocketGetPeerAddress(RTSOCKET hSocket, PRTNETADDR pAddr)
1627{
1628 /*
1629 * Validate input.
1630 */
1631 RTSOCKETINT *pThis = hSocket;
1632 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1633 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1634 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
1635
1636 /*
1637 * Get the address and convert it.
1638 */
1639 int rc;
1640 RTSOCKADDRUNION u;
1641#ifdef RT_OS_WINDOWS
1642 int cbAddr = sizeof(u);
1643#else
1644 socklen_t cbAddr = sizeof(u);
1645#endif
1646 RT_ZERO(u);
1647 if (getpeername(pThis->hNative, &u.Addr, &cbAddr) == 0)
1648 rc = rtSocketNetAddrFromAddr(&u, cbAddr, pAddr);
1649 else
1650 rc = rtSocketError();
1651
1652 return rc;
1653}
1654
1655
1656
1657/**
1658 * Wrapper around bind.
1659 *
1660 * @returns IPRT status code.
1661 * @param hSocket The socket handle.
1662 * @param pAddr The address to bind to.
1663 */
1664DECLHIDDEN(int) rtSocketBind(RTSOCKET hSocket, PCRTNETADDR pAddr)
1665{
1666 RTSOCKADDRUNION u;
1667 int cbAddr;
1668 int rc = rtSocketAddrFromNetAddr(pAddr, &u, sizeof(u), &cbAddr);
1669 if (RT_SUCCESS(rc))
1670 rc = rtSocketBindRawAddr(hSocket, &u.Addr, cbAddr);
1671 return rc;
1672}
1673
1674
1675/**
1676 * Very thin wrapper around bind.
1677 *
1678 * @returns IPRT status code.
1679 * @param hSocket The socket handle.
1680 * @param pvAddr The address to bind to (struct sockaddr and
1681 * friends).
1682 * @param cbAddr The size of the address.
1683 */
1684DECLHIDDEN(int) rtSocketBindRawAddr(RTSOCKET hSocket, void const *pvAddr, size_t cbAddr)
1685{
1686 /*
1687 * Validate input.
1688 */
1689 RTSOCKETINT *pThis = hSocket;
1690 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1691 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1692 AssertPtrReturn(pvAddr, VERR_INVALID_POINTER);
1693 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1694
1695 int rc;
1696 if (bind(pThis->hNative, (struct sockaddr const *)pvAddr, (int)cbAddr) == 0)
1697 rc = VINF_SUCCESS;
1698 else
1699 rc = rtSocketError();
1700
1701 rtSocketUnlock(pThis);
1702 return rc;
1703}
1704
1705
1706
1707/**
1708 * Wrapper around listen.
1709 *
1710 * @returns IPRT status code.
1711 * @param hSocket The socket handle.
1712 * @param cMaxPending The max number of pending connections.
1713 */
1714DECLHIDDEN(int) rtSocketListen(RTSOCKET hSocket, int cMaxPending)
1715{
1716 /*
1717 * Validate input.
1718 */
1719 RTSOCKETINT *pThis = hSocket;
1720 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1721 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1722 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1723
1724 int rc = VINF_SUCCESS;
1725 if (listen(pThis->hNative, cMaxPending) != 0)
1726 rc = rtSocketError();
1727
1728 rtSocketUnlock(pThis);
1729 return rc;
1730}
1731
1732
1733/**
1734 * Wrapper around accept.
1735 *
1736 * @returns IPRT status code.
1737 * @param hSocket The socket handle.
1738 * @param phClient Where to return the client socket handle on
1739 * success.
1740 * @param pAddr Where to return the client address.
1741 * @param pcbAddr On input this gives the size buffer size of what
1742 * @a pAddr point to. On return this contains the
1743 * size of what's stored at @a pAddr.
1744 */
1745DECLHIDDEN(int) rtSocketAccept(RTSOCKET hSocket, PRTSOCKET phClient, struct sockaddr *pAddr, size_t *pcbAddr)
1746{
1747 /*
1748 * Validate input.
1749 * Only lock the socket temporarily while we get the native handle, so that
1750 * we can safely shutdown and destroy the socket from a different thread.
1751 */
1752 RTSOCKETINT *pThis = hSocket;
1753 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1754 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1755 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1756
1757 /*
1758 * Call accept().
1759 */
1760 rtSocketErrorReset();
1761 int rc = VINF_SUCCESS;
1762#ifdef RT_OS_WINDOWS
1763 int cbAddr = (int)*pcbAddr;
1764#else
1765 socklen_t cbAddr = *pcbAddr;
1766#endif
1767 RTSOCKETNATIVE hNativeClient = accept(pThis->hNative, pAddr, &cbAddr);
1768 if (hNativeClient != NIL_RTSOCKETNATIVE)
1769 {
1770 *pcbAddr = cbAddr;
1771
1772 /*
1773 * Wrap the client socket.
1774 */
1775 rc = rtSocketCreateForNative(phClient, hNativeClient);
1776 if (RT_FAILURE(rc))
1777 {
1778#ifdef RT_OS_WINDOWS
1779 closesocket(hNativeClient);
1780#else
1781 close(hNativeClient);
1782#endif
1783 }
1784 }
1785 else
1786 rc = rtSocketError();
1787
1788 rtSocketUnlock(pThis);
1789 return rc;
1790}
1791
1792
1793/**
1794 * Wrapper around connect.
1795 *
1796 * @returns IPRT status code.
1797 * @param hSocket The socket handle.
1798 * @param pAddr The socket address to connect to.
1799 * @param cMillies Number of milliseconds to wait for the connect attempt to complete.
1800 * Use RT_INDEFINITE_WAIT to wait for ever.
1801 * Use RT_TCPCLIENTCONNECT_DEFAULT_WAIT to wait for the default time
1802 * configured on the running system.
1803 */
1804DECLHIDDEN(int) rtSocketConnect(RTSOCKET hSocket, PCRTNETADDR pAddr, RTMSINTERVAL cMillies)
1805{
1806 /*
1807 * Validate input.
1808 */
1809 RTSOCKETINT *pThis = hSocket;
1810 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1811 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1812 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1813
1814 RTSOCKADDRUNION u;
1815 int cbAddr;
1816 int rc = rtSocketAddrFromNetAddr(pAddr, &u, sizeof(u), &cbAddr);
1817 if (RT_SUCCESS(rc))
1818 {
1819 if (cMillies == RT_SOCKETCONNECT_DEFAULT_WAIT)
1820 {
1821 if (connect(pThis->hNative, &u.Addr, cbAddr) != 0)
1822 rc = rtSocketError();
1823 }
1824 else
1825 {
1826 /*
1827 * Switch the socket to nonblocking mode, initiate the connect
1828 * and wait for the socket to become writable or until the timeout
1829 * expires.
1830 */
1831 rc = rtSocketSwitchBlockingMode(pThis, false /* fBlocking */);
1832 if (RT_SUCCESS(rc))
1833 {
1834 if (connect(pThis->hNative, &u.Addr, cbAddr) != 0)
1835 {
1836 rc = rtSocketError();
1837 if (rc == VERR_TRY_AGAIN || rc == VERR_NET_IN_PROGRESS)
1838 {
1839 int rcSock = 0;
1840 fd_set FdSetWriteable;
1841 struct timeval TvTimeout;
1842
1843 TvTimeout.tv_sec = cMillies / RT_MS_1SEC;
1844 TvTimeout.tv_usec = (cMillies % RT_MS_1SEC) * RT_US_1MS;
1845
1846 FD_ZERO(&FdSetWriteable);
1847 FD_SET(pThis->hNative, &FdSetWriteable);
1848 do
1849 {
1850 rcSock = select(pThis->hNative + 1, NULL, &FdSetWriteable, NULL,
1851 cMillies == RT_INDEFINITE_WAIT || cMillies >= INT_MAX
1852 ? NULL
1853 : &TvTimeout);
1854 if (rcSock > 0)
1855 {
1856 int iSockError = 0;
1857 socklen_t cbSockOpt = sizeof(iSockError);
1858 rcSock = getsockopt(pThis->hNative, SOL_SOCKET, SO_ERROR, (char *)&iSockError, &cbSockOpt);
1859 if (rcSock == 0)
1860 {
1861 if (iSockError == 0)
1862 rc = VINF_SUCCESS;
1863 else
1864 {
1865#ifdef RT_OS_WINDOWS
1866 rc = RTErrConvertFromWin32(iSockError);
1867#else
1868 rc = RTErrConvertFromErrno(iSockError);
1869#endif
1870 }
1871 }
1872 else
1873 rc = rtSocketError();
1874 }
1875 else if (rcSock == 0)
1876 rc = VERR_TIMEOUT;
1877 else
1878 rc = rtSocketError();
1879 } while (rc == VERR_INTERRUPTED);
1880 }
1881 }
1882
1883 rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
1884 }
1885 }
1886 }
1887
1888 rtSocketUnlock(pThis);
1889 return rc;
1890}
1891
1892
1893/**
1894 * Wrapper around connect, raw address, no timeout.
1895 *
1896 * @returns IPRT status code.
1897 * @param hSocket The socket handle.
1898 * @param pvAddr The raw socket address to connect to.
1899 * @param cbAddr The size of the raw address.
1900 */
1901DECLHIDDEN(int) rtSocketConnectRaw(RTSOCKET hSocket, void const *pvAddr, size_t cbAddr)
1902{
1903 /*
1904 * Validate input.
1905 */
1906 RTSOCKETINT *pThis = hSocket;
1907 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1908 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1909 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1910
1911 int rc;
1912 if (connect(pThis->hNative, (const struct sockaddr *)pvAddr, (int)cbAddr) == 0)
1913 rc = VINF_SUCCESS;
1914 else
1915 rc = rtSocketError();
1916
1917 rtSocketUnlock(pThis);
1918 return rc;
1919}
1920
1921
1922/**
1923 * Wrapper around setsockopt.
1924 *
1925 * @returns IPRT status code.
1926 * @param hSocket The socket handle.
1927 * @param iLevel The protocol level, e.g. IPPORTO_TCP.
1928 * @param iOption The option, e.g. TCP_NODELAY.
1929 * @param pvValue The value buffer.
1930 * @param cbValue The size of the value pointed to by pvValue.
1931 */
1932DECLHIDDEN(int) rtSocketSetOpt(RTSOCKET hSocket, int iLevel, int iOption, void const *pvValue, int cbValue)
1933{
1934 /*
1935 * Validate input.
1936 */
1937 RTSOCKETINT *pThis = hSocket;
1938 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1939 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1940 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1941
1942 int rc = VINF_SUCCESS;
1943 if (setsockopt(pThis->hNative, iLevel, iOption, (const char *)pvValue, cbValue) != 0)
1944 rc = rtSocketError();
1945
1946 rtSocketUnlock(pThis);
1947 return rc;
1948}
1949
1950
1951/**
1952 * Internal RTPollSetAdd helper that returns the handle that should be added to
1953 * the pollset.
1954 *
1955 * @returns Valid handle on success, INVALID_HANDLE_VALUE on failure.
1956 * @param hSocket The socket handle.
1957 * @param fEvents The events we're polling for.
1958 * @param phNative Where to put the primary handle.
1959 */
1960DECLHIDDEN(int) rtSocketPollGetHandle(RTSOCKET hSocket, uint32_t fEvents, PRTHCINTPTR phNative)
1961{
1962 RTSOCKETINT *pThis = hSocket;
1963 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1964 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1965#ifdef RT_OS_WINDOWS
1966 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1967
1968 int rc = VINF_SUCCESS;
1969 if (pThis->hEvent != WSA_INVALID_EVENT)
1970 *phNative = (RTHCINTPTR)pThis->hEvent;
1971 else
1972 {
1973 pThis->hEvent = WSACreateEvent();
1974 *phNative = (RTHCINTPTR)pThis->hEvent;
1975 if (pThis->hEvent == WSA_INVALID_EVENT)
1976 rc = rtSocketError();
1977 }
1978
1979 rtSocketUnlock(pThis);
1980 return rc;
1981
1982#else /* !RT_OS_WINDOWS */
1983 *phNative = (RTHCUINTPTR)pThis->hNative;
1984 return VINF_SUCCESS;
1985#endif /* !RT_OS_WINDOWS */
1986}
1987
1988#ifdef RT_OS_WINDOWS
1989
1990/**
1991 * Undos the harm done by WSAEventSelect.
1992 *
1993 * @returns IPRT status code.
1994 * @param pThis The socket handle.
1995 */
1996static int rtSocketPollClearEventAndRestoreBlocking(RTSOCKETINT *pThis)
1997{
1998 int rc = VINF_SUCCESS;
1999 if (pThis->fSubscribedEvts)
2000 {
2001 if (WSAEventSelect(pThis->hNative, WSA_INVALID_EVENT, 0) == 0)
2002 {
2003 pThis->fSubscribedEvts = 0;
2004
2005 /*
2006 * Switch back to blocking mode if that was the state before the
2007 * operation.
2008 */
2009 if (pThis->fBlocking)
2010 {
2011 u_long fNonBlocking = 0;
2012 int rc2 = ioctlsocket(pThis->hNative, FIONBIO, &fNonBlocking);
2013 if (rc2 != 0)
2014 {
2015 rc = rtSocketError();
2016 AssertMsgFailed(("%Rrc; rc2=%d\n", rc, rc2));
2017 }
2018 }
2019 }
2020 else
2021 {
2022 rc = rtSocketError();
2023 AssertMsgFailed(("%Rrc\n", rc));
2024 }
2025 }
2026 return rc;
2027}
2028
2029
2030/**
2031 * Updates the mask of events we're subscribing to.
2032 *
2033 * @returns IPRT status code.
2034 * @param pThis The socket handle.
2035 * @param fEvents The events we want to subscribe to.
2036 */
2037static int rtSocketPollUpdateEvents(RTSOCKETINT *pThis, uint32_t fEvents)
2038{
2039 LONG fNetworkEvents = 0;
2040 if (fEvents & RTPOLL_EVT_READ)
2041 fNetworkEvents |= FD_READ;
2042 if (fEvents & RTPOLL_EVT_WRITE)
2043 fNetworkEvents |= FD_WRITE;
2044 if (fEvents & RTPOLL_EVT_ERROR)
2045 fNetworkEvents |= FD_CLOSE;
2046 LogFlowFunc(("fNetworkEvents=%#x\n", fNetworkEvents));
2047 if (WSAEventSelect(pThis->hNative, pThis->hEvent, fNetworkEvents) == 0)
2048 {
2049 pThis->fSubscribedEvts = fEvents;
2050 return VINF_SUCCESS;
2051 }
2052
2053 int rc = rtSocketError();
2054 AssertMsgFailed(("fNetworkEvents=%#x rc=%Rrc\n", fNetworkEvents, rtSocketError()));
2055 return rc;
2056}
2057
2058#endif /* RT_OS_WINDOWS */
2059
2060
2061#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
2062
2063/**
2064 * Checks for pending events.
2065 *
2066 * @returns Event mask or 0.
2067 * @param pThis The socket handle.
2068 * @param fEvents The desired events.
2069 */
2070static uint32_t rtSocketPollCheck(RTSOCKETINT *pThis, uint32_t fEvents)
2071{
2072 uint32_t fRetEvents = 0;
2073
2074 LogFlowFunc(("pThis=%#p fEvents=%#x\n", pThis, fEvents));
2075
2076# ifdef RT_OS_WINDOWS
2077 /* Make sure WSAEnumNetworkEvents returns what we want. */
2078 int rc = VINF_SUCCESS;
2079 if ((pThis->fSubscribedEvts & fEvents) != fEvents)
2080 rc = rtSocketPollUpdateEvents(pThis, pThis->fSubscribedEvts | fEvents);
2081
2082 /* Get the event mask, ASSUMES that WSAEnumNetworkEvents doesn't clear stuff. */
2083 WSANETWORKEVENTS NetEvts;
2084 RT_ZERO(NetEvts);
2085 if (WSAEnumNetworkEvents(pThis->hNative, pThis->hEvent, &NetEvts) == 0)
2086 {
2087 if ( (NetEvts.lNetworkEvents & FD_READ)
2088 && (fEvents & RTPOLL_EVT_READ)
2089 && NetEvts.iErrorCode[FD_READ_BIT] == 0)
2090 fRetEvents |= RTPOLL_EVT_READ;
2091
2092 if ( (NetEvts.lNetworkEvents & FD_WRITE)
2093 && (fEvents & RTPOLL_EVT_WRITE)
2094 && NetEvts.iErrorCode[FD_WRITE_BIT] == 0)
2095 fRetEvents |= RTPOLL_EVT_WRITE;
2096
2097 if (fEvents & RTPOLL_EVT_ERROR)
2098 {
2099 if (NetEvts.lNetworkEvents & FD_CLOSE)
2100 fRetEvents |= RTPOLL_EVT_ERROR;
2101 else
2102 for (uint32_t i = 0; i < FD_MAX_EVENTS; i++)
2103 if ( (NetEvts.lNetworkEvents & (1L << i))
2104 && NetEvts.iErrorCode[i] != 0)
2105 fRetEvents |= RTPOLL_EVT_ERROR;
2106 }
2107 }
2108 else
2109 rc = rtSocketError();
2110
2111 /* Fall back on select if we hit an error above. */
2112 if (RT_FAILURE(rc))
2113 {
2114
2115 }
2116
2117#else /* RT_OS_OS2 */
2118 int aFds[4] = { pThis->hNative, pThis->hNative, pThis->hNative, -1 };
2119 int rc = os2_select(aFds, 1, 1, 1, 0);
2120 if (rc > 0)
2121 {
2122 if (aFds[0] == pThis->hNative)
2123 fRetEvents |= RTPOLL_EVT_READ;
2124 if (aFds[1] == pThis->hNative)
2125 fRetEvents |= RTPOLL_EVT_WRITE;
2126 if (aFds[2] == pThis->hNative)
2127 fRetEvents |= RTPOLL_EVT_ERROR;
2128 fRetEvents &= fEvents;
2129 }
2130#endif /* RT_OS_OS2 */
2131
2132 LogFlowFunc(("fRetEvents=%#x\n", fRetEvents));
2133 return fRetEvents;
2134}
2135
2136
2137/**
2138 * Internal RTPoll helper that polls the socket handle and, if @a fNoWait is
2139 * clear, starts whatever actions we've got running during the poll call.
2140 *
2141 * @returns 0 if no pending events, actions initiated if @a fNoWait is clear.
2142 * Event mask (in @a fEvents) and no actions if the handle is ready
2143 * already.
2144 * UINT32_MAX (asserted) if the socket handle is busy in I/O or a
2145 * different poll set.
2146 *
2147 * @param hSocket The socket handle.
2148 * @param hPollSet The poll set handle (for access checks).
2149 * @param fEvents The events we're polling for.
2150 * @param fFinalEntry Set if this is the final entry for this handle
2151 * in this poll set. This can be used for dealing
2152 * with duplicate entries.
2153 * @param fNoWait Set if it's a zero-wait poll call. Clear if
2154 * we'll wait for an event to occur.
2155 *
2156 * @remarks There is a potential race wrt duplicate handles when @a fNoWait is
2157 * @c true, we don't currently care about that oddity...
2158 */
2159DECLHIDDEN(uint32_t) rtSocketPollStart(RTSOCKET hSocket, RTPOLLSET hPollSet, uint32_t fEvents, bool fFinalEntry, bool fNoWait)
2160{
2161 RTSOCKETINT *pThis = hSocket;
2162 AssertPtrReturn(pThis, UINT32_MAX);
2163 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, UINT32_MAX);
2164 /** @todo This isn't quite sane. Replace by critsect and open up concurrent
2165 * reads and writes! */
2166 if (rtSocketTryLock(pThis))
2167 pThis->hPollSet = hPollSet;
2168 else
2169 {
2170 AssertReturn(pThis->hPollSet == hPollSet, UINT32_MAX);
2171 ASMAtomicIncU32(&pThis->cUsers);
2172 }
2173
2174 /* (rtSocketPollCheck will reset the event object). */
2175# ifdef RT_OS_WINDOWS
2176 uint32_t fRetEvents = pThis->fEventsSaved;
2177 pThis->fEventsSaved = 0; /* Reset */
2178 fRetEvents |= rtSocketPollCheck(pThis, fEvents);
2179
2180 if ( !fRetEvents
2181 && !fNoWait)
2182 {
2183 pThis->fPollEvts |= fEvents;
2184 if ( fFinalEntry
2185 && pThis->fSubscribedEvts != pThis->fPollEvts)
2186 {
2187 int rc = rtSocketPollUpdateEvents(pThis, pThis->fPollEvts);
2188 if (RT_FAILURE(rc))
2189 {
2190 pThis->fPollEvts = 0;
2191 fRetEvents = UINT32_MAX;
2192 }
2193 }
2194 }
2195# else
2196 uint32_t fRetEvents = rtSocketPollCheck(pThis, fEvents);
2197# endif
2198
2199 if (fRetEvents || fNoWait)
2200 {
2201 if (pThis->cUsers == 1)
2202 {
2203# ifdef RT_OS_WINDOWS
2204 rtSocketPollClearEventAndRestoreBlocking(pThis);
2205# endif
2206 pThis->hPollSet = NIL_RTPOLLSET;
2207 }
2208 ASMAtomicDecU32(&pThis->cUsers);
2209 }
2210
2211 return fRetEvents;
2212}
2213
2214
2215/**
2216 * Called after a WaitForMultipleObjects returned in order to check for pending
2217 * events and stop whatever actions that rtSocketPollStart() initiated.
2218 *
2219 * @returns Event mask or 0.
2220 *
2221 * @param hSocket The socket handle.
2222 * @param fEvents The events we're polling for.
2223 * @param fFinalEntry Set if this is the final entry for this handle
2224 * in this poll set. This can be used for dealing
2225 * with duplicate entries. Only keep in mind that
2226 * this method is called in reverse order, so the
2227 * first call will have this set (when the entire
2228 * set was processed).
2229 * @param fHarvestEvents Set if we should check for pending events.
2230 */
2231DECLHIDDEN(uint32_t) rtSocketPollDone(RTSOCKET hSocket, uint32_t fEvents, bool fFinalEntry, bool fHarvestEvents)
2232{
2233 RTSOCKETINT *pThis = hSocket;
2234 AssertPtrReturn(pThis, 0);
2235 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, 0);
2236 Assert(pThis->cUsers > 0);
2237 Assert(pThis->hPollSet != NIL_RTPOLLSET);
2238
2239 /* Harvest events and clear the event mask for the next round of polling. */
2240 uint32_t fRetEvents = rtSocketPollCheck(pThis, fEvents);
2241# ifdef RT_OS_WINDOWS
2242 pThis->fPollEvts = 0;
2243
2244 /*
2245 * Save the write event if required.
2246 * It is only posted once and might get lost if the another source in the
2247 * pollset with a higher priority has pending events.
2248 */
2249 if ( !fHarvestEvents
2250 && fRetEvents)
2251 {
2252 pThis->fEventsSaved = fRetEvents;
2253 fRetEvents = 0;
2254 }
2255# endif
2256
2257 /* Make the socket blocking again and unlock the handle. */
2258 if (pThis->cUsers == 1)
2259 {
2260# ifdef RT_OS_WINDOWS
2261 rtSocketPollClearEventAndRestoreBlocking(pThis);
2262# endif
2263 pThis->hPollSet = NIL_RTPOLLSET;
2264 }
2265 ASMAtomicDecU32(&pThis->cUsers);
2266 return fRetEvents;
2267}
2268
2269#endif /* RT_OS_WINDOWS || RT_OS_OS2 */
2270
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