VirtualBox

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

Last change on this file since 31105 was 31105, checked in by vboxsync, 15 years ago

Really fix windows burn

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 43.7 KB
Line 
1/* $Id: socket.cpp 31105 2010-07-26 11:04:01Z vboxsync $ */
2/** @file
3 * IPRT - Network Sockets.
4 */
5
6/*
7 * Copyright (C) 2006-2010 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.215389.xyz. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 */
26
27
28/*******************************************************************************
29* Header Files *
30*******************************************************************************/
31#ifdef RT_OS_WINDOWS
32# include <winsock2.h>
33#else /* !RT_OS_WINDOWS */
34# include <errno.h>
35# include <sys/stat.h>
36# include <sys/socket.h>
37# include <netinet/in.h>
38# include <netinet/tcp.h>
39# include <arpa/inet.h>
40# ifdef IPRT_WITH_TCPIP_V6
41# include <netinet6/in6.h>
42# endif
43# include <sys/un.h>
44# include <netdb.h>
45# include <unistd.h>
46# include <fcntl.h>
47# include <sys/uio.h>
48#endif /* !RT_OS_WINDOWS */
49#include <limits.h>
50
51#include "internal/iprt.h"
52#include <iprt/socket.h>
53
54#include <iprt/alloca.h>
55#include <iprt/asm.h>
56#include <iprt/assert.h>
57#include <iprt/err.h>
58#include <iprt/mempool.h>
59#include <iprt/poll.h>
60#include <iprt/string.h>
61#include <iprt/thread.h>
62#include <iprt/time.h>
63#include <iprt/mem.h>
64#include <iprt/sg.h>
65
66#include "internal/magics.h"
67#include "internal/socket.h"
68
69
70/*******************************************************************************
71* Defined Constants And Macros *
72*******************************************************************************/
73/* non-standard linux stuff (it seems). */
74#ifndef MSG_NOSIGNAL
75# define MSG_NOSIGNAL 0
76#endif
77
78/* Windows has different names for SHUT_XXX. */
79#ifndef SHUT_RDWR
80# ifdef SD_BOTH
81# define SHUT_RDWR SD_BOTH
82# else
83# define SHUT_RDWR 2
84# endif
85#endif
86#ifndef SHUT_WR
87# ifdef SD_SEND
88# define SHUT_WR SD_SEND
89# else
90# define SHUT_WR 1
91# endif
92#endif
93#ifndef SHUT_RD
94# ifdef SD_RECEIVE
95# define SHUT_RD SD_RECEIVE
96# else
97# define SHUT_RD 0
98# endif
99#endif
100
101/* fixup backlevel OSes. */
102#if defined(RT_OS_OS2) || defined(RT_OS_WINDOWS)
103# define socklen_t int
104#endif
105
106/** How many pending connection. */
107#define RTTCP_SERVER_BACKLOG 10
108
109
110/*******************************************************************************
111* Structures and Typedefs *
112*******************************************************************************/
113/**
114 * Socket handle data.
115 *
116 * This is mainly required for implementing RTPollSet on Windows.
117 */
118typedef struct RTSOCKETINT
119{
120 /** Magic number (RTSOCKET_MAGIC). */
121 uint32_t u32Magic;
122 /** Exclusive user count.
123 * This is used to prevent two threads from accessing the handle concurrently.
124 * It can be higher than 1 if this handle is reference multiple times in a
125 * polling set (Windows). */
126 uint32_t volatile cUsers;
127 /** The native socket handle. */
128 RTSOCKETNATIVE hNative;
129 /** Indicates whether the handle has been closed or not. */
130 bool volatile fClosed;
131 /** Indicates whether the socket is operating in blocking or non-blocking mode
132 * currently. */
133 bool fBlocking;
134#ifdef RT_OS_WINDOWS
135 /** The event semaphore we've associated with the socket handle.
136 * This is WSA_INVALID_EVENT if not done. */
137 WSAEVENT hEvent;
138 /** The pollset currently polling this socket. This is NIL if no one is
139 * polling. */
140 RTPOLLSET hPollSet;
141 /** The events we're polling for. */
142 uint32_t fPollEvts;
143 /** The events we're currently subscribing to with WSAEventSelect.
144 * This is ZERO if we're currently not subscribing to anything. */
145 uint32_t fSubscribedEvts;
146#endif /* RT_OS_WINDOWS */
147} RTSOCKETINT;
148
149
150/**
151 * Address union used internally for things like getpeername and getsockname.
152 */
153typedef union RTSOCKADDRUNION
154{
155 struct sockaddr Addr;
156 struct sockaddr_in Ipv4;
157#ifdef IPRT_WITH_TCPIP_V6
158 struct sockaddr_in6 Ipv6;
159#endif
160} RTSOCKADDRUNION;
161
162
163/**
164 * Get the last error as an iprt status code.
165 *
166 * @returns IPRT status code.
167 */
168DECLINLINE(int) rtSocketError(void)
169{
170#ifdef RT_OS_WINDOWS
171 return RTErrConvertFromWin32(WSAGetLastError());
172#else
173 return RTErrConvertFromErrno(errno);
174#endif
175}
176
177
178/**
179 * Resets the last error.
180 */
181DECLINLINE(void) rtSocketErrorReset(void)
182{
183#ifdef RT_OS_WINDOWS
184 WSASetLastError(0);
185#else
186 errno = 0;
187#endif
188}
189
190
191/**
192 * Get the last resolver error as an iprt status code.
193 *
194 * @returns iprt status code.
195 */
196int rtSocketResolverError(void)
197{
198#ifdef RT_OS_WINDOWS
199 return RTErrConvertFromWin32(WSAGetLastError());
200#else
201 switch (h_errno)
202 {
203 case HOST_NOT_FOUND:
204 return VERR_NET_HOST_NOT_FOUND;
205 case NO_DATA:
206 return VERR_NET_ADDRESS_NOT_AVAILABLE;
207 case NO_RECOVERY:
208 return VERR_IO_GEN_FAILURE;
209 case TRY_AGAIN:
210 return VERR_TRY_AGAIN;
211
212 default:
213 return VERR_UNRESOLVED_ERROR;
214 }
215#endif
216}
217
218
219/**
220 * Tries to lock the socket for exclusive usage by the calling thread.
221 *
222 * Call rtSocketUnlock() to unlock.
223 *
224 * @returns @c true if locked, @c false if not.
225 * @param pThis The socket structure.
226 */
227DECLINLINE(bool) rtSocketTryLock(RTSOCKETINT *pThis)
228{
229 return ASMAtomicCmpXchgU32(&pThis->cUsers, 1, 0);
230}
231
232
233/**
234 * Unlocks the socket.
235 *
236 * @param pThis The socket structure.
237 */
238DECLINLINE(void) rtSocketUnlock(RTSOCKETINT *pThis)
239{
240 ASMAtomicCmpXchgU32(&pThis->cUsers, 0, 1);
241}
242
243
244/**
245 * Switches the socket to the desired blocking mode if neccessary.
246 *
247 * The socket must be locked.
248 *
249 * @returns IPRT status code.
250 * @param pThis The socket structure.
251 * @param fBlocking The desired mode of operation.
252 */
253DECLINLINE(int) rtSocketSwitchBlockingMode(RTSOCKETINT *pThis, bool fBlocking)
254{
255 int rc = VINF_SUCCESS;
256
257 if (pThis->fBlocking != fBlocking)
258 {
259#ifdef RT_OS_WINDOWS
260 u_long uBlocking = fBlocking ? 0 : 1;
261 if (ioctlsocket(pThis->hNative, FIONBIO, &uBlocking))
262#else
263 if (fcntl(pThis->hNative, F_SETFL, O_NONBLOCK))
264#endif
265 rc = rtSocketError();
266 else
267 pThis->fBlocking = fBlocking;
268 }
269
270 return rc;
271}
272
273/**
274 * Creates an IPRT socket handle for a native one.
275 *
276 * @returns IPRT status code.
277 * @param ppSocket Where to return the IPRT socket handle.
278 * @param hNative The native handle.
279 */
280int rtSocketCreateForNative(RTSOCKETINT **ppSocket, RTSOCKETNATIVE hNative)
281{
282 RTSOCKETINT *pThis = (RTSOCKETINT *)RTMemPoolAlloc(RTMEMPOOL_DEFAULT, sizeof(*pThis));
283 if (!pThis)
284 return VERR_NO_MEMORY;
285 pThis->u32Magic = RTSOCKET_MAGIC;
286 pThis->cUsers = 0;
287 pThis->hNative = hNative;
288 pThis->fClosed = false;
289 pThis->fBlocking = true;
290#ifdef RT_OS_WINDOWS
291 pThis->hEvent = WSA_INVALID_EVENT;
292 pThis->hPollSet = NIL_RTPOLLSET;
293 pThis->fPollEvts = 0;
294 pThis->fSubscribedEvts = 0;
295#endif
296 *ppSocket = pThis;
297 return VINF_SUCCESS;
298}
299
300
301RTDECL(int) RTSocketFromNative(PRTSOCKET phSocket, RTHCINTPTR uNative)
302{
303 AssertReturn(uNative != NIL_RTSOCKETNATIVE, VERR_INVALID_PARAMETER);
304#ifndef RT_OS_WINDOWS
305 AssertReturn(uNative >= 0, VERR_INVALID_PARAMETER);
306#endif
307 AssertPtrReturn(phSocket, VERR_INVALID_POINTER);
308 return rtSocketCreateForNative(phSocket, uNative);
309}
310
311
312/**
313 * Wrapper around socket().
314 *
315 * @returns IPRT status code.
316 * @param phSocket Where to store the handle to the socket on
317 * success.
318 * @param iDomain The protocol family (PF_XXX).
319 * @param iType The socket type (SOCK_XXX).
320 * @param iProtocol Socket parameter, usually 0.
321 */
322int rtSocketCreate(PRTSOCKET phSocket, int iDomain, int iType, int iProtocol)
323{
324 /*
325 * Create the socket.
326 */
327 RTSOCKETNATIVE hNative = socket(iDomain, iType, iProtocol);
328 if (hNative == NIL_RTSOCKETNATIVE)
329 return rtSocketError();
330
331 /*
332 * Wrap it.
333 */
334 int rc = rtSocketCreateForNative(phSocket, hNative);
335 if (RT_FAILURE(rc))
336 {
337#ifdef RT_OS_WINDOWS
338 closesocket(hNative);
339#else
340 close(hNative);
341#endif
342 }
343 return rc;
344}
345
346
347RTDECL(uint32_t) RTSocketRetain(RTSOCKET hSocket)
348{
349 RTSOCKETINT *pThis = hSocket;
350 AssertPtrReturn(pThis, UINT32_MAX);
351 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, UINT32_MAX);
352 return RTMemPoolRetain(pThis);
353}
354
355
356/**
357 * Worker for RTSocketRelease and RTSocketClose.
358 *
359 * @returns IPRT status code.
360 * @param pThis The socket handle instance data.
361 * @param fDestroy Whether we're reaching ref count zero.
362 */
363static int rtSocketCloseIt(RTSOCKETINT *pThis, bool fDestroy)
364{
365 /*
366 * Invalidate the handle structure on destroy.
367 */
368 if (fDestroy)
369 {
370 Assert(ASMAtomicReadU32(&pThis->u32Magic) == RTSOCKET_MAGIC);
371 ASMAtomicWriteU32(&pThis->u32Magic, RTSOCKET_MAGIC_DEAD);
372 }
373
374 int rc = VINF_SUCCESS;
375 if (ASMAtomicCmpXchgBool(&pThis->fClosed, true, false))
376 {
377 /*
378 * Close the native handle.
379 */
380 RTSOCKETNATIVE hNative = pThis->hNative;
381 if (hNative != NIL_RTSOCKETNATIVE)
382 {
383 pThis->hNative = NIL_RTSOCKETNATIVE;
384
385#ifdef RT_OS_WINDOWS
386 if (closesocket(hNative))
387#else
388 if (close(hNative))
389#endif
390 {
391 rc = rtSocketError();
392#ifdef RT_OS_WINDOWS
393 AssertMsgFailed(("\"%s\": closesocket(%p) -> %Rrc\n", (uintptr_t)hNative, rc));
394#else
395 AssertMsgFailed(("\"%s\": close(%d) -> %Rrc\n", hNative, rc));
396#endif
397 }
398 }
399
400#ifdef RT_OS_WINDOWS
401 /*
402 * Close the event.
403 */
404 WSAEVENT hEvent = pThis->hEvent;
405 if (hEvent == WSA_INVALID_EVENT)
406 {
407 pThis->hEvent = WSA_INVALID_EVENT;
408 WSACloseEvent(hEvent);
409 }
410#endif
411 }
412
413 return rc;
414}
415
416
417RTDECL(uint32_t) RTSocketRelease(RTSOCKET hSocket)
418{
419 RTSOCKETINT *pThis = hSocket;
420 if (pThis == NIL_RTSOCKET)
421 return 0;
422 AssertPtrReturn(pThis, UINT32_MAX);
423 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, UINT32_MAX);
424
425 /* get the refcount without killing it... */
426 uint32_t cRefs = RTMemPoolRefCount(pThis);
427 AssertReturn(cRefs != UINT32_MAX, UINT32_MAX);
428 if (cRefs == 1)
429 rtSocketCloseIt(pThis, true);
430
431 return RTMemPoolRelease(RTMEMPOOL_DEFAULT, pThis);
432}
433
434
435RTDECL(int) RTSocketClose(RTSOCKET hSocket)
436{
437 RTSOCKETINT *pThis = hSocket;
438 if (pThis == NIL_RTSOCKET)
439 return VINF_SUCCESS;
440 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
441 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
442
443 uint32_t cRefs = RTMemPoolRefCount(pThis);
444 AssertReturn(cRefs != UINT32_MAX, UINT32_MAX);
445
446 int rc = rtSocketCloseIt(pThis, cRefs == 1);
447
448 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pThis);
449 return rc;
450}
451
452
453RTDECL(RTHCUINTPTR) RTSocketToNative(RTSOCKET hSocket)
454{
455 RTSOCKETINT *pThis = hSocket;
456 AssertPtrReturn(pThis, RTHCUINTPTR_MAX);
457 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, RTHCUINTPTR_MAX);
458 return (RTHCUINTPTR)pThis->hNative;
459}
460
461
462RTDECL(int) RTSocketSetInheritance(RTSOCKET hSocket, bool fInheritable)
463{
464 RTSOCKETINT *pThis = hSocket;
465 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
466 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
467 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
468
469 int rc = VINF_SUCCESS;
470#ifdef RT_OS_WINDOWS
471 if (!SetHandleInformation((HANDLE)pThis->hNative, HANDLE_FLAG_INHERIT, fInheritable ? HANDLE_FLAG_INHERIT : 0))
472 rc = RTErrConvertFromWin32(GetLastError());
473#else
474 if (fcntl(pThis->hNative, F_SETFD, fInheritable ? 0 : FD_CLOEXEC) < 0)
475 rc = RTErrConvertFromErrno(errno);
476#endif
477
478 return rc;
479}
480
481
482RTDECL(int) RTSocketRead(RTSOCKET hSocket, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
483{
484 /*
485 * Validate input.
486 */
487 RTSOCKETINT *pThis = hSocket;
488 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
489 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
490 AssertReturn(cbBuffer > 0, VERR_INVALID_PARAMETER);
491 AssertPtr(pvBuffer);
492 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
493
494
495 int rc = rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
496 if (RT_FAILURE(rc))
497 return rc;
498
499 /*
500 * Read loop.
501 * If pcbRead is NULL we have to fill the entire buffer!
502 */
503 size_t cbRead = 0;
504 size_t cbToRead = cbBuffer;
505 for (;;)
506 {
507 rtSocketErrorReset();
508#ifdef RT_OS_WINDOWS
509 int cbNow = cbToRead >= INT_MAX/2 ? INT_MAX/2 : (int)cbToRead;
510#else
511 size_t cbNow = cbToRead;
512#endif
513 ssize_t cbBytesRead = recv(pThis->hNative, (char *)pvBuffer + cbRead, cbNow, MSG_NOSIGNAL);
514 if (cbBytesRead <= 0)
515 {
516 rc = rtSocketError();
517 Assert(RT_FAILURE_NP(rc) || cbBytesRead == 0);
518 if (RT_SUCCESS_NP(rc))
519 {
520 if (!pcbRead)
521 rc = VERR_NET_SHUTDOWN;
522 else
523 {
524 *pcbRead = 0;
525 rc = VINF_SUCCESS;
526 }
527 }
528 break;
529 }
530 if (pcbRead)
531 {
532 /* return partial data */
533 *pcbRead = cbBytesRead;
534 break;
535 }
536
537 /* read more? */
538 cbRead += cbBytesRead;
539 if (cbRead == cbBuffer)
540 break;
541
542 /* next */
543 cbToRead = cbBuffer - cbRead;
544 }
545
546 rtSocketUnlock(pThis);
547 return rc;
548}
549
550
551RTDECL(int) RTSocketWrite(RTSOCKET hSocket, const void *pvBuffer, size_t cbBuffer)
552{
553 /*
554 * Validate input.
555 */
556 RTSOCKETINT *pThis = hSocket;
557 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
558 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
559 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
560
561 int rc = rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
562 if (RT_FAILURE(rc))
563 return rc;
564
565 /*
566 * Try write all at once.
567 */
568#ifdef RT_OS_WINDOWS
569 int cbNow = cbBuffer >= INT_MAX / 2 ? INT_MAX / 2 : (int)cbBuffer;
570#else
571 size_t cbNow = cbBuffer >= SSIZE_MAX ? SSIZE_MAX : cbBuffer;
572#endif
573 ssize_t cbWritten = send(pThis->hNative, (const char *)pvBuffer, cbNow, MSG_NOSIGNAL);
574 if (RT_LIKELY((size_t)cbWritten == cbBuffer && cbWritten >= 0))
575 rc = VINF_SUCCESS;
576 else if (cbWritten < 0)
577 rc = rtSocketError();
578 else
579 {
580 /*
581 * Unfinished business, write the remainder of the request. Must ignore
582 * VERR_INTERRUPTED here if we've managed to send something.
583 */
584 size_t cbSentSoFar = 0;
585 for (;;)
586 {
587 /* advance */
588 cbBuffer -= (size_t)cbWritten;
589 if (!cbBuffer)
590 break;
591 cbSentSoFar += (size_t)cbWritten;
592 pvBuffer = (char const *)pvBuffer + cbWritten;
593
594 /* send */
595#ifdef RT_OS_WINDOWS
596 cbNow = cbBuffer >= INT_MAX / 2 ? INT_MAX / 2 : (int)cbBuffer;
597#else
598 cbNow = cbBuffer >= SSIZE_MAX ? SSIZE_MAX : cbBuffer;
599#endif
600 cbWritten = send(pThis->hNative, (const char *)pvBuffer, cbNow, MSG_NOSIGNAL);
601 if (cbWritten >= 0)
602 AssertMsg(cbBuffer >= (size_t)cbWritten, ("Wrote more than we requested!!! cbWritten=%zu cbBuffer=%zu rtSocketError()=%d\n",
603 cbWritten, cbBuffer, rtSocketError()));
604 else
605 {
606 rc = rtSocketError();
607 if (rc != VERR_INTERNAL_ERROR || cbSentSoFar == 0)
608 break;
609 cbWritten = 0;
610 rc = VINF_SUCCESS;
611 }
612 }
613 }
614
615 rtSocketUnlock(pThis);
616 return rc;
617}
618
619
620RTDECL(int) RTSocketSgWrite(RTSOCKET hSocket, PCRTSGBUF pSgBuf)
621{
622 /*
623 * Validate input.
624 */
625 RTSOCKETINT *pThis = hSocket;
626 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
627 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
628 AssertPtrReturn(pSgBuf, VERR_INVALID_PARAMETER);
629 AssertReturn(pSgBuf->cSegs > 0, VERR_INVALID_PARAMETER);
630 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
631
632 int rc = rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
633 if (RT_FAILURE(rc))
634 return rc;
635
636 /*
637 * Construct message descriptor (translate pSgBuf) and send it.
638 */
639 rc = VERR_NO_TMP_MEMORY;
640#ifdef RT_OS_WINDOWS
641 AssertCompileSize(WSABUF, sizeof(RTSGSEG));
642 AssertCompileMemberSize(WSABUF, buf, RT_SIZEOFMEMB(RTSGSEG, pvSeg));
643
644 LPWSABUF paMsg = (LPWSABUF)RTMemTmpAllocZ(pSgBuf->cSegs * sizeof(WSABUF));
645 if (paMsg)
646 {
647 for (unsigned i = 0; i < pSgBuf->cSegs; i++)
648 {
649 paMsg[i].buf = (char *)pSgBuf->paSegs[i].pvSeg;
650 paMsg[i].len = (u_long)pSgBuf->paSegs[i].cbSeg;
651 }
652
653 DWORD dwSent;
654 int hrc = WSASend(pThis->hNative, paMsg, pSgBuf->cSegs, &dwSent,
655 MSG_NOSIGNAL, NULL, NULL);
656 if (!hrc)
657 rc = VINF_SUCCESS;
658/** @todo check for incomplete writes */
659 else
660 rc = rtSocketError();
661
662 RTMemTmpFree(paMsg);
663 }
664
665#else /* !RT_OS_WINDOWS */
666 AssertCompileSize(struct iovec, sizeof(RTSGSEG));
667 AssertCompileMemberSize(struct iovec, iov_base, RT_SIZEOFMEMB(RTSGSEG, pvSeg));
668 AssertCompileMemberSize(struct iovec, iov_len, RT_SIZEOFMEMB(RTSGSEG, cbSeg));
669
670 struct iovec *paMsg = (struct iovec *)RTMemTmpAllocZ(pSgBuf->cSegs * sizeof(struct iovec));
671 if (paMsg)
672 {
673 for (unsigned i = 0; i < pSgBuf->cSegs; i++)
674 {
675 paMsg[i].iov_base = pSgBuf->paSegs[i].pvSeg;
676 paMsg[i].iov_len = pSgBuf->paSegs[i].cbSeg;
677 }
678
679 struct msghdr msgHdr;
680 RT_ZERO(msgHdr);
681 msgHdr.msg_iov = paMsg;
682 msgHdr.msg_iovlen = pSgBuf->cSegs;
683 ssize_t cbWritten = sendmsg(pThis->hNative, &msgHdr, MSG_NOSIGNAL);
684 if (RT_LIKELY(cbWritten >= 0))
685 rc = VINF_SUCCESS;
686/** @todo check for incomplete writes */
687 else
688 rc = rtSocketError();
689
690 RTMemTmpFree(paMsg);
691 }
692#endif /* !RT_OS_WINDOWS */
693
694 rtSocketUnlock(pThis);
695 return rc;
696}
697
698
699RTDECL(int) RTSocketSgWriteL(RTSOCKET hSocket, size_t cSegs, ...)
700{
701 va_list va;
702 va_start(va, cSegs);
703 int rc = RTSocketSgWriteLV(hSocket, cSegs, va);
704 va_end(va);
705 return rc;
706}
707
708
709RTDECL(int) RTSocketSgWriteLV(RTSOCKET hSocket, size_t cSegs, va_list va)
710{
711 /*
712 * Set up a S/G segment array + buffer on the stack and pass it
713 * on to RTSocketSgWrite.
714 */
715 Assert(cSegs <= 16);
716 PRTSGSEG paSegs = (PRTSGSEG)alloca(cSegs * sizeof(RTSGSEG));
717 AssertReturn(paSegs, VERR_NO_TMP_MEMORY);
718 for (size_t i = 0; i < cSegs; i++)
719 {
720 paSegs[i].pvSeg = va_arg(va, void *);
721 paSegs[i].cbSeg = va_arg(va, size_t);
722 }
723
724 RTSGBUF SgBuf;
725 RTSgBufInit(&SgBuf, paSegs, cSegs);
726 return RTSocketSgWrite(hSocket, &SgBuf);
727}
728
729
730RTDECL(int) RTSocketReadNB(RTSOCKET hSocket, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
731{
732 /*
733 * Validate input.
734 */
735 RTSOCKETINT *pThis = hSocket;
736 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
737 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
738 AssertReturn(cbBuffer > 0, VERR_INVALID_PARAMETER);
739 AssertPtr(pvBuffer);
740 AssertPtrReturn(pcbRead, VERR_INVALID_PARAMETER);
741 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
742
743 int rc = rtSocketSwitchBlockingMode(pThis, false /* fBlocking */);
744 if (RT_FAILURE(rc))
745 return rc;
746
747 /*
748 * Read loop.
749 */
750 size_t cbRead = 0;
751 size_t cbToRead = cbBuffer;
752 for (;;)
753 {
754 rtSocketErrorReset();
755#ifdef RT_OS_WINDOWS
756 int cbNow = cbToRead >= INT_MAX/2 ? INT_MAX/2 : (int)cbToRead;
757#else
758 size_t cbNow = cbToRead;
759#endif
760 ssize_t cbBytesRead = recv(pThis->hNative, (char *)pvBuffer + cbRead, cbNow, MSG_NOSIGNAL);
761 if (cbBytesRead <= 0)
762 {
763 rc = rtSocketError();
764 Assert(RT_FAILURE_NP(rc) || cbBytesRead == 0);
765 if (RT_SUCCESS_NP(rc))
766 {
767 *pcbRead = 0;
768 rc = VINF_SUCCESS;
769 }
770 else
771 *pcbRead = cbRead;
772 break;
773 }
774
775 /* read more? */
776 cbRead += cbBytesRead;
777 if (cbRead == cbBuffer)
778 {
779 *pcbRead = cbRead;
780 break;
781 }
782
783 /* next */
784 cbToRead = cbBuffer - cbRead;
785 }
786
787 rtSocketUnlock(pThis);
788 return rc;
789}
790
791
792RTDECL(int) RTSocketWriteNB(RTSOCKET hSocket, const void *pvBuffer, size_t cbBuffer, size_t *pcbWritten)
793{
794 /*
795 * Validate input.
796 */
797 RTSOCKETINT *pThis = hSocket;
798 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
799 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
800 AssertPtrReturn(pcbWritten, VERR_INVALID_PARAMETER);
801 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
802
803 int rc = rtSocketSwitchBlockingMode(pThis, false /* fBlocking */);
804 if (RT_FAILURE(rc))
805 return rc;
806
807 /*
808 * Write loop.
809 */
810 size_t cbWrite = 0;
811 size_t cbToWrite = cbBuffer;
812 for (;;)
813 {
814 rtSocketErrorReset();
815#ifdef RT_OS_WINDOWS
816 int cbNow = RT_MIN(cbToWrite, INT_MAX/2);
817#else
818 size_t cbNow = cbToWrite;
819#endif
820 ssize_t cbBytesWritten = send(pThis->hNative, (char *)pvBuffer + cbWrite, cbNow, MSG_NOSIGNAL);
821 if (cbBytesWritten < 0)
822 {
823 rc = rtSocketError();
824 *pcbWritten = cbWrite;
825 break;
826 }
827
828 /* write more? */
829 cbWrite += cbBytesWritten;
830 if (cbWrite == cbBuffer)
831 {
832 *pcbWritten = cbWrite;
833 break;
834 }
835
836 /* next */
837 cbToWrite = cbBuffer - cbWrite;
838 }
839
840 rtSocketUnlock(pThis);
841 return rc;
842}
843
844
845RTDECL(int) RTSocketSgWriteNB(RTSOCKET hSocket, PCRTSGBUF pSgBuf, size_t *pcbWritten)
846{
847 /*
848 * Validate input.
849 */
850 RTSOCKETINT *pThis = hSocket;
851 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
852 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
853 AssertPtrReturn(pSgBuf, VERR_INVALID_PARAMETER);
854 AssertPtrReturn(pcbWritten, VERR_INVALID_PARAMETER);
855 AssertReturn(pSgBuf->cSegs > 0, VERR_INVALID_PARAMETER);
856 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
857
858 int rc = rtSocketSwitchBlockingMode(pThis, false /* fBlocking */);
859 if (RT_FAILURE(rc))
860 return rc;
861
862 /*
863 * Construct message descriptor (translate pSgBuf) and send it.
864 */
865 rc = VERR_NO_TMP_MEMORY;
866#ifdef RT_OS_WINDOWS
867 AssertCompileSize(WSABUF, sizeof(RTSGSEG));
868 AssertCompileMemberSize(WSABUF, buf, RT_SIZEOFMEMB(RTSGSEG, pvSeg));
869
870 LPWSABUF paMsg = (LPWSABUF)RTMemTmpAllocZ(pSgBuf->cSegs * sizeof(WSABUF));
871 if (paMsg)
872 {
873 for (unsigned i = 0; i < pSgBuf->cSegs; i++)
874 {
875 paMsg[i].buf = (char *)pSgBuf->paSegs[i].pvSeg;
876 paMsg[i].len = (u_long)pSgBuf->paSegs[i].cbSeg;
877 }
878
879 DWORD dwSent = 0;
880 int hrc = WSASend(pThis->hNative, paMsg, pSgBuf->cSegs, &dwSent,
881 MSG_NOSIGNAL, NULL, NULL);
882 if (!hrc)
883 rc = VINF_SUCCESS;
884/** @todo check for incomplete writes */
885 else
886 rc = rtSocketError();
887
888 *pcbWritten = dwSent;
889
890 RTMemTmpFree(paMsg);
891 }
892
893#else /* !RT_OS_WINDOWS */
894 AssertCompileSize(struct iovec, sizeof(RTSGSEG));
895 AssertCompileMemberSize(struct iovec, iov_base, RT_SIZEOFMEMB(RTSGSEG, pvSeg));
896 AssertCompileMemberSize(struct iovec, iov_len, RT_SIZEOFMEMB(RTSGSEG, cbSeg));
897
898 struct iovec *paMsg = (struct iovec *)RTMemTmpAllocZ(pSgBuf->cSegs * sizeof(struct iovec));
899 if (paMsg)
900 {
901 for (unsigned i = 0; i < pSgBuf->cSegs; i++)
902 {
903 paMsg[i].iov_base = pSgBuf->paSegs[i].pvSeg;
904 paMsg[i].iov_len = pSgBuf->paSegs[i].cbSeg;
905 }
906
907 struct msghdr msgHdr;
908 RT_ZERO(msgHdr);
909 msgHdr.msg_iov = paMsg;
910 msgHdr.msg_iovlen = pSgBuf->cSegs;
911 ssize_t cbWritten = sendmsg(pThis->hNative, &msgHdr, MSG_NOSIGNAL);
912 if (RT_LIKELY(cbWritten >= 0))
913 rc = VINF_SUCCESS;
914/** @todo check for incomplete writes */
915 else
916 rc = rtSocketError();
917
918 *pcbWritten = cbWritten;
919
920 RTMemTmpFree(paMsg);
921 }
922#endif /* !RT_OS_WINDOWS */
923
924 rtSocketUnlock(pThis);
925 return rc;
926}
927
928
929RTDECL(int) RTSocketSgWriteLNB(RTSOCKET hSocket, size_t cSegs, size_t *pcbWritten, ...)
930{
931 va_list va;
932 va_start(va, pcbWritten);
933 int rc = RTSocketSgWriteLVNB(hSocket, cSegs, pcbWritten, va);
934 va_end(va);
935 return rc;
936}
937
938
939RTDECL(int) RTSocketSgWriteLVNB(RTSOCKET hSocket, size_t cSegs, size_t *pcbWritten, va_list va)
940{
941 /*
942 * Set up a S/G segment array + buffer on the stack and pass it
943 * on to RTSocketSgWrite.
944 */
945 Assert(cSegs <= 16);
946 PRTSGSEG paSegs = (PRTSGSEG)alloca(cSegs * sizeof(RTSGSEG));
947 AssertReturn(paSegs, VERR_NO_TMP_MEMORY);
948 for (size_t i = 0; i < cSegs; i++)
949 {
950 paSegs[i].pvSeg = va_arg(va, void *);
951 paSegs[i].cbSeg = va_arg(va, size_t);
952 }
953
954 RTSGBUF SgBuf;
955 RTSgBufInit(&SgBuf, paSegs, cSegs);
956 return RTSocketSgWriteNB(hSocket, &SgBuf, pcbWritten);
957}
958
959
960RTDECL(int) RTSocketSelectOne(RTSOCKET hSocket, RTMSINTERVAL cMillies)
961{
962 /*
963 * Validate input.
964 */
965 RTSOCKETINT *pThis = hSocket;
966 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
967 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
968 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
969
970 /*
971 * Set up the file descriptor sets and do the select.
972 */
973 fd_set fdsetR;
974 FD_ZERO(&fdsetR);
975 FD_SET(pThis->hNative, &fdsetR);
976
977 fd_set fdsetE = fdsetR;
978
979 int rc;
980 if (cMillies == RT_INDEFINITE_WAIT)
981 rc = select(pThis->hNative + 1, &fdsetR, NULL, &fdsetE, NULL);
982 else
983 {
984 struct timeval timeout;
985 timeout.tv_sec = cMillies / 1000;
986 timeout.tv_usec = (cMillies % 1000) * 1000;
987 rc = select(pThis->hNative + 1, &fdsetR, NULL, &fdsetE, &timeout);
988 }
989 if (rc > 0)
990 rc = VINF_SUCCESS;
991 else if (rc == 0)
992 rc = VERR_TIMEOUT;
993 else
994 rc = rtSocketError();
995
996 return rc;
997}
998
999
1000RTDECL(int) RTSocketShutdown(RTSOCKET hSocket, bool fRead, bool fWrite)
1001{
1002 /*
1003 * Validate input, don't lock it because we might want to interrupt a call
1004 * active on a different thread.
1005 */
1006 RTSOCKETINT *pThis = hSocket;
1007 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1008 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1009 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
1010 AssertReturn(fRead || fWrite, VERR_INVALID_PARAMETER);
1011
1012 /*
1013 * Do the job.
1014 */
1015 int rc = VINF_SUCCESS;
1016 int fHow;
1017 if (fRead && fWrite)
1018 fHow = SHUT_RDWR;
1019 else if (fRead)
1020 fHow = SHUT_RD;
1021 else
1022 fHow = SHUT_WR;
1023 if (shutdown(pThis->hNative, fHow) == -1)
1024 rc = rtSocketError();
1025
1026 return rc;
1027}
1028
1029
1030/**
1031 * Converts from a native socket address to a generic IPRT network address.
1032 *
1033 * @returns IPRT status code.
1034 * @param pSrc The source address.
1035 * @param cbSrc The size of the source address.
1036 * @param pAddr Where to return the generic IPRT network
1037 * address.
1038 */
1039static int rtSocketConvertAddress(RTSOCKADDRUNION const *pSrc, size_t cbSrc, PRTNETADDR pAddr)
1040{
1041 /*
1042 * Convert the address.
1043 */
1044 if ( cbSrc == sizeof(struct sockaddr_in)
1045 && pSrc->Addr.sa_family == AF_INET)
1046 {
1047 RT_ZERO(*pAddr);
1048 pAddr->enmType = RTNETADDRTYPE_IPV4;
1049 pAddr->uPort = RT_N2H_U16(pSrc->Ipv4.sin_port);
1050 pAddr->uAddr.IPv4.u = pSrc->Ipv4.sin_addr.s_addr;
1051 }
1052#ifdef IPRT_WITH_TCPIP_V6
1053 else if ( cbSrc == sizeof(struct sockaddr_in6)
1054 && pSrc->Addr.sa_family == AF_INET6)
1055 {
1056 RT_ZERO(*pAddr);
1057 pAddr->enmType = RTNETADDRTYPE_IPV6;
1058 pAddr->uPort = RT_N2H_U16(pSrc->Ipv6.sin6_port);
1059 pAddr->uAddr.IPv6.au32[0] = pSrc->Ipv6.sin6_addr.s6_addr32[0];
1060 pAddr->uAddr.IPv6.au32[1] = pSrc->Ipv6.sin6_addr.s6_addr32[1];
1061 pAddr->uAddr.IPv6.au32[2] = pSrc->Ipv6.sin6_addr.s6_addr32[2];
1062 pAddr->uAddr.IPv6.au32[3] = pSrc->Ipv6.sin6_addr.s6_addr32[3];
1063 }
1064#endif
1065 else
1066 return VERR_NET_ADDRESS_FAMILY_NOT_SUPPORTED;
1067 return VINF_SUCCESS;
1068}
1069
1070
1071RTDECL(int) RTSocketGetLocalAddress(RTSOCKET hSocket, PRTNETADDR pAddr)
1072{
1073 /*
1074 * Validate input.
1075 */
1076 RTSOCKETINT *pThis = hSocket;
1077 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1078 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1079 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
1080
1081 /*
1082 * Get the address and convert it.
1083 */
1084 int rc;
1085 RTSOCKADDRUNION u;
1086#ifdef RT_OS_WINDOWS
1087 int cbAddr = sizeof(u);
1088#else
1089 socklen_t cbAddr = sizeof(u);
1090#endif
1091 RT_ZERO(u);
1092 if (getsockname(pThis->hNative, &u.Addr, &cbAddr) == 0)
1093 rc = rtSocketConvertAddress(&u, cbAddr, pAddr);
1094 else
1095 rc = rtSocketError();
1096
1097 return rc;
1098}
1099
1100
1101RTDECL(int) RTSocketGetPeerAddress(RTSOCKET hSocket, PRTNETADDR pAddr)
1102{
1103 /*
1104 * Validate input.
1105 */
1106 RTSOCKETINT *pThis = hSocket;
1107 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1108 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1109 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
1110
1111 /*
1112 * Get the address and convert it.
1113 */
1114 int rc;
1115 RTSOCKADDRUNION u;
1116#ifdef RT_OS_WINDOWS
1117 int cbAddr = sizeof(u);
1118#else
1119 socklen_t cbAddr = sizeof(u);
1120#endif
1121 RT_ZERO(u);
1122 if (getpeername(pThis->hNative, &u.Addr, &cbAddr) == 0)
1123 rc = rtSocketConvertAddress(&u, cbAddr, pAddr);
1124 else
1125 rc = rtSocketError();
1126
1127 return rc;
1128}
1129
1130
1131
1132/**
1133 * Wrapper around bind.
1134 *
1135 * @returns IPRT status code.
1136 * @param hSocket The socket handle.
1137 * @param pAddr The socket address to bind to.
1138 * @param cbAddr The size of the address structure @a pAddr
1139 * points to.
1140 */
1141int rtSocketBind(RTSOCKET hSocket, const struct sockaddr *pAddr, int cbAddr)
1142{
1143 /*
1144 * Validate input.
1145 */
1146 RTSOCKETINT *pThis = hSocket;
1147 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1148 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1149 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1150
1151 int rc = VINF_SUCCESS;
1152 if (bind(pThis->hNative, pAddr, cbAddr) != 0)
1153 rc = rtSocketError();
1154
1155 rtSocketUnlock(pThis);
1156 return rc;
1157}
1158
1159
1160/**
1161 * Wrapper around listen.
1162 *
1163 * @returns IPRT status code.
1164 * @param hSocket The socket handle.
1165 * @param cMaxPending The max number of pending connections.
1166 */
1167int rtSocketListen(RTSOCKET hSocket, int cMaxPending)
1168{
1169 /*
1170 * Validate input.
1171 */
1172 RTSOCKETINT *pThis = hSocket;
1173 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1174 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1175 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1176
1177 int rc = VINF_SUCCESS;
1178 if (listen(pThis->hNative, cMaxPending) != 0)
1179 rc = rtSocketError();
1180
1181 rtSocketUnlock(pThis);
1182 return rc;
1183}
1184
1185
1186/**
1187 * Wrapper around accept.
1188 *
1189 * @returns IPRT status code.
1190 * @param hSocket The socket handle.
1191 * @param phClient Where to return the client socket handle on
1192 * success.
1193 * @param pAddr Where to return the client address.
1194 * @param pcbAddr On input this gives the size buffer size of what
1195 * @a pAddr point to. On return this contains the
1196 * size of what's stored at @a pAddr.
1197 */
1198int rtSocketAccept(RTSOCKET hSocket, PRTSOCKET phClient, struct sockaddr *pAddr, size_t *pcbAddr)
1199{
1200 /*
1201 * Validate input.
1202 * Only lock the socket temporarily while we get the native handle, so that
1203 * we can safely shutdown and destroy the socket from a different thread.
1204 */
1205 RTSOCKETINT *pThis = hSocket;
1206 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1207 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1208 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1209
1210 /*
1211 * Call accept().
1212 */
1213 rtSocketErrorReset();
1214 int rc = VINF_SUCCESS;
1215#ifdef RT_OS_WINDOWS
1216 int cbAddr = (int)*pcbAddr;
1217#else
1218 socklen_t cbAddr = *pcbAddr;
1219#endif
1220 RTSOCKETNATIVE hNativeClient = accept(pThis->hNative, pAddr, &cbAddr);
1221 if (hNativeClient != NIL_RTSOCKETNATIVE)
1222 {
1223 *pcbAddr = cbAddr;
1224
1225 /*
1226 * Wrap the client socket.
1227 */
1228 rc = rtSocketCreateForNative(phClient, hNativeClient);
1229 if (RT_FAILURE(rc))
1230 {
1231#ifdef RT_OS_WINDOWS
1232 closesocket(hNativeClient);
1233#else
1234 close(hNativeClient);
1235#endif
1236 }
1237 }
1238 else
1239 rc = rtSocketError();
1240
1241 rtSocketUnlock(pThis);
1242 return rc;
1243}
1244
1245
1246/**
1247 * Wrapper around connect.
1248 *
1249 * @returns IPRT status code.
1250 * @param hSocket The socket handle.
1251 * @param pAddr The socket address to connect to.
1252 * @param cbAddr The size of the address structure @a pAddr
1253 * points to.
1254 */
1255int rtSocketConnect(RTSOCKET hSocket, const struct sockaddr *pAddr, int cbAddr)
1256{
1257 /*
1258 * Validate input.
1259 */
1260 RTSOCKETINT *pThis = hSocket;
1261 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1262 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1263 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1264
1265 int rc = VINF_SUCCESS;
1266 if (connect(pThis->hNative, pAddr, cbAddr) != 0)
1267 rc = rtSocketError();
1268
1269 rtSocketUnlock(pThis);
1270 return rc;
1271}
1272
1273
1274/**
1275 * Wrapper around setsockopt.
1276 *
1277 * @returns IPRT status code.
1278 * @param hSocket The socket handle.
1279 * @param iLevel The protocol level, e.g. IPPORTO_TCP.
1280 * @param iOption The option, e.g. TCP_NODELAY.
1281 * @param pvValue The value buffer.
1282 * @param cbValue The size of the value pointed to by pvValue.
1283 */
1284int rtSocketSetOpt(RTSOCKET hSocket, int iLevel, int iOption, void const *pvValue, int cbValue)
1285{
1286 /*
1287 * Validate input.
1288 */
1289 RTSOCKETINT *pThis = hSocket;
1290 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1291 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1292 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1293
1294 int rc = VINF_SUCCESS;
1295 if (setsockopt(pThis->hNative, iLevel, iOption, (const char *)pvValue, cbValue) != 0)
1296 rc = rtSocketError();
1297
1298 rtSocketUnlock(pThis);
1299 return rc;
1300}
1301
1302#ifdef RT_OS_WINDOWS
1303
1304/**
1305 * Internal RTPollSetAdd helper that returns the handle that should be added to
1306 * the pollset.
1307 *
1308 * @returns Valid handle on success, INVALID_HANDLE_VALUE on failure.
1309 * @param hSocket The socket handle.
1310 * @param fEvents The events we're polling for.
1311 * @param ph wher to put the primary handle.
1312 */
1313int rtSocketPollGetHandle(RTSOCKET hSocket, uint32_t fEvents, PHANDLE ph)
1314{
1315 RTSOCKETINT *pThis = hSocket;
1316 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1317 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1318 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1319
1320 int rc = VINF_SUCCESS;
1321 if (pThis->hEvent != WSA_INVALID_EVENT)
1322 *ph = pThis->hEvent;
1323 else
1324 {
1325 *ph = pThis->hEvent = WSACreateEvent();
1326 if (pThis->hEvent == WSA_INVALID_EVENT)
1327 rc = rtSocketError();
1328 }
1329
1330 rtSocketUnlock(pThis);
1331 return rc;
1332}
1333
1334
1335/**
1336 * Undos the harm done by WSAEventSelect.
1337 *
1338 * @returns IPRT status code.
1339 * @param pThis The socket handle.
1340 */
1341static int rtSocketPollClearEventAndMakeBlocking(RTSOCKETINT *pThis)
1342{
1343 int rc = VINF_SUCCESS;
1344 if (pThis->fSubscribedEvts)
1345 {
1346 if (WSAEventSelect(pThis->hNative, WSA_INVALID_EVENT, 0) == 0)
1347 {
1348 pThis->fSubscribedEvts = 0;
1349
1350 u_long fNonBlocking = 0;
1351 int rc2 = ioctlsocket(pThis->hNative, FIONBIO, &fNonBlocking);
1352 if (rc2 != 0)
1353 {
1354 rc = rtSocketError();
1355 AssertMsgFailed(("%Rrc; rc2=%d\n", rc, rc2));
1356 }
1357 }
1358 else
1359 {
1360 rc = rtSocketError();
1361 AssertMsgFailed(("%Rrc\n", rc));
1362 }
1363 }
1364 return rc;
1365}
1366
1367
1368/**
1369 * Updates the mask of events we're subscribing to.
1370 *
1371 * @returns IPRT status code.
1372 * @param pThis The socket handle.
1373 * @param fEvents The events we want to subscribe to.
1374 */
1375static int rtSocketPollUpdateEvents(RTSOCKETINT *pThis, uint32_t fEvents)
1376{
1377 LONG fNetworkEvents = 0;
1378 if (fEvents & RTPOLL_EVT_READ)
1379 fNetworkEvents |= FD_READ;
1380 if (fEvents & RTPOLL_EVT_WRITE)
1381 fNetworkEvents |= FD_WRITE;
1382 if (fEvents & RTPOLL_EVT_ERROR)
1383 fNetworkEvents |= FD_CLOSE;
1384 if (WSAEventSelect(pThis->hNative, pThis->hEvent, fNetworkEvents) == 0)
1385 {
1386 pThis->fSubscribedEvts = fEvents;
1387 return VINF_SUCCESS;
1388 }
1389
1390 int rc = rtSocketError();
1391 AssertMsgFailed(("fNetworkEvents=%#x rc=%Rrc\n", fNetworkEvents, rtSocketError()));
1392 return rc;
1393}
1394
1395
1396/**
1397 * Checks for pending events.
1398 *
1399 * @returns Event mask or 0.
1400 * @param pThis The socket handle.
1401 * @param fEvents The desired events.
1402 */
1403static uint32_t rtSocketPollCheck(RTSOCKETINT *pThis, uint32_t fEvents)
1404{
1405 int rc = VINF_SUCCESS;
1406 uint32_t fRetEvents = 0;
1407
1408 /* Make sure WSAEnumNetworkEvents returns what we want. */
1409 if ((pThis->fSubscribedEvts & fEvents) != fEvents)
1410 rc = rtSocketPollUpdateEvents(pThis, pThis->fSubscribedEvts | fEvents);
1411
1412 /* Get the event mask, ASSUMES that WSAEnumNetworkEvents doesn't clear stuff. */
1413 WSANETWORKEVENTS NetEvts;
1414 RT_ZERO(NetEvts);
1415 if (WSAEnumNetworkEvents(pThis->hNative, pThis->hEvent, &NetEvts) == 0)
1416 {
1417 if ( (NetEvts.lNetworkEvents & FD_READ)
1418 && (fEvents & RTPOLL_EVT_READ)
1419 && NetEvts.iErrorCode[FD_READ_BIT] == 0)
1420 fRetEvents |= RTPOLL_EVT_READ;
1421
1422 if ( (NetEvts.lNetworkEvents & FD_WRITE)
1423 && (fEvents & RTPOLL_EVT_WRITE)
1424 && NetEvts.iErrorCode[FD_WRITE_BIT] == 0)
1425 fRetEvents |= RTPOLL_EVT_WRITE;
1426
1427 if (fEvents & RTPOLL_EVT_ERROR)
1428 {
1429 if (NetEvts.lNetworkEvents & FD_CLOSE)
1430 fRetEvents |= RTPOLL_EVT_ERROR;
1431 else
1432 for (uint32_t i = 0; i < FD_MAX_EVENTS; i++)
1433 if ( (NetEvts.lNetworkEvents & (1L << i))
1434 && NetEvts.iErrorCode[i] != 0)
1435 fRetEvents |= RTPOLL_EVT_ERROR;
1436 }
1437 }
1438 else
1439 rc = rtSocketError();
1440
1441 /* Fall back on select if we hit an error above. */
1442 if (RT_FAILURE(rc))
1443 {
1444 /** @todo */
1445 }
1446
1447 return fRetEvents;
1448}
1449
1450
1451/**
1452 * Internal RTPoll helper that polls the socket handle and, if @a fNoWait is
1453 * clear, starts whatever actions we've got running during the poll call.
1454 *
1455 * @returns 0 if no pending events, actions initiated if @a fNoWait is clear.
1456 * Event mask (in @a fEvents) and no actions if the handle is ready
1457 * already.
1458 * UINT32_MAX (asserted) if the socket handle is busy in I/O or a
1459 * different poll set.
1460 *
1461 * @param hSocket The socket handle.
1462 * @param hPollSet The poll set handle (for access checks).
1463 * @param fEvents The events we're polling for.
1464 * @param fFinalEntry Set if this is the final entry for this handle
1465 * in this poll set. This can be used for dealing
1466 * with duplicate entries.
1467 * @param fNoWait Set if it's a zero-wait poll call. Clear if
1468 * we'll wait for an event to occur.
1469 *
1470 * @remarks There is a potential race wrt duplicate handles when @a fNoWait is
1471 * @c true, we don't currently care about that oddity...
1472 */
1473uint32_t rtSocketPollStart(RTSOCKET hSocket, RTPOLLSET hPollSet, uint32_t fEvents, bool fFinalEntry, bool fNoWait)
1474{
1475 RTSOCKETINT *pThis = hSocket;
1476 AssertPtrReturn(pThis, UINT32_MAX);
1477 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, UINT32_MAX);
1478 if (rtSocketTryLock(pThis))
1479 pThis->hPollSet = hPollSet;
1480 else
1481 {
1482 AssertReturn(pThis->hPollSet == hPollSet, UINT32_MAX);
1483 ASMAtomicIncU32(&pThis->cUsers);
1484 }
1485
1486 /* (rtSocketPollCheck will reset the event object). */
1487 uint32_t fRetEvents = rtSocketPollCheck(pThis, fEvents);
1488 if ( !fRetEvents
1489 && !fNoWait)
1490 {
1491 pThis->fPollEvts |= fEvents;
1492 if ( fFinalEntry
1493 && pThis->fSubscribedEvts != pThis->fPollEvts)
1494 {
1495 int rc = rtSocketPollUpdateEvents(pThis, pThis->fPollEvts);
1496 if (RT_FAILURE(rc))
1497 {
1498 pThis->fPollEvts = 0;
1499 fRetEvents = UINT32_MAX;
1500 }
1501 }
1502 }
1503
1504 if (fRetEvents || fNoWait)
1505 {
1506 if (pThis->cUsers == 1)
1507 {
1508 rtSocketPollClearEventAndMakeBlocking(pThis);
1509 pThis->hPollSet = NIL_RTPOLLSET;
1510 }
1511 ASMAtomicDecU32(&pThis->cUsers);
1512 }
1513
1514 return fRetEvents;
1515}
1516
1517
1518/**
1519 * Called after a WaitForMultipleObjects returned in order to check for pending
1520 * events and stop whatever actions that rtSocketPollStart() initiated.
1521 *
1522 * @returns Event mask or 0.
1523 *
1524 * @param hSocket The socket handle.
1525 * @param fEvents The events we're polling for.
1526 * @param fFinalEntry Set if this is the final entry for this handle
1527 * in this poll set. This can be used for dealing
1528 * with duplicate entries. Only keep in mind that
1529 * this method is called in reverse order, so the
1530 * first call will have this set (when the entire
1531 * set was processed).
1532 */
1533uint32_t rtSocketPollDone(RTSOCKET hSocket, uint32_t fEvents, bool fFinalEntry)
1534{
1535 RTSOCKETINT *pThis = hSocket;
1536 AssertPtrReturn(pThis, 0);
1537 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, 0);
1538 Assert(pThis->cUsers > 0);
1539 Assert(pThis->hPollSet != NIL_RTPOLLSET);
1540
1541 /* Harvest events and clear the event mask for the next round of polling. */
1542 uint32_t fRetEvents = rtSocketPollCheck(pThis, fEvents);
1543 pThis->fPollEvts = 0;
1544
1545 /* Make the socket blocking again and unlock the handle. */
1546 if (pThis->cUsers == 1)
1547 {
1548 rtSocketPollClearEventAndMakeBlocking(pThis);
1549 pThis->hPollSet = NIL_RTPOLLSET;
1550 }
1551 ASMAtomicDecU32(&pThis->cUsers);
1552 return fRetEvents;
1553}
1554
1555#endif /* RT_OS_WINDOWS */
Note: See TracBrowser for help on using the repository browser.

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