VirtualBox

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

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

Runtime/sockets: Don't loop in the non blocking calls

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 42.7 KB
Line 
1/* $Id: socket.cpp 31582 2010-08-11 21:33:47Z 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 rc = rtSocketError();
263#else
264 int fFlags = fcntl(pThis->hNative, F_GETFL, 0);
265 if (fFlags != -1)
266 {
267 if (fBlocking)
268 fFlags &= ~O_NONBLOCK;
269 else
270 fFlags |= O_NONBLOCK;
271
272 if (fcntl(pThis->hNative, F_SETFL, fFlags) == -1)
273 rc = rtSocketError();
274 }
275 else
276 rc = rtSocketError();
277#endif
278
279 if (RT_SUCCESS(rc))
280 pThis->fBlocking = fBlocking;
281 }
282
283 return rc;
284}
285
286/**
287 * Creates an IPRT socket handle for a native one.
288 *
289 * @returns IPRT status code.
290 * @param ppSocket Where to return the IPRT socket handle.
291 * @param hNative The native handle.
292 */
293int rtSocketCreateForNative(RTSOCKETINT **ppSocket, RTSOCKETNATIVE hNative)
294{
295 RTSOCKETINT *pThis = (RTSOCKETINT *)RTMemPoolAlloc(RTMEMPOOL_DEFAULT, sizeof(*pThis));
296 if (!pThis)
297 return VERR_NO_MEMORY;
298 pThis->u32Magic = RTSOCKET_MAGIC;
299 pThis->cUsers = 0;
300 pThis->hNative = hNative;
301 pThis->fClosed = false;
302 pThis->fBlocking = true;
303#ifdef RT_OS_WINDOWS
304 pThis->hEvent = WSA_INVALID_EVENT;
305 pThis->hPollSet = NIL_RTPOLLSET;
306 pThis->fPollEvts = 0;
307 pThis->fSubscribedEvts = 0;
308#endif
309 *ppSocket = pThis;
310 return VINF_SUCCESS;
311}
312
313
314RTDECL(int) RTSocketFromNative(PRTSOCKET phSocket, RTHCINTPTR uNative)
315{
316 AssertReturn(uNative != NIL_RTSOCKETNATIVE, VERR_INVALID_PARAMETER);
317#ifndef RT_OS_WINDOWS
318 AssertReturn(uNative >= 0, VERR_INVALID_PARAMETER);
319#endif
320 AssertPtrReturn(phSocket, VERR_INVALID_POINTER);
321 return rtSocketCreateForNative(phSocket, uNative);
322}
323
324
325/**
326 * Wrapper around socket().
327 *
328 * @returns IPRT status code.
329 * @param phSocket Where to store the handle to the socket on
330 * success.
331 * @param iDomain The protocol family (PF_XXX).
332 * @param iType The socket type (SOCK_XXX).
333 * @param iProtocol Socket parameter, usually 0.
334 */
335int rtSocketCreate(PRTSOCKET phSocket, int iDomain, int iType, int iProtocol)
336{
337 /*
338 * Create the socket.
339 */
340 RTSOCKETNATIVE hNative = socket(iDomain, iType, iProtocol);
341 if (hNative == NIL_RTSOCKETNATIVE)
342 return rtSocketError();
343
344 /*
345 * Wrap it.
346 */
347 int rc = rtSocketCreateForNative(phSocket, hNative);
348 if (RT_FAILURE(rc))
349 {
350#ifdef RT_OS_WINDOWS
351 closesocket(hNative);
352#else
353 close(hNative);
354#endif
355 }
356 return rc;
357}
358
359
360RTDECL(uint32_t) RTSocketRetain(RTSOCKET hSocket)
361{
362 RTSOCKETINT *pThis = hSocket;
363 AssertPtrReturn(pThis, UINT32_MAX);
364 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, UINT32_MAX);
365 return RTMemPoolRetain(pThis);
366}
367
368
369/**
370 * Worker for RTSocketRelease and RTSocketClose.
371 *
372 * @returns IPRT status code.
373 * @param pThis The socket handle instance data.
374 * @param fDestroy Whether we're reaching ref count zero.
375 */
376static int rtSocketCloseIt(RTSOCKETINT *pThis, bool fDestroy)
377{
378 /*
379 * Invalidate the handle structure on destroy.
380 */
381 if (fDestroy)
382 {
383 Assert(ASMAtomicReadU32(&pThis->u32Magic) == RTSOCKET_MAGIC);
384 ASMAtomicWriteU32(&pThis->u32Magic, RTSOCKET_MAGIC_DEAD);
385 }
386
387 int rc = VINF_SUCCESS;
388 if (ASMAtomicCmpXchgBool(&pThis->fClosed, true, false))
389 {
390 /*
391 * Close the native handle.
392 */
393 RTSOCKETNATIVE hNative = pThis->hNative;
394 if (hNative != NIL_RTSOCKETNATIVE)
395 {
396 pThis->hNative = NIL_RTSOCKETNATIVE;
397
398#ifdef RT_OS_WINDOWS
399 if (closesocket(hNative))
400#else
401 if (close(hNative))
402#endif
403 {
404 rc = rtSocketError();
405#ifdef RT_OS_WINDOWS
406 AssertMsgFailed(("\"%s\": closesocket(%p) -> %Rrc\n", (uintptr_t)hNative, rc));
407#else
408 AssertMsgFailed(("\"%s\": close(%d) -> %Rrc\n", hNative, rc));
409#endif
410 }
411 }
412
413#ifdef RT_OS_WINDOWS
414 /*
415 * Close the event.
416 */
417 WSAEVENT hEvent = pThis->hEvent;
418 if (hEvent == WSA_INVALID_EVENT)
419 {
420 pThis->hEvent = WSA_INVALID_EVENT;
421 WSACloseEvent(hEvent);
422 }
423#endif
424 }
425
426 return rc;
427}
428
429
430RTDECL(uint32_t) RTSocketRelease(RTSOCKET hSocket)
431{
432 RTSOCKETINT *pThis = hSocket;
433 if (pThis == NIL_RTSOCKET)
434 return 0;
435 AssertPtrReturn(pThis, UINT32_MAX);
436 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, UINT32_MAX);
437
438 /* get the refcount without killing it... */
439 uint32_t cRefs = RTMemPoolRefCount(pThis);
440 AssertReturn(cRefs != UINT32_MAX, UINT32_MAX);
441 if (cRefs == 1)
442 rtSocketCloseIt(pThis, true);
443
444 return RTMemPoolRelease(RTMEMPOOL_DEFAULT, pThis);
445}
446
447
448RTDECL(int) RTSocketClose(RTSOCKET hSocket)
449{
450 RTSOCKETINT *pThis = hSocket;
451 if (pThis == NIL_RTSOCKET)
452 return VINF_SUCCESS;
453 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
454 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
455
456 uint32_t cRefs = RTMemPoolRefCount(pThis);
457 AssertReturn(cRefs != UINT32_MAX, UINT32_MAX);
458
459 int rc = rtSocketCloseIt(pThis, cRefs == 1);
460
461 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pThis);
462 return rc;
463}
464
465
466RTDECL(RTHCUINTPTR) RTSocketToNative(RTSOCKET hSocket)
467{
468 RTSOCKETINT *pThis = hSocket;
469 AssertPtrReturn(pThis, RTHCUINTPTR_MAX);
470 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, RTHCUINTPTR_MAX);
471 return (RTHCUINTPTR)pThis->hNative;
472}
473
474
475RTDECL(int) RTSocketSetInheritance(RTSOCKET hSocket, bool fInheritable)
476{
477 RTSOCKETINT *pThis = hSocket;
478 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
479 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
480 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
481
482 int rc = VINF_SUCCESS;
483#ifdef RT_OS_WINDOWS
484 if (!SetHandleInformation((HANDLE)pThis->hNative, HANDLE_FLAG_INHERIT, fInheritable ? HANDLE_FLAG_INHERIT : 0))
485 rc = RTErrConvertFromWin32(GetLastError());
486#else
487 if (fcntl(pThis->hNative, F_SETFD, fInheritable ? 0 : FD_CLOEXEC) < 0)
488 rc = RTErrConvertFromErrno(errno);
489#endif
490
491 return rc;
492}
493
494
495RTDECL(int) RTSocketRead(RTSOCKET hSocket, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
496{
497 /*
498 * Validate input.
499 */
500 RTSOCKETINT *pThis = hSocket;
501 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
502 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
503 AssertReturn(cbBuffer > 0, VERR_INVALID_PARAMETER);
504 AssertPtr(pvBuffer);
505 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
506
507
508 int rc = rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
509 if (RT_FAILURE(rc))
510 return rc;
511
512 /*
513 * Read loop.
514 * If pcbRead is NULL we have to fill the entire buffer!
515 */
516 size_t cbRead = 0;
517 size_t cbToRead = cbBuffer;
518 for (;;)
519 {
520 rtSocketErrorReset();
521#ifdef RT_OS_WINDOWS
522 int cbNow = cbToRead >= INT_MAX/2 ? INT_MAX/2 : (int)cbToRead;
523#else
524 size_t cbNow = cbToRead;
525#endif
526 ssize_t cbBytesRead = recv(pThis->hNative, (char *)pvBuffer + cbRead, cbNow, MSG_NOSIGNAL);
527 if (cbBytesRead <= 0)
528 {
529 rc = rtSocketError();
530 Assert(RT_FAILURE_NP(rc) || cbBytesRead == 0);
531 if (RT_SUCCESS_NP(rc))
532 {
533 if (!pcbRead)
534 rc = VERR_NET_SHUTDOWN;
535 else
536 {
537 *pcbRead = 0;
538 rc = VINF_SUCCESS;
539 }
540 }
541 break;
542 }
543 if (pcbRead)
544 {
545 /* return partial data */
546 *pcbRead = cbBytesRead;
547 break;
548 }
549
550 /* read more? */
551 cbRead += cbBytesRead;
552 if (cbRead == cbBuffer)
553 break;
554
555 /* next */
556 cbToRead = cbBuffer - cbRead;
557 }
558
559 rtSocketUnlock(pThis);
560 return rc;
561}
562
563
564RTDECL(int) RTSocketWrite(RTSOCKET hSocket, const void *pvBuffer, size_t cbBuffer)
565{
566 /*
567 * Validate input.
568 */
569 RTSOCKETINT *pThis = hSocket;
570 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
571 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
572 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
573
574 int rc = rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
575 if (RT_FAILURE(rc))
576 return rc;
577
578 /*
579 * Try write all at once.
580 */
581#ifdef RT_OS_WINDOWS
582 int cbNow = cbBuffer >= INT_MAX / 2 ? INT_MAX / 2 : (int)cbBuffer;
583#else
584 size_t cbNow = cbBuffer >= SSIZE_MAX ? SSIZE_MAX : cbBuffer;
585#endif
586 ssize_t cbWritten = send(pThis->hNative, (const char *)pvBuffer, cbNow, MSG_NOSIGNAL);
587 if (RT_LIKELY((size_t)cbWritten == cbBuffer && cbWritten >= 0))
588 rc = VINF_SUCCESS;
589 else if (cbWritten < 0)
590 rc = rtSocketError();
591 else
592 {
593 /*
594 * Unfinished business, write the remainder of the request. Must ignore
595 * VERR_INTERRUPTED here if we've managed to send something.
596 */
597 size_t cbSentSoFar = 0;
598 for (;;)
599 {
600 /* advance */
601 cbBuffer -= (size_t)cbWritten;
602 if (!cbBuffer)
603 break;
604 cbSentSoFar += (size_t)cbWritten;
605 pvBuffer = (char const *)pvBuffer + cbWritten;
606
607 /* send */
608#ifdef RT_OS_WINDOWS
609 cbNow = cbBuffer >= INT_MAX / 2 ? INT_MAX / 2 : (int)cbBuffer;
610#else
611 cbNow = cbBuffer >= SSIZE_MAX ? SSIZE_MAX : cbBuffer;
612#endif
613 cbWritten = send(pThis->hNative, (const char *)pvBuffer, cbNow, MSG_NOSIGNAL);
614 if (cbWritten >= 0)
615 AssertMsg(cbBuffer >= (size_t)cbWritten, ("Wrote more than we requested!!! cbWritten=%zu cbBuffer=%zu rtSocketError()=%d\n",
616 cbWritten, cbBuffer, rtSocketError()));
617 else
618 {
619 rc = rtSocketError();
620 if (rc != VERR_INTERNAL_ERROR || cbSentSoFar == 0)
621 break;
622 cbWritten = 0;
623 rc = VINF_SUCCESS;
624 }
625 }
626 }
627
628 rtSocketUnlock(pThis);
629 return rc;
630}
631
632
633RTDECL(int) RTSocketSgWrite(RTSOCKET hSocket, PCRTSGBUF pSgBuf)
634{
635 /*
636 * Validate input.
637 */
638 RTSOCKETINT *pThis = hSocket;
639 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
640 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
641 AssertPtrReturn(pSgBuf, VERR_INVALID_PARAMETER);
642 AssertReturn(pSgBuf->cSegs > 0, VERR_INVALID_PARAMETER);
643 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
644
645 int rc = rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
646 if (RT_FAILURE(rc))
647 return rc;
648
649 /*
650 * Construct message descriptor (translate pSgBuf) and send it.
651 */
652 rc = VERR_NO_TMP_MEMORY;
653#ifdef RT_OS_WINDOWS
654 AssertCompileSize(WSABUF, sizeof(RTSGSEG));
655 AssertCompileMemberSize(WSABUF, buf, RT_SIZEOFMEMB(RTSGSEG, pvSeg));
656
657 LPWSABUF paMsg = (LPWSABUF)RTMemTmpAllocZ(pSgBuf->cSegs * sizeof(WSABUF));
658 if (paMsg)
659 {
660 for (unsigned i = 0; i < pSgBuf->cSegs; i++)
661 {
662 paMsg[i].buf = (char *)pSgBuf->paSegs[i].pvSeg;
663 paMsg[i].len = (u_long)pSgBuf->paSegs[i].cbSeg;
664 }
665
666 DWORD dwSent;
667 int hrc = WSASend(pThis->hNative, paMsg, pSgBuf->cSegs, &dwSent,
668 MSG_NOSIGNAL, NULL, NULL);
669 if (!hrc)
670 rc = VINF_SUCCESS;
671/** @todo check for incomplete writes */
672 else
673 rc = rtSocketError();
674
675 RTMemTmpFree(paMsg);
676 }
677
678#else /* !RT_OS_WINDOWS */
679 AssertCompileSize(struct iovec, sizeof(RTSGSEG));
680 AssertCompileMemberSize(struct iovec, iov_base, RT_SIZEOFMEMB(RTSGSEG, pvSeg));
681 AssertCompileMemberSize(struct iovec, iov_len, RT_SIZEOFMEMB(RTSGSEG, cbSeg));
682
683 struct iovec *paMsg = (struct iovec *)RTMemTmpAllocZ(pSgBuf->cSegs * sizeof(struct iovec));
684 if (paMsg)
685 {
686 for (unsigned i = 0; i < pSgBuf->cSegs; i++)
687 {
688 paMsg[i].iov_base = pSgBuf->paSegs[i].pvSeg;
689 paMsg[i].iov_len = pSgBuf->paSegs[i].cbSeg;
690 }
691
692 struct msghdr msgHdr;
693 RT_ZERO(msgHdr);
694 msgHdr.msg_iov = paMsg;
695 msgHdr.msg_iovlen = pSgBuf->cSegs;
696 ssize_t cbWritten = sendmsg(pThis->hNative, &msgHdr, MSG_NOSIGNAL);
697 if (RT_LIKELY(cbWritten >= 0))
698 rc = VINF_SUCCESS;
699/** @todo check for incomplete writes */
700 else
701 rc = rtSocketError();
702
703 RTMemTmpFree(paMsg);
704 }
705#endif /* !RT_OS_WINDOWS */
706
707 rtSocketUnlock(pThis);
708 return rc;
709}
710
711
712RTDECL(int) RTSocketSgWriteL(RTSOCKET hSocket, size_t cSegs, ...)
713{
714 va_list va;
715 va_start(va, cSegs);
716 int rc = RTSocketSgWriteLV(hSocket, cSegs, va);
717 va_end(va);
718 return rc;
719}
720
721
722RTDECL(int) RTSocketSgWriteLV(RTSOCKET hSocket, size_t cSegs, va_list va)
723{
724 /*
725 * Set up a S/G segment array + buffer on the stack and pass it
726 * on to RTSocketSgWrite.
727 */
728 Assert(cSegs <= 16);
729 PRTSGSEG paSegs = (PRTSGSEG)alloca(cSegs * sizeof(RTSGSEG));
730 AssertReturn(paSegs, VERR_NO_TMP_MEMORY);
731 for (size_t i = 0; i < cSegs; i++)
732 {
733 paSegs[i].pvSeg = va_arg(va, void *);
734 paSegs[i].cbSeg = va_arg(va, size_t);
735 }
736
737 RTSGBUF SgBuf;
738 RTSgBufInit(&SgBuf, paSegs, cSegs);
739 return RTSocketSgWrite(hSocket, &SgBuf);
740}
741
742
743RTDECL(int) RTSocketReadNB(RTSOCKET hSocket, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
744{
745 /*
746 * Validate input.
747 */
748 RTSOCKETINT *pThis = hSocket;
749 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
750 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
751 AssertReturn(cbBuffer > 0, VERR_INVALID_PARAMETER);
752 AssertPtr(pvBuffer);
753 AssertPtrReturn(pcbRead, VERR_INVALID_PARAMETER);
754 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
755
756 int rc = rtSocketSwitchBlockingMode(pThis, false /* fBlocking */);
757 if (RT_FAILURE(rc))
758 return rc;
759
760 rtSocketErrorReset();
761#ifdef RT_OS_WINDOWS
762 int cbNow = cbBuffer >= INT_MAX/2 ? INT_MAX/2 : (int)cbBuffer;
763#else
764 size_t cbNow = cbBuffer;
765#endif
766 ssize_t cbRead = recv(pThis->hNative, pvBuffer, cbNow, MSG_NOSIGNAL);
767 if (cbRead >= 0)
768 *pcbRead = cbRead;
769 else if (errno == EAGAIN)
770 {
771 *pcbRead = 0;
772 rc = VINF_TRY_AGAIN;
773 }
774 else
775 rc = RTErrConvertFromErrno(errno);
776
777 rtSocketUnlock(pThis);
778 return rc;
779}
780
781
782RTDECL(int) RTSocketWriteNB(RTSOCKET hSocket, const void *pvBuffer, size_t cbBuffer, size_t *pcbWritten)
783{
784 /*
785 * Validate input.
786 */
787 RTSOCKETINT *pThis = hSocket;
788 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
789 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
790 AssertPtrReturn(pcbWritten, VERR_INVALID_PARAMETER);
791 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
792
793 int rc = rtSocketSwitchBlockingMode(pThis, false /* fBlocking */);
794 if (RT_FAILURE(rc))
795 return rc;
796
797 rtSocketErrorReset();
798#ifdef RT_OS_WINDOWS
799 int cbNow = RT_MIN((int)cbBuffer, INT_MAX/2);
800#else
801 size_t cbNow = cbBuffer;
802#endif
803 ssize_t cbWritten = send(pThis->hNative, pvBuffer, cbNow, MSG_NOSIGNAL);
804 if (cbWritten >= 0)
805 *pcbWritten = cbWritten;
806 else if (errno == EAGAIN)
807 {
808 *pcbWritten = 0;
809 rc = VINF_TRY_AGAIN;
810 }
811 else
812 rc = RTErrConvertFromErrno(errno);
813
814 rtSocketUnlock(pThis);
815 return rc;
816}
817
818
819RTDECL(int) RTSocketSgWriteNB(RTSOCKET hSocket, PCRTSGBUF pSgBuf, size_t *pcbWritten)
820{
821 /*
822 * Validate input.
823 */
824 RTSOCKETINT *pThis = hSocket;
825 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
826 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
827 AssertPtrReturn(pSgBuf, VERR_INVALID_PARAMETER);
828 AssertPtrReturn(pcbWritten, VERR_INVALID_PARAMETER);
829 AssertReturn(pSgBuf->cSegs > 0, VERR_INVALID_PARAMETER);
830 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
831
832 int rc = rtSocketSwitchBlockingMode(pThis, false /* fBlocking */);
833 if (RT_FAILURE(rc))
834 return rc;
835
836 unsigned cSegsToSend = 0;
837 rc = VERR_NO_TMP_MEMORY;
838#ifdef RT_OS_WINDOWS
839 LPWSABUF paMsg = NULL;
840
841 RTSgBufMapToNative(paMsg, pSgBuf, WSABUF, buf, char *, len, u_long, cSegsToSend);
842 if (paMsg)
843 {
844 DWORD dwSent = 0;
845 int hrc = WSASend(pThis->hNative, paMsg, cSegsToSend, &dwSent,
846 MSG_NOSIGNAL, NULL, NULL);
847 if (!hrc)
848 rc = VINF_SUCCESS;
849 else
850 rc = rtSocketError();
851
852 *pcbWritten = dwSent;
853
854 RTMemTmpFree(paMsg);
855 }
856
857#else /* !RT_OS_WINDOWS */
858 struct iovec *paMsg = NULL;
859
860 RTSgBufMapToNative(paMsg, pSgBuf, struct iovec, iov_base, void *, iov_len, size_t, cSegsToSend);
861 if (paMsg)
862 {
863 struct msghdr msgHdr;
864 RT_ZERO(msgHdr);
865 msgHdr.msg_iov = paMsg;
866 msgHdr.msg_iovlen = cSegsToSend;
867 ssize_t cbWritten = sendmsg(pThis->hNative, &msgHdr, MSG_NOSIGNAL);
868 if (RT_LIKELY(cbWritten >= 0))
869 {
870 rc = VINF_SUCCESS;
871 *pcbWritten = cbWritten;
872 }
873 else
874 rc = rtSocketError();
875
876 RTMemTmpFree(paMsg);
877 }
878#endif /* !RT_OS_WINDOWS */
879
880 rtSocketUnlock(pThis);
881 return rc;
882}
883
884
885RTDECL(int) RTSocketSgWriteLNB(RTSOCKET hSocket, size_t cSegs, size_t *pcbWritten, ...)
886{
887 va_list va;
888 va_start(va, pcbWritten);
889 int rc = RTSocketSgWriteLVNB(hSocket, cSegs, pcbWritten, va);
890 va_end(va);
891 return rc;
892}
893
894
895RTDECL(int) RTSocketSgWriteLVNB(RTSOCKET hSocket, size_t cSegs, size_t *pcbWritten, va_list va)
896{
897 /*
898 * Set up a S/G segment array + buffer on the stack and pass it
899 * on to RTSocketSgWrite.
900 */
901 Assert(cSegs <= 16);
902 PRTSGSEG paSegs = (PRTSGSEG)alloca(cSegs * sizeof(RTSGSEG));
903 AssertReturn(paSegs, VERR_NO_TMP_MEMORY);
904 for (size_t i = 0; i < cSegs; i++)
905 {
906 paSegs[i].pvSeg = va_arg(va, void *);
907 paSegs[i].cbSeg = va_arg(va, size_t);
908 }
909
910 RTSGBUF SgBuf;
911 RTSgBufInit(&SgBuf, paSegs, cSegs);
912 return RTSocketSgWriteNB(hSocket, &SgBuf, pcbWritten);
913}
914
915
916RTDECL(int) RTSocketSelectOne(RTSOCKET hSocket, RTMSINTERVAL cMillies)
917{
918 /*
919 * Validate input.
920 */
921 RTSOCKETINT *pThis = hSocket;
922 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
923 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
924 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
925
926 /*
927 * Set up the file descriptor sets and do the select.
928 */
929 fd_set fdsetR;
930 FD_ZERO(&fdsetR);
931 FD_SET(pThis->hNative, &fdsetR);
932
933 fd_set fdsetE = fdsetR;
934
935 int rc;
936 if (cMillies == RT_INDEFINITE_WAIT)
937 rc = select(pThis->hNative + 1, &fdsetR, NULL, &fdsetE, NULL);
938 else
939 {
940 struct timeval timeout;
941 timeout.tv_sec = cMillies / 1000;
942 timeout.tv_usec = (cMillies % 1000) * 1000;
943 rc = select(pThis->hNative + 1, &fdsetR, NULL, &fdsetE, &timeout);
944 }
945 if (rc > 0)
946 rc = VINF_SUCCESS;
947 else if (rc == 0)
948 rc = VERR_TIMEOUT;
949 else
950 rc = rtSocketError();
951
952 return rc;
953}
954
955
956RTDECL(int) RTSocketShutdown(RTSOCKET hSocket, bool fRead, bool fWrite)
957{
958 /*
959 * Validate input, don't lock it because we might want to interrupt a call
960 * active on a different thread.
961 */
962 RTSOCKETINT *pThis = hSocket;
963 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
964 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
965 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
966 AssertReturn(fRead || fWrite, VERR_INVALID_PARAMETER);
967
968 /*
969 * Do the job.
970 */
971 int rc = VINF_SUCCESS;
972 int fHow;
973 if (fRead && fWrite)
974 fHow = SHUT_RDWR;
975 else if (fRead)
976 fHow = SHUT_RD;
977 else
978 fHow = SHUT_WR;
979 if (shutdown(pThis->hNative, fHow) == -1)
980 rc = rtSocketError();
981
982 return rc;
983}
984
985
986/**
987 * Converts from a native socket address to a generic IPRT network address.
988 *
989 * @returns IPRT status code.
990 * @param pSrc The source address.
991 * @param cbSrc The size of the source address.
992 * @param pAddr Where to return the generic IPRT network
993 * address.
994 */
995static int rtSocketConvertAddress(RTSOCKADDRUNION const *pSrc, size_t cbSrc, PRTNETADDR pAddr)
996{
997 /*
998 * Convert the address.
999 */
1000 if ( cbSrc == sizeof(struct sockaddr_in)
1001 && pSrc->Addr.sa_family == AF_INET)
1002 {
1003 RT_ZERO(*pAddr);
1004 pAddr->enmType = RTNETADDRTYPE_IPV4;
1005 pAddr->uPort = RT_N2H_U16(pSrc->Ipv4.sin_port);
1006 pAddr->uAddr.IPv4.u = pSrc->Ipv4.sin_addr.s_addr;
1007 }
1008#ifdef IPRT_WITH_TCPIP_V6
1009 else if ( cbSrc == sizeof(struct sockaddr_in6)
1010 && pSrc->Addr.sa_family == AF_INET6)
1011 {
1012 RT_ZERO(*pAddr);
1013 pAddr->enmType = RTNETADDRTYPE_IPV6;
1014 pAddr->uPort = RT_N2H_U16(pSrc->Ipv6.sin6_port);
1015 pAddr->uAddr.IPv6.au32[0] = pSrc->Ipv6.sin6_addr.s6_addr32[0];
1016 pAddr->uAddr.IPv6.au32[1] = pSrc->Ipv6.sin6_addr.s6_addr32[1];
1017 pAddr->uAddr.IPv6.au32[2] = pSrc->Ipv6.sin6_addr.s6_addr32[2];
1018 pAddr->uAddr.IPv6.au32[3] = pSrc->Ipv6.sin6_addr.s6_addr32[3];
1019 }
1020#endif
1021 else
1022 return VERR_NET_ADDRESS_FAMILY_NOT_SUPPORTED;
1023 return VINF_SUCCESS;
1024}
1025
1026
1027RTDECL(int) RTSocketGetLocalAddress(RTSOCKET hSocket, PRTNETADDR pAddr)
1028{
1029 /*
1030 * Validate input.
1031 */
1032 RTSOCKETINT *pThis = hSocket;
1033 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1034 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1035 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
1036
1037 /*
1038 * Get the address and convert it.
1039 */
1040 int rc;
1041 RTSOCKADDRUNION u;
1042#ifdef RT_OS_WINDOWS
1043 int cbAddr = sizeof(u);
1044#else
1045 socklen_t cbAddr = sizeof(u);
1046#endif
1047 RT_ZERO(u);
1048 if (getsockname(pThis->hNative, &u.Addr, &cbAddr) == 0)
1049 rc = rtSocketConvertAddress(&u, cbAddr, pAddr);
1050 else
1051 rc = rtSocketError();
1052
1053 return rc;
1054}
1055
1056
1057RTDECL(int) RTSocketGetPeerAddress(RTSOCKET hSocket, PRTNETADDR pAddr)
1058{
1059 /*
1060 * Validate input.
1061 */
1062 RTSOCKETINT *pThis = hSocket;
1063 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1064 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1065 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
1066
1067 /*
1068 * Get the address and convert it.
1069 */
1070 int rc;
1071 RTSOCKADDRUNION u;
1072#ifdef RT_OS_WINDOWS
1073 int cbAddr = sizeof(u);
1074#else
1075 socklen_t cbAddr = sizeof(u);
1076#endif
1077 RT_ZERO(u);
1078 if (getpeername(pThis->hNative, &u.Addr, &cbAddr) == 0)
1079 rc = rtSocketConvertAddress(&u, cbAddr, pAddr);
1080 else
1081 rc = rtSocketError();
1082
1083 return rc;
1084}
1085
1086
1087
1088/**
1089 * Wrapper around bind.
1090 *
1091 * @returns IPRT status code.
1092 * @param hSocket The socket handle.
1093 * @param pAddr The socket address to bind to.
1094 * @param cbAddr The size of the address structure @a pAddr
1095 * points to.
1096 */
1097int rtSocketBind(RTSOCKET hSocket, const struct sockaddr *pAddr, int cbAddr)
1098{
1099 /*
1100 * Validate input.
1101 */
1102 RTSOCKETINT *pThis = hSocket;
1103 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1104 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1105 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1106
1107 int rc = VINF_SUCCESS;
1108 if (bind(pThis->hNative, pAddr, cbAddr) != 0)
1109 rc = rtSocketError();
1110
1111 rtSocketUnlock(pThis);
1112 return rc;
1113}
1114
1115
1116/**
1117 * Wrapper around listen.
1118 *
1119 * @returns IPRT status code.
1120 * @param hSocket The socket handle.
1121 * @param cMaxPending The max number of pending connections.
1122 */
1123int rtSocketListen(RTSOCKET hSocket, int cMaxPending)
1124{
1125 /*
1126 * Validate input.
1127 */
1128 RTSOCKETINT *pThis = hSocket;
1129 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1130 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1131 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1132
1133 int rc = VINF_SUCCESS;
1134 if (listen(pThis->hNative, cMaxPending) != 0)
1135 rc = rtSocketError();
1136
1137 rtSocketUnlock(pThis);
1138 return rc;
1139}
1140
1141
1142/**
1143 * Wrapper around accept.
1144 *
1145 * @returns IPRT status code.
1146 * @param hSocket The socket handle.
1147 * @param phClient Where to return the client socket handle on
1148 * success.
1149 * @param pAddr Where to return the client address.
1150 * @param pcbAddr On input this gives the size buffer size of what
1151 * @a pAddr point to. On return this contains the
1152 * size of what's stored at @a pAddr.
1153 */
1154int rtSocketAccept(RTSOCKET hSocket, PRTSOCKET phClient, struct sockaddr *pAddr, size_t *pcbAddr)
1155{
1156 /*
1157 * Validate input.
1158 * Only lock the socket temporarily while we get the native handle, so that
1159 * we can safely shutdown and destroy the socket from a different thread.
1160 */
1161 RTSOCKETINT *pThis = hSocket;
1162 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1163 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1164 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1165
1166 /*
1167 * Call accept().
1168 */
1169 rtSocketErrorReset();
1170 int rc = VINF_SUCCESS;
1171#ifdef RT_OS_WINDOWS
1172 int cbAddr = (int)*pcbAddr;
1173#else
1174 socklen_t cbAddr = *pcbAddr;
1175#endif
1176 RTSOCKETNATIVE hNativeClient = accept(pThis->hNative, pAddr, &cbAddr);
1177 if (hNativeClient != NIL_RTSOCKETNATIVE)
1178 {
1179 *pcbAddr = cbAddr;
1180
1181 /*
1182 * Wrap the client socket.
1183 */
1184 rc = rtSocketCreateForNative(phClient, hNativeClient);
1185 if (RT_FAILURE(rc))
1186 {
1187#ifdef RT_OS_WINDOWS
1188 closesocket(hNativeClient);
1189#else
1190 close(hNativeClient);
1191#endif
1192 }
1193 }
1194 else
1195 rc = rtSocketError();
1196
1197 rtSocketUnlock(pThis);
1198 return rc;
1199}
1200
1201
1202/**
1203 * Wrapper around connect.
1204 *
1205 * @returns IPRT status code.
1206 * @param hSocket The socket handle.
1207 * @param pAddr The socket address to connect to.
1208 * @param cbAddr The size of the address structure @a pAddr
1209 * points to.
1210 */
1211int rtSocketConnect(RTSOCKET hSocket, const struct sockaddr *pAddr, int cbAddr)
1212{
1213 /*
1214 * Validate input.
1215 */
1216 RTSOCKETINT *pThis = hSocket;
1217 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1218 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1219 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1220
1221 int rc = VINF_SUCCESS;
1222 if (connect(pThis->hNative, pAddr, cbAddr) != 0)
1223 rc = rtSocketError();
1224
1225 rtSocketUnlock(pThis);
1226 return rc;
1227}
1228
1229
1230/**
1231 * Wrapper around setsockopt.
1232 *
1233 * @returns IPRT status code.
1234 * @param hSocket The socket handle.
1235 * @param iLevel The protocol level, e.g. IPPORTO_TCP.
1236 * @param iOption The option, e.g. TCP_NODELAY.
1237 * @param pvValue The value buffer.
1238 * @param cbValue The size of the value pointed to by pvValue.
1239 */
1240int rtSocketSetOpt(RTSOCKET hSocket, int iLevel, int iOption, void const *pvValue, int cbValue)
1241{
1242 /*
1243 * Validate input.
1244 */
1245 RTSOCKETINT *pThis = hSocket;
1246 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1247 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1248 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1249
1250 int rc = VINF_SUCCESS;
1251 if (setsockopt(pThis->hNative, iLevel, iOption, (const char *)pvValue, cbValue) != 0)
1252 rc = rtSocketError();
1253
1254 rtSocketUnlock(pThis);
1255 return rc;
1256}
1257
1258#ifdef RT_OS_WINDOWS
1259
1260/**
1261 * Internal RTPollSetAdd helper that returns the handle that should be added to
1262 * the pollset.
1263 *
1264 * @returns Valid handle on success, INVALID_HANDLE_VALUE on failure.
1265 * @param hSocket The socket handle.
1266 * @param fEvents The events we're polling for.
1267 * @param ph wher to put the primary handle.
1268 */
1269int rtSocketPollGetHandle(RTSOCKET hSocket, uint32_t fEvents, PHANDLE ph)
1270{
1271 RTSOCKETINT *pThis = hSocket;
1272 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1273 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1274 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1275
1276 int rc = VINF_SUCCESS;
1277 if (pThis->hEvent != WSA_INVALID_EVENT)
1278 *ph = pThis->hEvent;
1279 else
1280 {
1281 *ph = pThis->hEvent = WSACreateEvent();
1282 if (pThis->hEvent == WSA_INVALID_EVENT)
1283 rc = rtSocketError();
1284 }
1285
1286 rtSocketUnlock(pThis);
1287 return rc;
1288}
1289
1290
1291/**
1292 * Undos the harm done by WSAEventSelect.
1293 *
1294 * @returns IPRT status code.
1295 * @param pThis The socket handle.
1296 */
1297static int rtSocketPollClearEventAndRestoreBlocking(RTSOCKETINT *pThis)
1298{
1299 int rc = VINF_SUCCESS;
1300 if (pThis->fSubscribedEvts)
1301 {
1302 if (WSAEventSelect(pThis->hNative, WSA_INVALID_EVENT, 0) == 0)
1303 {
1304 pThis->fSubscribedEvts = 0;
1305
1306 /*
1307 * Switch back to blocking mode if that was the state before the
1308 * operation.
1309 */
1310 if (pThis->fBlocking)
1311 {
1312 u_long fNonBlocking = 0;
1313 int rc2 = ioctlsocket(pThis->hNative, FIONBIO, &fNonBlocking);
1314 if (rc2 != 0)
1315 {
1316 rc = rtSocketError();
1317 AssertMsgFailed(("%Rrc; rc2=%d\n", rc, rc2));
1318 }
1319 }
1320 }
1321 else
1322 {
1323 rc = rtSocketError();
1324 AssertMsgFailed(("%Rrc\n", rc));
1325 }
1326 }
1327 return rc;
1328}
1329
1330
1331/**
1332 * Updates the mask of events we're subscribing to.
1333 *
1334 * @returns IPRT status code.
1335 * @param pThis The socket handle.
1336 * @param fEvents The events we want to subscribe to.
1337 */
1338static int rtSocketPollUpdateEvents(RTSOCKETINT *pThis, uint32_t fEvents)
1339{
1340 LONG fNetworkEvents = 0;
1341 if (fEvents & RTPOLL_EVT_READ)
1342 fNetworkEvents |= FD_READ;
1343 if (fEvents & RTPOLL_EVT_WRITE)
1344 fNetworkEvents |= FD_WRITE;
1345 if (fEvents & RTPOLL_EVT_ERROR)
1346 fNetworkEvents |= FD_CLOSE;
1347 if (WSAEventSelect(pThis->hNative, pThis->hEvent, fNetworkEvents) == 0)
1348 {
1349 pThis->fSubscribedEvts = fEvents;
1350 return VINF_SUCCESS;
1351 }
1352
1353 int rc = rtSocketError();
1354 AssertMsgFailed(("fNetworkEvents=%#x rc=%Rrc\n", fNetworkEvents, rtSocketError()));
1355 return rc;
1356}
1357
1358
1359/**
1360 * Checks for pending events.
1361 *
1362 * @returns Event mask or 0.
1363 * @param pThis The socket handle.
1364 * @param fEvents The desired events.
1365 */
1366static uint32_t rtSocketPollCheck(RTSOCKETINT *pThis, uint32_t fEvents)
1367{
1368 int rc = VINF_SUCCESS;
1369 uint32_t fRetEvents = 0;
1370
1371 /* Make sure WSAEnumNetworkEvents returns what we want. */
1372 if ((pThis->fSubscribedEvts & fEvents) != fEvents)
1373 rc = rtSocketPollUpdateEvents(pThis, pThis->fSubscribedEvts | fEvents);
1374
1375 /* Get the event mask, ASSUMES that WSAEnumNetworkEvents doesn't clear stuff. */
1376 WSANETWORKEVENTS NetEvts;
1377 RT_ZERO(NetEvts);
1378 if (WSAEnumNetworkEvents(pThis->hNative, pThis->hEvent, &NetEvts) == 0)
1379 {
1380 if ( (NetEvts.lNetworkEvents & FD_READ)
1381 && (fEvents & RTPOLL_EVT_READ)
1382 && NetEvts.iErrorCode[FD_READ_BIT] == 0)
1383 fRetEvents |= RTPOLL_EVT_READ;
1384
1385 if ( (NetEvts.lNetworkEvents & FD_WRITE)
1386 && (fEvents & RTPOLL_EVT_WRITE)
1387 && NetEvts.iErrorCode[FD_WRITE_BIT] == 0)
1388 fRetEvents |= RTPOLL_EVT_WRITE;
1389
1390 if (fEvents & RTPOLL_EVT_ERROR)
1391 {
1392 if (NetEvts.lNetworkEvents & FD_CLOSE)
1393 fRetEvents |= RTPOLL_EVT_ERROR;
1394 else
1395 for (uint32_t i = 0; i < FD_MAX_EVENTS; i++)
1396 if ( (NetEvts.lNetworkEvents & (1L << i))
1397 && NetEvts.iErrorCode[i] != 0)
1398 fRetEvents |= RTPOLL_EVT_ERROR;
1399 }
1400 }
1401 else
1402 rc = rtSocketError();
1403
1404 /* Fall back on select if we hit an error above. */
1405 if (RT_FAILURE(rc))
1406 {
1407 /** @todo */
1408 }
1409
1410 return fRetEvents;
1411}
1412
1413
1414/**
1415 * Internal RTPoll helper that polls the socket handle and, if @a fNoWait is
1416 * clear, starts whatever actions we've got running during the poll call.
1417 *
1418 * @returns 0 if no pending events, actions initiated if @a fNoWait is clear.
1419 * Event mask (in @a fEvents) and no actions if the handle is ready
1420 * already.
1421 * UINT32_MAX (asserted) if the socket handle is busy in I/O or a
1422 * different poll set.
1423 *
1424 * @param hSocket The socket handle.
1425 * @param hPollSet The poll set handle (for access checks).
1426 * @param fEvents The events we're polling for.
1427 * @param fFinalEntry Set if this is the final entry for this handle
1428 * in this poll set. This can be used for dealing
1429 * with duplicate entries.
1430 * @param fNoWait Set if it's a zero-wait poll call. Clear if
1431 * we'll wait for an event to occur.
1432 *
1433 * @remarks There is a potential race wrt duplicate handles when @a fNoWait is
1434 * @c true, we don't currently care about that oddity...
1435 */
1436uint32_t rtSocketPollStart(RTSOCKET hSocket, RTPOLLSET hPollSet, uint32_t fEvents, bool fFinalEntry, bool fNoWait)
1437{
1438 RTSOCKETINT *pThis = hSocket;
1439 AssertPtrReturn(pThis, UINT32_MAX);
1440 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, UINT32_MAX);
1441 if (rtSocketTryLock(pThis))
1442 pThis->hPollSet = hPollSet;
1443 else
1444 {
1445 AssertReturn(pThis->hPollSet == hPollSet, UINT32_MAX);
1446 ASMAtomicIncU32(&pThis->cUsers);
1447 }
1448
1449 /* (rtSocketPollCheck will reset the event object). */
1450 uint32_t fRetEvents = rtSocketPollCheck(pThis, fEvents);
1451 if ( !fRetEvents
1452 && !fNoWait)
1453 {
1454 pThis->fPollEvts |= fEvents;
1455 if ( fFinalEntry
1456 && pThis->fSubscribedEvts != pThis->fPollEvts)
1457 {
1458 int rc = rtSocketPollUpdateEvents(pThis, pThis->fPollEvts);
1459 if (RT_FAILURE(rc))
1460 {
1461 pThis->fPollEvts = 0;
1462 fRetEvents = UINT32_MAX;
1463 }
1464 }
1465 }
1466
1467 if (fRetEvents || fNoWait)
1468 {
1469 if (pThis->cUsers == 1)
1470 {
1471 rtSocketPollClearEventAndRestoreBlocking(pThis);
1472 pThis->hPollSet = NIL_RTPOLLSET;
1473 }
1474 ASMAtomicDecU32(&pThis->cUsers);
1475 }
1476
1477 return fRetEvents;
1478}
1479
1480
1481/**
1482 * Called after a WaitForMultipleObjects returned in order to check for pending
1483 * events and stop whatever actions that rtSocketPollStart() initiated.
1484 *
1485 * @returns Event mask or 0.
1486 *
1487 * @param hSocket The socket handle.
1488 * @param fEvents The events we're polling for.
1489 * @param fFinalEntry Set if this is the final entry for this handle
1490 * in this poll set. This can be used for dealing
1491 * with duplicate entries. Only keep in mind that
1492 * this method is called in reverse order, so the
1493 * first call will have this set (when the entire
1494 * set was processed).
1495 */
1496uint32_t rtSocketPollDone(RTSOCKET hSocket, uint32_t fEvents, bool fFinalEntry)
1497{
1498 RTSOCKETINT *pThis = hSocket;
1499 AssertPtrReturn(pThis, 0);
1500 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, 0);
1501 Assert(pThis->cUsers > 0);
1502 Assert(pThis->hPollSet != NIL_RTPOLLSET);
1503
1504 /* Harvest events and clear the event mask for the next round of polling. */
1505 uint32_t fRetEvents = rtSocketPollCheck(pThis, fEvents);
1506 pThis->fPollEvts = 0;
1507
1508 /* Make the socket blocking again and unlock the handle. */
1509 if (pThis->cUsers == 1)
1510 {
1511 rtSocketPollClearEventAndRestoreBlocking(pThis);
1512 pThis->hPollSet = NIL_RTPOLLSET;
1513 }
1514 ASMAtomicDecU32(&pThis->cUsers);
1515 return fRetEvents;
1516}
1517
1518#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