VirtualBox

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

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

IPRT: Unused parameters on windows.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 65.8 KB
Line 
1/* $Id: socket.cpp 62584 2016-07-27 11:46:03Z 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 <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 RTNETADDRTYPE enmAddrType = RTNETADDRTYPE_INVALID;
780 size_t cchIpAddress;
781 char szIpAddress[48];
782 if (pgrResult->ai_family == AF_INET)
783 {
784 struct sockaddr_in const *pgrSa = (struct sockaddr_in const *)pgrResult->ai_addr;
785 cchIpAddress = RTStrPrintf(szIpAddress, sizeof(szIpAddress),
786 "%RTnaipv4", pgrSa->sin_addr.s_addr);
787 Assert(cchIpAddress >= 7 && cchIpAddress < sizeof(szIpAddress) - 1);
788 enmAddrType = RTNETADDRTYPE_IPV4;
789 rc = VINF_SUCCESS;
790 }
791 else if (pgrResult->ai_family == AF_INET6)
792 {
793 struct sockaddr_in6 const *pgrSa6 = (struct sockaddr_in6 const *)pgrResult->ai_addr;
794 cchIpAddress = RTStrPrintf(szIpAddress, sizeof(szIpAddress),
795 "%RTnaipv6", (PRTNETADDRIPV6)&pgrSa6->sin6_addr);
796 enmAddrType = RTNETADDRTYPE_IPV6;
797 rc = VINF_SUCCESS;
798 }
799 else
800 {
801 rc = VERR_NET_ADDRESS_NOT_AVAILABLE;
802 szIpAddress[0] = '\0';
803 cchIpAddress = 0;
804 }
805 freeaddrinfo(pgrResults);
806
807 /*
808 * Copy out the result.
809 */
810 size_t const cbResult = *pcbResult;
811 *pcbResult = cchIpAddress + 1;
812 if (cchIpAddress < cbResult)
813 memcpy(pszResult, szIpAddress, cchIpAddress + 1);
814 else
815 {
816 RT_BZERO(pszResult, cbResult);
817 if (RT_SUCCESS(rc))
818 rc = VERR_BUFFER_OVERFLOW;
819 }
820 if (penmAddrType && RT_SUCCESS(rc))
821 *penmAddrType = enmAddrType;
822 return rc;
823#endif /* !RT_OS_OS2 */
824}
825
826
827RTDECL(int) RTSocketRead(RTSOCKET hSocket, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
828{
829 /*
830 * Validate input.
831 */
832 RTSOCKETINT *pThis = hSocket;
833 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
834 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
835 AssertReturn(cbBuffer > 0, VERR_INVALID_PARAMETER);
836 AssertPtr(pvBuffer);
837 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
838
839 int rc = rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
840 if (RT_FAILURE(rc))
841 return rc;
842
843 /*
844 * Read loop.
845 * If pcbRead is NULL we have to fill the entire buffer!
846 */
847 size_t cbRead = 0;
848 size_t cbToRead = cbBuffer;
849 for (;;)
850 {
851 rtSocketErrorReset();
852#ifdef RTSOCKET_MAX_READ
853 int cbNow = cbToRead >= RTSOCKET_MAX_READ ? RTSOCKET_MAX_READ : (int)cbToRead;
854#else
855 size_t cbNow = cbToRead;
856#endif
857 ssize_t cbBytesRead = recv(pThis->hNative, (char *)pvBuffer + cbRead, cbNow, MSG_NOSIGNAL);
858 if (cbBytesRead <= 0)
859 {
860 rc = rtSocketError();
861 Assert(RT_FAILURE_NP(rc) || cbBytesRead == 0);
862 if (RT_SUCCESS_NP(rc))
863 {
864 if (!pcbRead)
865 rc = VERR_NET_SHUTDOWN;
866 else
867 {
868 *pcbRead = 0;
869 rc = VINF_SUCCESS;
870 }
871 }
872 break;
873 }
874 if (pcbRead)
875 {
876 /* return partial data */
877 *pcbRead = cbBytesRead;
878 break;
879 }
880
881 /* read more? */
882 cbRead += cbBytesRead;
883 if (cbRead == cbBuffer)
884 break;
885
886 /* next */
887 cbToRead = cbBuffer - cbRead;
888 }
889
890 rtSocketUnlock(pThis);
891 return rc;
892}
893
894
895RTDECL(int) RTSocketReadFrom(RTSOCKET hSocket, void *pvBuffer, size_t cbBuffer, size_t *pcbRead, PRTNETADDR pSrcAddr)
896{
897 /*
898 * Validate input.
899 */
900 RTSOCKETINT *pThis = hSocket;
901 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
902 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
903 AssertReturn(cbBuffer > 0, VERR_INVALID_PARAMETER);
904 AssertPtr(pvBuffer);
905 AssertPtr(pcbRead);
906 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
907
908 int rc = rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
909 if (RT_FAILURE(rc))
910 return rc;
911
912 /*
913 * Read data.
914 */
915 size_t cbRead = 0;
916 size_t cbToRead = cbBuffer;
917 rtSocketErrorReset();
918 RTSOCKADDRUNION u;
919#ifdef RTSOCKET_MAX_READ
920 int cbNow = cbToRead >= RTSOCKET_MAX_READ ? RTSOCKET_MAX_READ : (int)cbToRead;
921 int cbAddr = sizeof(u);
922#else
923 size_t cbNow = cbToRead;
924 socklen_t cbAddr = sizeof(u);
925#endif
926 ssize_t cbBytesRead = recvfrom(pThis->hNative, (char *)pvBuffer + cbRead, cbNow, MSG_NOSIGNAL, &u.Addr, &cbAddr);
927 if (cbBytesRead <= 0)
928 {
929 rc = rtSocketError();
930 Assert(RT_FAILURE_NP(rc) || cbBytesRead == 0);
931 if (RT_SUCCESS_NP(rc))
932 {
933 *pcbRead = 0;
934 rc = VINF_SUCCESS;
935 }
936 }
937 else
938 {
939 if (pSrcAddr)
940 rc = rtSocketNetAddrFromAddr(&u, cbAddr, pSrcAddr);
941 *pcbRead = cbBytesRead;
942 }
943
944 rtSocketUnlock(pThis);
945 return rc;
946}
947
948
949RTDECL(int) RTSocketWrite(RTSOCKET hSocket, const void *pvBuffer, size_t cbBuffer)
950{
951 /*
952 * Validate input.
953 */
954 RTSOCKETINT *pThis = hSocket;
955 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
956 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
957 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
958
959 int rc = rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
960 if (RT_FAILURE(rc))
961 return rc;
962
963 /*
964 * Try write all at once.
965 */
966#ifdef RTSOCKET_MAX_WRITE
967 int cbNow = cbBuffer >= RTSOCKET_MAX_WRITE ? RTSOCKET_MAX_WRITE : (int)cbBuffer;
968#else
969 size_t cbNow = cbBuffer >= SSIZE_MAX ? SSIZE_MAX : cbBuffer;
970#endif
971 ssize_t cbWritten = send(pThis->hNative, (const char *)pvBuffer, cbNow, MSG_NOSIGNAL);
972 if (RT_LIKELY((size_t)cbWritten == cbBuffer && cbWritten >= 0))
973 rc = VINF_SUCCESS;
974 else if (cbWritten < 0)
975 rc = rtSocketError();
976 else
977 {
978 /*
979 * Unfinished business, write the remainder of the request. Must ignore
980 * VERR_INTERRUPTED here if we've managed to send something.
981 */
982 size_t cbSentSoFar = 0;
983 for (;;)
984 {
985 /* advance */
986 cbBuffer -= (size_t)cbWritten;
987 if (!cbBuffer)
988 break;
989 cbSentSoFar += (size_t)cbWritten;
990 pvBuffer = (char const *)pvBuffer + cbWritten;
991
992 /* send */
993#ifdef RTSOCKET_MAX_WRITE
994 cbNow = cbBuffer >= RTSOCKET_MAX_WRITE ? RTSOCKET_MAX_WRITE : (int)cbBuffer;
995#else
996 cbNow = cbBuffer >= SSIZE_MAX ? SSIZE_MAX : cbBuffer;
997#endif
998 cbWritten = send(pThis->hNative, (const char *)pvBuffer, cbNow, MSG_NOSIGNAL);
999 if (cbWritten >= 0)
1000 AssertMsg(cbBuffer >= (size_t)cbWritten, ("Wrote more than we requested!!! cbWritten=%zu cbBuffer=%zu rtSocketError()=%d\n",
1001 cbWritten, cbBuffer, rtSocketError()));
1002 else
1003 {
1004 rc = rtSocketError();
1005 if (rc != VERR_INTERNAL_ERROR || cbSentSoFar == 0)
1006 break;
1007 cbWritten = 0;
1008 rc = VINF_SUCCESS;
1009 }
1010 }
1011 }
1012
1013 rtSocketUnlock(pThis);
1014 return rc;
1015}
1016
1017
1018RTDECL(int) RTSocketWriteTo(RTSOCKET hSocket, const void *pvBuffer, size_t cbBuffer, PCRTNETADDR pAddr)
1019{
1020 /*
1021 * Validate input.
1022 */
1023 RTSOCKETINT *pThis = hSocket;
1024 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1025 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1026
1027 /* no locking since UDP reads may be done concurrently to writes, and
1028 * this is the normal use case of this code. */
1029
1030 int rc = rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
1031 if (RT_FAILURE(rc))
1032 return rc;
1033
1034 /* Figure out destination address. */
1035 struct sockaddr *pSA = NULL;
1036#ifdef RT_OS_WINDOWS
1037 int cbSA = 0;
1038#else
1039 socklen_t cbSA = 0;
1040#endif
1041 RTSOCKADDRUNION u;
1042 if (pAddr)
1043 {
1044 rc = rtSocketAddrFromNetAddr(pAddr, &u, sizeof(u), NULL);
1045 if (RT_FAILURE(rc))
1046 return rc;
1047 pSA = &u.Addr;
1048 cbSA = sizeof(u);
1049 }
1050
1051 /*
1052 * Must write all at once, otherwise it is a failure.
1053 */
1054#ifdef RT_OS_WINDOWS
1055 int cbNow = cbBuffer >= RTSOCKET_MAX_WRITE ? RTSOCKET_MAX_WRITE : (int)cbBuffer;
1056#else
1057 size_t cbNow = cbBuffer >= SSIZE_MAX ? SSIZE_MAX : cbBuffer;
1058#endif
1059 ssize_t cbWritten = sendto(pThis->hNative, (const char *)pvBuffer, cbNow, MSG_NOSIGNAL, pSA, cbSA);
1060 if (RT_LIKELY((size_t)cbWritten == cbBuffer && cbWritten >= 0))
1061 rc = VINF_SUCCESS;
1062 else if (cbWritten < 0)
1063 rc = rtSocketError();
1064 else
1065 rc = VERR_TOO_MUCH_DATA;
1066
1067 rtSocketUnlock(pThis);
1068 return rc;
1069}
1070
1071
1072RTDECL(int) RTSocketWriteToNB(RTSOCKET hSocket, const void *pvBuffer, size_t cbBuffer, PCRTNETADDR pAddr)
1073{
1074 /*
1075 * Validate input.
1076 */
1077 RTSOCKETINT *pThis = hSocket;
1078 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1079 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1080
1081 /* no locking since UDP reads may be done concurrently to writes, and
1082 * this is the normal use case of this code. */
1083
1084 int rc = rtSocketSwitchBlockingMode(pThis, false /* fBlocking */);
1085 if (RT_FAILURE(rc))
1086 return rc;
1087
1088 /* Figure out destination address. */
1089 struct sockaddr *pSA = NULL;
1090#ifdef RT_OS_WINDOWS
1091 int cbSA = 0;
1092#else
1093 socklen_t cbSA = 0;
1094#endif
1095 RTSOCKADDRUNION u;
1096 if (pAddr)
1097 {
1098 rc = rtSocketAddrFromNetAddr(pAddr, &u, sizeof(u), NULL);
1099 if (RT_FAILURE(rc))
1100 return rc;
1101 pSA = &u.Addr;
1102 cbSA = sizeof(u);
1103 }
1104
1105 /*
1106 * Must write all at once, otherwise it is a failure.
1107 */
1108#ifdef RT_OS_WINDOWS
1109 int cbNow = cbBuffer >= RTSOCKET_MAX_WRITE ? RTSOCKET_MAX_WRITE : (int)cbBuffer;
1110#else
1111 size_t cbNow = cbBuffer >= SSIZE_MAX ? SSIZE_MAX : cbBuffer;
1112#endif
1113 ssize_t cbWritten = sendto(pThis->hNative, (const char *)pvBuffer, cbNow, MSG_NOSIGNAL, pSA, cbSA);
1114 if (RT_LIKELY((size_t)cbWritten == cbBuffer && cbWritten >= 0))
1115 rc = VINF_SUCCESS;
1116 else if (cbWritten < 0)
1117 rc = rtSocketError();
1118 else
1119 rc = VERR_TOO_MUCH_DATA;
1120
1121 rtSocketUnlock(pThis);
1122 return rc;
1123}
1124
1125
1126RTDECL(int) RTSocketSgWrite(RTSOCKET hSocket, PCRTSGBUF pSgBuf)
1127{
1128 /*
1129 * Validate input.
1130 */
1131 RTSOCKETINT *pThis = hSocket;
1132 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1133 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1134 AssertPtrReturn(pSgBuf, VERR_INVALID_PARAMETER);
1135 AssertReturn(pSgBuf->cSegs > 0, VERR_INVALID_PARAMETER);
1136 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1137
1138 int rc = rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
1139 if (RT_FAILURE(rc))
1140 return rc;
1141
1142 /*
1143 * Construct message descriptor (translate pSgBuf) and send it.
1144 */
1145 rc = VERR_NO_TMP_MEMORY;
1146#ifdef RT_OS_WINDOWS
1147 AssertCompileSize(WSABUF, sizeof(RTSGSEG));
1148 AssertCompileMemberSize(WSABUF, buf, RT_SIZEOFMEMB(RTSGSEG, pvSeg));
1149
1150 LPWSABUF paMsg = (LPWSABUF)RTMemTmpAllocZ(pSgBuf->cSegs * sizeof(WSABUF));
1151 if (paMsg)
1152 {
1153 for (unsigned i = 0; i < pSgBuf->cSegs; i++)
1154 {
1155 paMsg[i].buf = (char *)pSgBuf->paSegs[i].pvSeg;
1156 paMsg[i].len = (u_long)pSgBuf->paSegs[i].cbSeg;
1157 }
1158
1159 DWORD dwSent;
1160 int hrc = WSASend(pThis->hNative, paMsg, pSgBuf->cSegs, &dwSent,
1161 MSG_NOSIGNAL, NULL, NULL);
1162 if (!hrc)
1163 rc = VINF_SUCCESS;
1164/** @todo check for incomplete writes */
1165 else
1166 rc = rtSocketError();
1167
1168 RTMemTmpFree(paMsg);
1169 }
1170
1171#else /* !RT_OS_WINDOWS */
1172 AssertCompileSize(struct iovec, sizeof(RTSGSEG));
1173 AssertCompileMemberSize(struct iovec, iov_base, RT_SIZEOFMEMB(RTSGSEG, pvSeg));
1174 AssertCompileMemberSize(struct iovec, iov_len, RT_SIZEOFMEMB(RTSGSEG, cbSeg));
1175
1176 struct iovec *paMsg = (struct iovec *)RTMemTmpAllocZ(pSgBuf->cSegs * sizeof(struct iovec));
1177 if (paMsg)
1178 {
1179 for (unsigned i = 0; i < pSgBuf->cSegs; i++)
1180 {
1181 paMsg[i].iov_base = pSgBuf->paSegs[i].pvSeg;
1182 paMsg[i].iov_len = pSgBuf->paSegs[i].cbSeg;
1183 }
1184
1185 struct msghdr msgHdr;
1186 RT_ZERO(msgHdr);
1187 msgHdr.msg_iov = paMsg;
1188 msgHdr.msg_iovlen = pSgBuf->cSegs;
1189 ssize_t cbWritten = sendmsg(pThis->hNative, &msgHdr, MSG_NOSIGNAL);
1190 if (RT_LIKELY(cbWritten >= 0))
1191 rc = VINF_SUCCESS;
1192/** @todo check for incomplete writes */
1193 else
1194 rc = rtSocketError();
1195
1196 RTMemTmpFree(paMsg);
1197 }
1198#endif /* !RT_OS_WINDOWS */
1199
1200 rtSocketUnlock(pThis);
1201 return rc;
1202}
1203
1204
1205RTDECL(int) RTSocketSgWriteL(RTSOCKET hSocket, size_t cSegs, ...)
1206{
1207 va_list va;
1208 va_start(va, cSegs);
1209 int rc = RTSocketSgWriteLV(hSocket, cSegs, va);
1210 va_end(va);
1211 return rc;
1212}
1213
1214
1215RTDECL(int) RTSocketSgWriteLV(RTSOCKET hSocket, size_t cSegs, va_list va)
1216{
1217 /*
1218 * Set up a S/G segment array + buffer on the stack and pass it
1219 * on to RTSocketSgWrite.
1220 */
1221 Assert(cSegs <= 16);
1222 PRTSGSEG paSegs = (PRTSGSEG)alloca(cSegs * sizeof(RTSGSEG));
1223 AssertReturn(paSegs, VERR_NO_TMP_MEMORY);
1224 for (size_t i = 0; i < cSegs; i++)
1225 {
1226 paSegs[i].pvSeg = va_arg(va, void *);
1227 paSegs[i].cbSeg = va_arg(va, size_t);
1228 }
1229
1230 RTSGBUF SgBuf;
1231 RTSgBufInit(&SgBuf, paSegs, cSegs);
1232 return RTSocketSgWrite(hSocket, &SgBuf);
1233}
1234
1235
1236RTDECL(int) RTSocketReadNB(RTSOCKET hSocket, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
1237{
1238 /*
1239 * Validate input.
1240 */
1241 RTSOCKETINT *pThis = hSocket;
1242 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1243 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1244 AssertReturn(cbBuffer > 0, VERR_INVALID_PARAMETER);
1245 AssertPtr(pvBuffer);
1246 AssertPtrReturn(pcbRead, VERR_INVALID_PARAMETER);
1247 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1248
1249 int rc = rtSocketSwitchBlockingMode(pThis, false /* fBlocking */);
1250 if (RT_FAILURE(rc))
1251 return rc;
1252
1253 rtSocketErrorReset();
1254#ifdef RTSOCKET_MAX_READ
1255 int cbNow = cbBuffer >= RTSOCKET_MAX_WRITE ? RTSOCKET_MAX_WRITE : (int)cbBuffer;
1256#else
1257 size_t cbNow = cbBuffer;
1258#endif
1259
1260#ifdef RT_OS_WINDOWS
1261 int cbRead = recv(pThis->hNative, (char *)pvBuffer, cbNow, MSG_NOSIGNAL);
1262 if (cbRead >= 0)
1263 {
1264 *pcbRead = cbRead;
1265 rc = VINF_SUCCESS;
1266 }
1267 else
1268 {
1269 rc = rtSocketError();
1270 if (rc == VERR_TRY_AGAIN)
1271 {
1272 *pcbRead = 0;
1273 rc = VINF_TRY_AGAIN;
1274 }
1275 }
1276
1277#else
1278 ssize_t cbRead = recv(pThis->hNative, pvBuffer, cbNow, MSG_NOSIGNAL);
1279 if (cbRead >= 0)
1280 *pcbRead = cbRead;
1281 else if ( errno == EAGAIN
1282# ifdef EWOULDBLOCK
1283# if EWOULDBLOCK != EAGAIN
1284 || errno == EWOULDBLOCK
1285# endif
1286# endif
1287 )
1288 {
1289 *pcbRead = 0;
1290 rc = VINF_TRY_AGAIN;
1291 }
1292 else
1293 rc = rtSocketError();
1294#endif
1295
1296 rtSocketUnlock(pThis);
1297 return rc;
1298}
1299
1300
1301RTDECL(int) RTSocketWriteNB(RTSOCKET hSocket, const void *pvBuffer, size_t cbBuffer, size_t *pcbWritten)
1302{
1303 /*
1304 * Validate input.
1305 */
1306 RTSOCKETINT *pThis = hSocket;
1307 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1308 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1309 AssertPtrReturn(pcbWritten, VERR_INVALID_PARAMETER);
1310 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1311
1312 int rc = rtSocketSwitchBlockingMode(pThis, false /* fBlocking */);
1313 if (RT_FAILURE(rc))
1314 return rc;
1315
1316 rtSocketErrorReset();
1317#ifdef RT_OS_WINDOWS
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 int cbWritten = send(pThis->hNative, (const char *)pvBuffer, cbNow, MSG_NOSIGNAL);
1324 if (cbWritten >= 0)
1325 {
1326 *pcbWritten = cbWritten;
1327 rc = VINF_SUCCESS;
1328 }
1329 else
1330 {
1331 rc = rtSocketError();
1332 if (rc == VERR_TRY_AGAIN)
1333 {
1334 *pcbWritten = 0;
1335 rc = VINF_TRY_AGAIN;
1336 }
1337 }
1338#else
1339 ssize_t cbWritten = send(pThis->hNative, pvBuffer, cbBuffer, MSG_NOSIGNAL);
1340 if (cbWritten >= 0)
1341 *pcbWritten = cbWritten;
1342 else if ( errno == EAGAIN
1343# ifdef EWOULDBLOCK
1344# if EWOULDBLOCK != EAGAIN
1345 || errno == EWOULDBLOCK
1346# endif
1347# endif
1348 )
1349 {
1350 *pcbWritten = 0;
1351 rc = VINF_TRY_AGAIN;
1352 }
1353 else
1354 rc = rtSocketError();
1355#endif
1356
1357 rtSocketUnlock(pThis);
1358 return rc;
1359}
1360
1361
1362RTDECL(int) RTSocketSgWriteNB(RTSOCKET hSocket, PCRTSGBUF pSgBuf, size_t *pcbWritten)
1363{
1364 /*
1365 * Validate input.
1366 */
1367 RTSOCKETINT *pThis = hSocket;
1368 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1369 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1370 AssertPtrReturn(pSgBuf, VERR_INVALID_PARAMETER);
1371 AssertPtrReturn(pcbWritten, VERR_INVALID_PARAMETER);
1372 AssertReturn(pSgBuf->cSegs > 0, VERR_INVALID_PARAMETER);
1373 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1374
1375 int rc = rtSocketSwitchBlockingMode(pThis, false /* fBlocking */);
1376 if (RT_FAILURE(rc))
1377 return rc;
1378
1379 unsigned cSegsToSend = 0;
1380 rc = VERR_NO_TMP_MEMORY;
1381#ifdef RT_OS_WINDOWS
1382 LPWSABUF paMsg = NULL;
1383
1384 RTSgBufMapToNative(paMsg, pSgBuf, WSABUF, buf, char *, len, u_long, cSegsToSend);
1385 if (paMsg)
1386 {
1387 DWORD dwSent = 0;
1388 int hrc = WSASend(pThis->hNative, paMsg, cSegsToSend, &dwSent,
1389 MSG_NOSIGNAL, NULL, NULL);
1390 if (!hrc)
1391 rc = VINF_SUCCESS;
1392 else
1393 rc = rtSocketError();
1394
1395 *pcbWritten = dwSent;
1396
1397 RTMemTmpFree(paMsg);
1398 }
1399
1400#else /* !RT_OS_WINDOWS */
1401 struct iovec *paMsg = NULL;
1402
1403 RTSgBufMapToNative(paMsg, pSgBuf, struct iovec, iov_base, void *, iov_len, size_t, cSegsToSend);
1404 if (paMsg)
1405 {
1406 struct msghdr msgHdr;
1407 RT_ZERO(msgHdr);
1408 msgHdr.msg_iov = paMsg;
1409 msgHdr.msg_iovlen = cSegsToSend;
1410 ssize_t cbWritten = sendmsg(pThis->hNative, &msgHdr, MSG_NOSIGNAL);
1411 if (RT_LIKELY(cbWritten >= 0))
1412 {
1413 rc = VINF_SUCCESS;
1414 *pcbWritten = cbWritten;
1415 }
1416 else
1417 rc = rtSocketError();
1418
1419 RTMemTmpFree(paMsg);
1420 }
1421#endif /* !RT_OS_WINDOWS */
1422
1423 rtSocketUnlock(pThis);
1424 return rc;
1425}
1426
1427
1428RTDECL(int) RTSocketSgWriteLNB(RTSOCKET hSocket, size_t cSegs, size_t *pcbWritten, ...)
1429{
1430 va_list va;
1431 va_start(va, pcbWritten);
1432 int rc = RTSocketSgWriteLVNB(hSocket, cSegs, pcbWritten, va);
1433 va_end(va);
1434 return rc;
1435}
1436
1437
1438RTDECL(int) RTSocketSgWriteLVNB(RTSOCKET hSocket, size_t cSegs, size_t *pcbWritten, va_list va)
1439{
1440 /*
1441 * Set up a S/G segment array + buffer on the stack and pass it
1442 * on to RTSocketSgWrite.
1443 */
1444 Assert(cSegs <= 16);
1445 PRTSGSEG paSegs = (PRTSGSEG)alloca(cSegs * sizeof(RTSGSEG));
1446 AssertReturn(paSegs, VERR_NO_TMP_MEMORY);
1447 for (size_t i = 0; i < cSegs; i++)
1448 {
1449 paSegs[i].pvSeg = va_arg(va, void *);
1450 paSegs[i].cbSeg = va_arg(va, size_t);
1451 }
1452
1453 RTSGBUF SgBuf;
1454 RTSgBufInit(&SgBuf, paSegs, cSegs);
1455 return RTSocketSgWriteNB(hSocket, &SgBuf, pcbWritten);
1456}
1457
1458
1459RTDECL(int) RTSocketSelectOne(RTSOCKET hSocket, RTMSINTERVAL cMillies)
1460{
1461 /*
1462 * Validate input.
1463 */
1464 RTSOCKETINT *pThis = hSocket;
1465 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1466 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1467 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
1468 int const fdMax = (int)pThis->hNative + 1;
1469 AssertReturn((RTSOCKETNATIVE)(fdMax - 1) == pThis->hNative, VERR_INTERNAL_ERROR_5);
1470
1471 /*
1472 * Set up the file descriptor sets and do the select.
1473 */
1474 fd_set fdsetR;
1475 FD_ZERO(&fdsetR);
1476 FD_SET(pThis->hNative, &fdsetR);
1477
1478 fd_set fdsetE = fdsetR;
1479
1480 int rc;
1481 if (cMillies == RT_INDEFINITE_WAIT)
1482 rc = select(fdMax, &fdsetR, NULL, &fdsetE, NULL);
1483 else
1484 {
1485 struct timeval timeout;
1486 timeout.tv_sec = cMillies / 1000;
1487 timeout.tv_usec = (cMillies % 1000) * 1000;
1488 rc = select(fdMax, &fdsetR, NULL, &fdsetE, &timeout);
1489 }
1490 if (rc > 0)
1491 rc = VINF_SUCCESS;
1492 else if (rc == 0)
1493 rc = VERR_TIMEOUT;
1494 else
1495 rc = rtSocketError();
1496
1497 return rc;
1498}
1499
1500
1501RTDECL(int) RTSocketSelectOneEx(RTSOCKET hSocket, uint32_t fEvents, uint32_t *pfEvents, RTMSINTERVAL cMillies)
1502{
1503 /*
1504 * Validate input.
1505 */
1506 RTSOCKETINT *pThis = hSocket;
1507 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1508 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1509 AssertPtrReturn(pfEvents, VERR_INVALID_PARAMETER);
1510 AssertReturn(!(fEvents & ~RTSOCKET_EVT_VALID_MASK), VERR_INVALID_PARAMETER);
1511 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
1512 int const fdMax = (int)pThis->hNative + 1;
1513 AssertReturn((RTSOCKETNATIVE)(fdMax - 1) == pThis->hNative, VERR_INTERNAL_ERROR_5);
1514
1515 *pfEvents = 0;
1516
1517 /*
1518 * Set up the file descriptor sets and do the select.
1519 */
1520 fd_set fdsetR;
1521 fd_set fdsetW;
1522 fd_set fdsetE;
1523 FD_ZERO(&fdsetR);
1524 FD_ZERO(&fdsetW);
1525 FD_ZERO(&fdsetE);
1526
1527 if (fEvents & RTSOCKET_EVT_READ)
1528 FD_SET(pThis->hNative, &fdsetR);
1529 if (fEvents & RTSOCKET_EVT_WRITE)
1530 FD_SET(pThis->hNative, &fdsetW);
1531 if (fEvents & RTSOCKET_EVT_ERROR)
1532 FD_SET(pThis->hNative, &fdsetE);
1533
1534 int rc;
1535 if (cMillies == RT_INDEFINITE_WAIT)
1536 rc = select(fdMax, &fdsetR, &fdsetW, &fdsetE, NULL);
1537 else
1538 {
1539 struct timeval timeout;
1540 timeout.tv_sec = cMillies / 1000;
1541 timeout.tv_usec = (cMillies % 1000) * 1000;
1542 rc = select(fdMax, &fdsetR, &fdsetW, &fdsetE, &timeout);
1543 }
1544 if (rc > 0)
1545 {
1546 if (FD_ISSET(pThis->hNative, &fdsetR))
1547 *pfEvents |= RTSOCKET_EVT_READ;
1548 if (FD_ISSET(pThis->hNative, &fdsetW))
1549 *pfEvents |= RTSOCKET_EVT_WRITE;
1550 if (FD_ISSET(pThis->hNative, &fdsetE))
1551 *pfEvents |= RTSOCKET_EVT_ERROR;
1552
1553 rc = VINF_SUCCESS;
1554 }
1555 else if (rc == 0)
1556 rc = VERR_TIMEOUT;
1557 else
1558 rc = rtSocketError();
1559
1560 return rc;
1561}
1562
1563
1564RTDECL(int) RTSocketShutdown(RTSOCKET hSocket, bool fRead, bool fWrite)
1565{
1566 /*
1567 * Validate input, don't lock it because we might want to interrupt a call
1568 * active on a different thread.
1569 */
1570 RTSOCKETINT *pThis = hSocket;
1571 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1572 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1573 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
1574 AssertReturn(fRead || fWrite, VERR_INVALID_PARAMETER);
1575
1576 /*
1577 * Do the job.
1578 */
1579 int rc = VINF_SUCCESS;
1580 int fHow;
1581 if (fRead && fWrite)
1582 fHow = SHUT_RDWR;
1583 else if (fRead)
1584 fHow = SHUT_RD;
1585 else
1586 fHow = SHUT_WR;
1587 if (shutdown(pThis->hNative, fHow) == -1)
1588 rc = rtSocketError();
1589
1590 return rc;
1591}
1592
1593
1594RTDECL(int) RTSocketGetLocalAddress(RTSOCKET hSocket, PRTNETADDR pAddr)
1595{
1596 /*
1597 * Validate input.
1598 */
1599 RTSOCKETINT *pThis = hSocket;
1600 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1601 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1602 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
1603
1604 /*
1605 * Get the address and convert it.
1606 */
1607 int rc;
1608 RTSOCKADDRUNION u;
1609#ifdef RT_OS_WINDOWS
1610 int cbAddr = sizeof(u);
1611#else
1612 socklen_t cbAddr = sizeof(u);
1613#endif
1614 RT_ZERO(u);
1615 if (getsockname(pThis->hNative, &u.Addr, &cbAddr) == 0)
1616 rc = rtSocketNetAddrFromAddr(&u, cbAddr, pAddr);
1617 else
1618 rc = rtSocketError();
1619
1620 return rc;
1621}
1622
1623
1624RTDECL(int) RTSocketGetPeerAddress(RTSOCKET hSocket, PRTNETADDR pAddr)
1625{
1626 /*
1627 * Validate input.
1628 */
1629 RTSOCKETINT *pThis = hSocket;
1630 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1631 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1632 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
1633
1634 /*
1635 * Get the address and convert it.
1636 */
1637 int rc;
1638 RTSOCKADDRUNION u;
1639#ifdef RT_OS_WINDOWS
1640 int cbAddr = sizeof(u);
1641#else
1642 socklen_t cbAddr = sizeof(u);
1643#endif
1644 RT_ZERO(u);
1645 if (getpeername(pThis->hNative, &u.Addr, &cbAddr) == 0)
1646 rc = rtSocketNetAddrFromAddr(&u, cbAddr, pAddr);
1647 else
1648 rc = rtSocketError();
1649
1650 return rc;
1651}
1652
1653
1654
1655/**
1656 * Wrapper around bind.
1657 *
1658 * @returns IPRT status code.
1659 * @param hSocket The socket handle.
1660 * @param pAddr The address to bind to.
1661 */
1662DECLHIDDEN(int) rtSocketBind(RTSOCKET hSocket, PCRTNETADDR pAddr)
1663{
1664 RTSOCKADDRUNION u;
1665 int cbAddr;
1666 int rc = rtSocketAddrFromNetAddr(pAddr, &u, sizeof(u), &cbAddr);
1667 if (RT_SUCCESS(rc))
1668 rc = rtSocketBindRawAddr(hSocket, &u.Addr, cbAddr);
1669 return rc;
1670}
1671
1672
1673/**
1674 * Very thin wrapper around bind.
1675 *
1676 * @returns IPRT status code.
1677 * @param hSocket The socket handle.
1678 * @param pvAddr The address to bind to (struct sockaddr and
1679 * friends).
1680 * @param cbAddr The size of the address.
1681 */
1682DECLHIDDEN(int) rtSocketBindRawAddr(RTSOCKET hSocket, void const *pvAddr, size_t cbAddr)
1683{
1684 /*
1685 * Validate input.
1686 */
1687 RTSOCKETINT *pThis = hSocket;
1688 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1689 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1690 AssertPtrReturn(pvAddr, VERR_INVALID_POINTER);
1691 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1692
1693 int rc;
1694 if (bind(pThis->hNative, (struct sockaddr const *)pvAddr, (int)cbAddr) == 0)
1695 rc = VINF_SUCCESS;
1696 else
1697 rc = rtSocketError();
1698
1699 rtSocketUnlock(pThis);
1700 return rc;
1701}
1702
1703
1704
1705/**
1706 * Wrapper around listen.
1707 *
1708 * @returns IPRT status code.
1709 * @param hSocket The socket handle.
1710 * @param cMaxPending The max number of pending connections.
1711 */
1712DECLHIDDEN(int) rtSocketListen(RTSOCKET hSocket, int cMaxPending)
1713{
1714 /*
1715 * Validate input.
1716 */
1717 RTSOCKETINT *pThis = hSocket;
1718 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1719 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1720 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1721
1722 int rc = VINF_SUCCESS;
1723 if (listen(pThis->hNative, cMaxPending) != 0)
1724 rc = rtSocketError();
1725
1726 rtSocketUnlock(pThis);
1727 return rc;
1728}
1729
1730
1731/**
1732 * Wrapper around accept.
1733 *
1734 * @returns IPRT status code.
1735 * @param hSocket The socket handle.
1736 * @param phClient Where to return the client socket handle on
1737 * success.
1738 * @param pAddr Where to return the client address.
1739 * @param pcbAddr On input this gives the size buffer size of what
1740 * @a pAddr point to. On return this contains the
1741 * size of what's stored at @a pAddr.
1742 */
1743DECLHIDDEN(int) rtSocketAccept(RTSOCKET hSocket, PRTSOCKET phClient, struct sockaddr *pAddr, size_t *pcbAddr)
1744{
1745 /*
1746 * Validate input.
1747 * Only lock the socket temporarily while we get the native handle, so that
1748 * we can safely shutdown and destroy the socket from a different thread.
1749 */
1750 RTSOCKETINT *pThis = hSocket;
1751 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1752 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1753 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1754
1755 /*
1756 * Call accept().
1757 */
1758 rtSocketErrorReset();
1759 int rc = VINF_SUCCESS;
1760#ifdef RT_OS_WINDOWS
1761 int cbAddr = (int)*pcbAddr;
1762#else
1763 socklen_t cbAddr = *pcbAddr;
1764#endif
1765 RTSOCKETNATIVE hNativeClient = accept(pThis->hNative, pAddr, &cbAddr);
1766 if (hNativeClient != NIL_RTSOCKETNATIVE)
1767 {
1768 *pcbAddr = cbAddr;
1769
1770 /*
1771 * Wrap the client socket.
1772 */
1773 rc = rtSocketCreateForNative(phClient, hNativeClient);
1774 if (RT_FAILURE(rc))
1775 {
1776#ifdef RT_OS_WINDOWS
1777 closesocket(hNativeClient);
1778#else
1779 close(hNativeClient);
1780#endif
1781 }
1782 }
1783 else
1784 rc = rtSocketError();
1785
1786 rtSocketUnlock(pThis);
1787 return rc;
1788}
1789
1790
1791/**
1792 * Wrapper around connect.
1793 *
1794 * @returns IPRT status code.
1795 * @param hSocket The socket handle.
1796 * @param pAddr The socket address to connect to.
1797 * @param cMillies Number of milliseconds to wait for the connect attempt to complete.
1798 * Use RT_INDEFINITE_WAIT to wait for ever.
1799 * Use RT_TCPCLIENTCONNECT_DEFAULT_WAIT to wait for the default time
1800 * configured on the running system.
1801 */
1802DECLHIDDEN(int) rtSocketConnect(RTSOCKET hSocket, PCRTNETADDR pAddr, RTMSINTERVAL cMillies)
1803{
1804 /*
1805 * Validate input.
1806 */
1807 RTSOCKETINT *pThis = hSocket;
1808 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1809 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1810 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1811
1812 RTSOCKADDRUNION u;
1813 int cbAddr;
1814 int rc = rtSocketAddrFromNetAddr(pAddr, &u, sizeof(u), &cbAddr);
1815 if (RT_SUCCESS(rc))
1816 {
1817 if (cMillies == RT_SOCKETCONNECT_DEFAULT_WAIT)
1818 {
1819 if (connect(pThis->hNative, &u.Addr, cbAddr) != 0)
1820 rc = rtSocketError();
1821 }
1822 else
1823 {
1824 /*
1825 * Switch the socket to nonblocking mode, initiate the connect
1826 * and wait for the socket to become writable or until the timeout
1827 * expires.
1828 */
1829 rc = rtSocketSwitchBlockingMode(pThis, false /* fBlocking */);
1830 if (RT_SUCCESS(rc))
1831 {
1832 if (connect(pThis->hNative, &u.Addr, cbAddr) != 0)
1833 {
1834 rc = rtSocketError();
1835 if (rc == VERR_TRY_AGAIN || rc == VERR_NET_IN_PROGRESS)
1836 {
1837 int rcSock = 0;
1838 fd_set FdSetWriteable;
1839 struct timeval TvTimeout;
1840
1841 TvTimeout.tv_sec = cMillies / RT_MS_1SEC;
1842 TvTimeout.tv_usec = (cMillies % RT_MS_1SEC) * RT_US_1MS;
1843
1844 FD_ZERO(&FdSetWriteable);
1845 FD_SET(pThis->hNative, &FdSetWriteable);
1846 do
1847 {
1848 rcSock = select(pThis->hNative + 1, NULL, &FdSetWriteable, NULL,
1849 cMillies == RT_INDEFINITE_WAIT || cMillies >= INT_MAX
1850 ? NULL
1851 : &TvTimeout);
1852 if (rcSock > 0)
1853 {
1854 int iSockError = 0;
1855 socklen_t cbSockOpt = sizeof(iSockError);
1856 rcSock = getsockopt(pThis->hNative, SOL_SOCKET, SO_ERROR, (char *)&iSockError, &cbSockOpt);
1857 if (rcSock == 0)
1858 {
1859 if (iSockError == 0)
1860 rc = VINF_SUCCESS;
1861 else
1862 {
1863#ifdef RT_OS_WINDOWS
1864 rc = RTErrConvertFromWin32(iSockError);
1865#else
1866 rc = RTErrConvertFromErrno(iSockError);
1867#endif
1868 }
1869 }
1870 else
1871 rc = rtSocketError();
1872 }
1873 else if (rcSock == 0)
1874 rc = VERR_TIMEOUT;
1875 else
1876 rc = rtSocketError();
1877 } while (rc == VERR_INTERRUPTED);
1878 }
1879 }
1880
1881 rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
1882 }
1883 }
1884 }
1885
1886 rtSocketUnlock(pThis);
1887 return rc;
1888}
1889
1890
1891/**
1892 * Wrapper around connect, raw address, no timeout.
1893 *
1894 * @returns IPRT status code.
1895 * @param hSocket The socket handle.
1896 * @param pvAddr The raw socket address to connect to.
1897 * @param cbAddr The size of the raw address.
1898 */
1899DECLHIDDEN(int) rtSocketConnectRaw(RTSOCKET hSocket, void const *pvAddr, size_t cbAddr)
1900{
1901 /*
1902 * Validate input.
1903 */
1904 RTSOCKETINT *pThis = hSocket;
1905 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1906 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1907 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1908
1909 int rc;
1910 if (connect(pThis->hNative, (const struct sockaddr *)pvAddr, (int)cbAddr) == 0)
1911 rc = VINF_SUCCESS;
1912 else
1913 rc = rtSocketError();
1914
1915 rtSocketUnlock(pThis);
1916 return rc;
1917}
1918
1919
1920/**
1921 * Wrapper around setsockopt.
1922 *
1923 * @returns IPRT status code.
1924 * @param hSocket The socket handle.
1925 * @param iLevel The protocol level, e.g. IPPORTO_TCP.
1926 * @param iOption The option, e.g. TCP_NODELAY.
1927 * @param pvValue The value buffer.
1928 * @param cbValue The size of the value pointed to by pvValue.
1929 */
1930DECLHIDDEN(int) rtSocketSetOpt(RTSOCKET hSocket, int iLevel, int iOption, void const *pvValue, int cbValue)
1931{
1932 /*
1933 * Validate input.
1934 */
1935 RTSOCKETINT *pThis = hSocket;
1936 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1937 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1938 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1939
1940 int rc = VINF_SUCCESS;
1941 if (setsockopt(pThis->hNative, iLevel, iOption, (const char *)pvValue, cbValue) != 0)
1942 rc = rtSocketError();
1943
1944 rtSocketUnlock(pThis);
1945 return rc;
1946}
1947
1948
1949/**
1950 * Internal RTPollSetAdd helper that returns the handle that should be added to
1951 * the pollset.
1952 *
1953 * @returns Valid handle on success, INVALID_HANDLE_VALUE on failure.
1954 * @param hSocket The socket handle.
1955 * @param fEvents The events we're polling for.
1956 * @param phNative Where to put the primary handle.
1957 */
1958DECLHIDDEN(int) rtSocketPollGetHandle(RTSOCKET hSocket, uint32_t fEvents, PRTHCINTPTR phNative)
1959{
1960 RTSOCKETINT *pThis = hSocket;
1961 RT_NOREF_PV(fEvents);
1962 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1963 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1964#ifdef RT_OS_WINDOWS
1965 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1966
1967 int rc = VINF_SUCCESS;
1968 if (pThis->hEvent != WSA_INVALID_EVENT)
1969 *phNative = (RTHCINTPTR)pThis->hEvent;
1970 else
1971 {
1972 pThis->hEvent = WSACreateEvent();
1973 *phNative = (RTHCINTPTR)pThis->hEvent;
1974 if (pThis->hEvent == WSA_INVALID_EVENT)
1975 rc = rtSocketError();
1976 }
1977
1978 rtSocketUnlock(pThis);
1979 return rc;
1980
1981#else /* !RT_OS_WINDOWS */
1982 *phNative = (RTHCUINTPTR)pThis->hNative;
1983 return VINF_SUCCESS;
1984#endif /* !RT_OS_WINDOWS */
1985}
1986
1987#ifdef RT_OS_WINDOWS
1988
1989/**
1990 * Undos the harm done by WSAEventSelect.
1991 *
1992 * @returns IPRT status code.
1993 * @param pThis The socket handle.
1994 */
1995static int rtSocketPollClearEventAndRestoreBlocking(RTSOCKETINT *pThis)
1996{
1997 int rc = VINF_SUCCESS;
1998 if (pThis->fSubscribedEvts)
1999 {
2000 if (WSAEventSelect(pThis->hNative, WSA_INVALID_EVENT, 0) == 0)
2001 {
2002 pThis->fSubscribedEvts = 0;
2003
2004 /*
2005 * Switch back to blocking mode if that was the state before the
2006 * operation.
2007 */
2008 if (pThis->fBlocking)
2009 {
2010 u_long fNonBlocking = 0;
2011 int rc2 = ioctlsocket(pThis->hNative, FIONBIO, &fNonBlocking);
2012 if (rc2 != 0)
2013 {
2014 rc = rtSocketError();
2015 AssertMsgFailed(("%Rrc; rc2=%d\n", rc, rc2));
2016 }
2017 }
2018 }
2019 else
2020 {
2021 rc = rtSocketError();
2022 AssertMsgFailed(("%Rrc\n", rc));
2023 }
2024 }
2025 return rc;
2026}
2027
2028
2029/**
2030 * Updates the mask of events we're subscribing to.
2031 *
2032 * @returns IPRT status code.
2033 * @param pThis The socket handle.
2034 * @param fEvents The events we want to subscribe to.
2035 */
2036static int rtSocketPollUpdateEvents(RTSOCKETINT *pThis, uint32_t fEvents)
2037{
2038 LONG fNetworkEvents = 0;
2039 if (fEvents & RTPOLL_EVT_READ)
2040 fNetworkEvents |= FD_READ;
2041 if (fEvents & RTPOLL_EVT_WRITE)
2042 fNetworkEvents |= FD_WRITE;
2043 if (fEvents & RTPOLL_EVT_ERROR)
2044 fNetworkEvents |= FD_CLOSE;
2045 LogFlowFunc(("fNetworkEvents=%#x\n", fNetworkEvents));
2046 if (WSAEventSelect(pThis->hNative, pThis->hEvent, fNetworkEvents) == 0)
2047 {
2048 pThis->fSubscribedEvts = fEvents;
2049 return VINF_SUCCESS;
2050 }
2051
2052 int rc = rtSocketError();
2053 AssertMsgFailed(("fNetworkEvents=%#x rc=%Rrc\n", fNetworkEvents, rtSocketError()));
2054 return rc;
2055}
2056
2057#endif /* RT_OS_WINDOWS */
2058
2059
2060#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
2061
2062/**
2063 * Checks for pending events.
2064 *
2065 * @returns Event mask or 0.
2066 * @param pThis The socket handle.
2067 * @param fEvents The desired events.
2068 */
2069static uint32_t rtSocketPollCheck(RTSOCKETINT *pThis, uint32_t fEvents)
2070{
2071 uint32_t fRetEvents = 0;
2072
2073 LogFlowFunc(("pThis=%#p fEvents=%#x\n", pThis, fEvents));
2074
2075# ifdef RT_OS_WINDOWS
2076 /* Make sure WSAEnumNetworkEvents returns what we want. */
2077 int rc = VINF_SUCCESS;
2078 if ((pThis->fSubscribedEvts & fEvents) != fEvents)
2079 rc = rtSocketPollUpdateEvents(pThis, pThis->fSubscribedEvts | fEvents);
2080
2081 /* Get the event mask, ASSUMES that WSAEnumNetworkEvents doesn't clear stuff. */
2082 WSANETWORKEVENTS NetEvts;
2083 RT_ZERO(NetEvts);
2084 if (WSAEnumNetworkEvents(pThis->hNative, pThis->hEvent, &NetEvts) == 0)
2085 {
2086 if ( (NetEvts.lNetworkEvents & FD_READ)
2087 && (fEvents & RTPOLL_EVT_READ)
2088 && NetEvts.iErrorCode[FD_READ_BIT] == 0)
2089 fRetEvents |= RTPOLL_EVT_READ;
2090
2091 if ( (NetEvts.lNetworkEvents & FD_WRITE)
2092 && (fEvents & RTPOLL_EVT_WRITE)
2093 && NetEvts.iErrorCode[FD_WRITE_BIT] == 0)
2094 fRetEvents |= RTPOLL_EVT_WRITE;
2095
2096 if (fEvents & RTPOLL_EVT_ERROR)
2097 {
2098 if (NetEvts.lNetworkEvents & FD_CLOSE)
2099 fRetEvents |= RTPOLL_EVT_ERROR;
2100 else
2101 for (uint32_t i = 0; i < FD_MAX_EVENTS; i++)
2102 if ( (NetEvts.lNetworkEvents & (1L << i))
2103 && NetEvts.iErrorCode[i] != 0)
2104 fRetEvents |= RTPOLL_EVT_ERROR;
2105 }
2106 }
2107 else
2108 rc = rtSocketError();
2109
2110 /* Fall back on select if we hit an error above. */
2111 if (RT_FAILURE(rc))
2112 {
2113
2114 }
2115
2116#else /* RT_OS_OS2 */
2117 int aFds[4] = { pThis->hNative, pThis->hNative, pThis->hNative, -1 };
2118 int rc = os2_select(aFds, 1, 1, 1, 0);
2119 if (rc > 0)
2120 {
2121 if (aFds[0] == pThis->hNative)
2122 fRetEvents |= RTPOLL_EVT_READ;
2123 if (aFds[1] == pThis->hNative)
2124 fRetEvents |= RTPOLL_EVT_WRITE;
2125 if (aFds[2] == pThis->hNative)
2126 fRetEvents |= RTPOLL_EVT_ERROR;
2127 fRetEvents &= fEvents;
2128 }
2129#endif /* RT_OS_OS2 */
2130
2131 LogFlowFunc(("fRetEvents=%#x\n", fRetEvents));
2132 return fRetEvents;
2133}
2134
2135
2136/**
2137 * Internal RTPoll helper that polls the socket handle and, if @a fNoWait is
2138 * clear, starts whatever actions we've got running during the poll call.
2139 *
2140 * @returns 0 if no pending events, actions initiated if @a fNoWait is clear.
2141 * Event mask (in @a fEvents) and no actions if the handle is ready
2142 * already.
2143 * UINT32_MAX (asserted) if the socket handle is busy in I/O or a
2144 * different poll set.
2145 *
2146 * @param hSocket The socket handle.
2147 * @param hPollSet The poll set handle (for access checks).
2148 * @param fEvents The events we're polling for.
2149 * @param fFinalEntry Set if this is the final entry for this handle
2150 * in this poll set. This can be used for dealing
2151 * with duplicate entries.
2152 * @param fNoWait Set if it's a zero-wait poll call. Clear if
2153 * we'll wait for an event to occur.
2154 *
2155 * @remarks There is a potential race wrt duplicate handles when @a fNoWait is
2156 * @c true, we don't currently care about that oddity...
2157 */
2158DECLHIDDEN(uint32_t) rtSocketPollStart(RTSOCKET hSocket, RTPOLLSET hPollSet, uint32_t fEvents, bool fFinalEntry, bool fNoWait)
2159{
2160 RTSOCKETINT *pThis = hSocket;
2161 AssertPtrReturn(pThis, UINT32_MAX);
2162 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, UINT32_MAX);
2163 /** @todo This isn't quite sane. Replace by critsect and open up concurrent
2164 * reads and writes! */
2165 if (rtSocketTryLock(pThis))
2166 pThis->hPollSet = hPollSet;
2167 else
2168 {
2169 AssertReturn(pThis->hPollSet == hPollSet, UINT32_MAX);
2170 ASMAtomicIncU32(&pThis->cUsers);
2171 }
2172
2173 /* (rtSocketPollCheck will reset the event object). */
2174# ifdef RT_OS_WINDOWS
2175 uint32_t fRetEvents = pThis->fEventsSaved;
2176 pThis->fEventsSaved = 0; /* Reset */
2177 fRetEvents |= rtSocketPollCheck(pThis, fEvents);
2178
2179 if ( !fRetEvents
2180 && !fNoWait)
2181 {
2182 pThis->fPollEvts |= fEvents;
2183 if ( fFinalEntry
2184 && pThis->fSubscribedEvts != pThis->fPollEvts)
2185 {
2186 int rc = rtSocketPollUpdateEvents(pThis, pThis->fPollEvts);
2187 if (RT_FAILURE(rc))
2188 {
2189 pThis->fPollEvts = 0;
2190 fRetEvents = UINT32_MAX;
2191 }
2192 }
2193 }
2194# else
2195 uint32_t fRetEvents = rtSocketPollCheck(pThis, fEvents);
2196# endif
2197
2198 if (fRetEvents || fNoWait)
2199 {
2200 if (pThis->cUsers == 1)
2201 {
2202# ifdef RT_OS_WINDOWS
2203 rtSocketPollClearEventAndRestoreBlocking(pThis);
2204# endif
2205 pThis->hPollSet = NIL_RTPOLLSET;
2206 }
2207 ASMAtomicDecU32(&pThis->cUsers);
2208 }
2209
2210 return fRetEvents;
2211}
2212
2213
2214/**
2215 * Called after a WaitForMultipleObjects returned in order to check for pending
2216 * events and stop whatever actions that rtSocketPollStart() initiated.
2217 *
2218 * @returns Event mask or 0.
2219 *
2220 * @param hSocket The socket handle.
2221 * @param fEvents The events we're polling for.
2222 * @param fFinalEntry Set if this is the final entry for this handle
2223 * in this poll set. This can be used for dealing
2224 * with duplicate entries. Only keep in mind that
2225 * this method is called in reverse order, so the
2226 * first call will have this set (when the entire
2227 * set was processed).
2228 * @param fHarvestEvents Set if we should check for pending events.
2229 */
2230DECLHIDDEN(uint32_t) rtSocketPollDone(RTSOCKET hSocket, uint32_t fEvents, bool fFinalEntry, bool fHarvestEvents)
2231{
2232 RTSOCKETINT *pThis = hSocket;
2233 AssertPtrReturn(pThis, 0);
2234 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, 0);
2235 Assert(pThis->cUsers > 0);
2236 Assert(pThis->hPollSet != NIL_RTPOLLSET);
2237 RT_NOREF_PV(fFinalEntry);
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