VirtualBox

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

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

Runtime/socket: Make use of the new method to convert the S/G buffer to another type (only non blocking version for now to not risk breaking something else)

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 43.5 KB
Line 
1/* $Id: socket.cpp 31450 2010-08-08 12:51:20Z 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.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#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 /*
761 * Read loop.
762 */
763 size_t cbRead = 0;
764 size_t cbToRead = cbBuffer;
765 for (;;)
766 {
767 rtSocketErrorReset();
768#ifdef RT_OS_WINDOWS
769 int cbNow = cbToRead >= INT_MAX/2 ? INT_MAX/2 : (int)cbToRead;
770#else
771 size_t cbNow = cbToRead;
772#endif
773 ssize_t cbBytesRead = recv(pThis->hNative, (char *)pvBuffer + cbRead, cbNow, MSG_NOSIGNAL);
774 if (cbBytesRead <= 0)
775 {
776 rc = rtSocketError();
777 Assert(RT_FAILURE_NP(rc) || cbBytesRead == 0);
778 if (RT_SUCCESS_NP(rc))
779 {
780 *pcbRead = 0;
781 rc = VINF_SUCCESS;
782 }
783 else
784 *pcbRead = cbRead;
785 break;
786 }
787
788 /* read more? */
789 cbRead += cbBytesRead;
790 if (cbRead == cbBuffer)
791 {
792 *pcbRead = cbRead;
793 break;
794 }
795
796 /* next */
797 cbToRead = cbBuffer - cbRead;
798 }
799
800 rtSocketUnlock(pThis);
801 return rc;
802}
803
804
805RTDECL(int) RTSocketWriteNB(RTSOCKET hSocket, const void *pvBuffer, size_t cbBuffer, size_t *pcbWritten)
806{
807 /*
808 * Validate input.
809 */
810 RTSOCKETINT *pThis = hSocket;
811 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
812 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
813 AssertPtrReturn(pcbWritten, VERR_INVALID_PARAMETER);
814 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
815
816 int rc = rtSocketSwitchBlockingMode(pThis, false /* fBlocking */);
817 if (RT_FAILURE(rc))
818 return rc;
819
820 /*
821 * Write loop.
822 */
823 size_t cbWrite = 0;
824 size_t cbToWrite = cbBuffer;
825 for (;;)
826 {
827 rtSocketErrorReset();
828#ifdef RT_OS_WINDOWS
829 int cbNow = RT_MIN((int)cbToWrite, INT_MAX/2);
830#else
831 size_t cbNow = cbToWrite;
832#endif
833 ssize_t cbBytesWritten = send(pThis->hNative, (char *)pvBuffer + cbWrite, cbNow, MSG_NOSIGNAL);
834 if (cbBytesWritten < 0)
835 {
836 rc = rtSocketError();
837 *pcbWritten = cbWrite;
838 break;
839 }
840
841 /* write more? */
842 cbWrite += cbBytesWritten;
843 if (cbWrite == cbBuffer)
844 {
845 *pcbWritten = cbWrite;
846 break;
847 }
848
849 /* next */
850 cbToWrite = cbBuffer - cbWrite;
851 }
852
853 rtSocketUnlock(pThis);
854 return rc;
855}
856
857
858RTDECL(int) RTSocketSgWriteNB(RTSOCKET hSocket, PCRTSGBUF pSgBuf, size_t *pcbWritten)
859{
860 /*
861 * Validate input.
862 */
863 RTSOCKETINT *pThis = hSocket;
864 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
865 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
866 AssertPtrReturn(pSgBuf, VERR_INVALID_PARAMETER);
867 AssertPtrReturn(pcbWritten, VERR_INVALID_PARAMETER);
868 AssertReturn(pSgBuf->cSegs > 0, VERR_INVALID_PARAMETER);
869 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
870
871 int rc = rtSocketSwitchBlockingMode(pThis, false /* fBlocking */);
872 if (RT_FAILURE(rc))
873 return rc;
874
875 unsigned cSegsToSend = 0;
876 rc = VERR_NO_TMP_MEMORY;
877#ifdef RT_OS_WINDOWS
878 LPWSABUF paMsg = NULL;
879
880 RTSgBufMapToNative(paMsg, pSgBuf, WSABUF, buf, char *, len, u_long, cSegsToSend);
881 if (paMsg)
882 {
883 DWORD dwSent = 0;
884 int hrc = WSASend(pThis->hNative, paMsg, cSegsToSend, &dwSent,
885 MSG_NOSIGNAL, NULL, NULL);
886 if (!hrc)
887 rc = VINF_SUCCESS;
888 else
889 rc = rtSocketError();
890
891 *pcbWritten = dwSent;
892
893 RTMemTmpFree(paMsg);
894 }
895
896#else /* !RT_OS_WINDOWS */
897 struct iovec *paMsg = NULL;
898
899 RTSgBufMapToNative(paMsg, pSgBuf, struct iovec, iov_base, void *, iov_len, size_t, cSegsToSend);
900 if (paMsg)
901 {
902 struct msghdr msgHdr;
903 RT_ZERO(msgHdr);
904 msgHdr.msg_iov = paMsg;
905 msgHdr.msg_iovlen = cSegsToSend;
906 ssize_t cbWritten = sendmsg(pThis->hNative, &msgHdr, MSG_NOSIGNAL);
907 if (RT_LIKELY(cbWritten >= 0))
908 {
909 rc = VINF_SUCCESS;
910 *pcbWritten = cbWritten;
911 }
912 else
913 rc = rtSocketError();
914
915 RTMemTmpFree(paMsg);
916 }
917#endif /* !RT_OS_WINDOWS */
918
919 rtSocketUnlock(pThis);
920 return rc;
921}
922
923
924RTDECL(int) RTSocketSgWriteLNB(RTSOCKET hSocket, size_t cSegs, size_t *pcbWritten, ...)
925{
926 va_list va;
927 va_start(va, pcbWritten);
928 int rc = RTSocketSgWriteLVNB(hSocket, cSegs, pcbWritten, va);
929 va_end(va);
930 return rc;
931}
932
933
934RTDECL(int) RTSocketSgWriteLVNB(RTSOCKET hSocket, size_t cSegs, size_t *pcbWritten, va_list va)
935{
936 /*
937 * Set up a S/G segment array + buffer on the stack and pass it
938 * on to RTSocketSgWrite.
939 */
940 Assert(cSegs <= 16);
941 PRTSGSEG paSegs = (PRTSGSEG)alloca(cSegs * sizeof(RTSGSEG));
942 AssertReturn(paSegs, VERR_NO_TMP_MEMORY);
943 for (size_t i = 0; i < cSegs; i++)
944 {
945 paSegs[i].pvSeg = va_arg(va, void *);
946 paSegs[i].cbSeg = va_arg(va, size_t);
947 }
948
949 RTSGBUF SgBuf;
950 RTSgBufInit(&SgBuf, paSegs, cSegs);
951 return RTSocketSgWriteNB(hSocket, &SgBuf, pcbWritten);
952}
953
954
955RTDECL(int) RTSocketSelectOne(RTSOCKET hSocket, RTMSINTERVAL cMillies)
956{
957 /*
958 * Validate input.
959 */
960 RTSOCKETINT *pThis = hSocket;
961 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
962 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
963 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
964
965 /*
966 * Set up the file descriptor sets and do the select.
967 */
968 fd_set fdsetR;
969 FD_ZERO(&fdsetR);
970 FD_SET(pThis->hNative, &fdsetR);
971
972 fd_set fdsetE = fdsetR;
973
974 int rc;
975 if (cMillies == RT_INDEFINITE_WAIT)
976 rc = select(pThis->hNative + 1, &fdsetR, NULL, &fdsetE, NULL);
977 else
978 {
979 struct timeval timeout;
980 timeout.tv_sec = cMillies / 1000;
981 timeout.tv_usec = (cMillies % 1000) * 1000;
982 rc = select(pThis->hNative + 1, &fdsetR, NULL, &fdsetE, &timeout);
983 }
984 if (rc > 0)
985 rc = VINF_SUCCESS;
986 else if (rc == 0)
987 rc = VERR_TIMEOUT;
988 else
989 rc = rtSocketError();
990
991 return rc;
992}
993
994
995RTDECL(int) RTSocketShutdown(RTSOCKET hSocket, bool fRead, bool fWrite)
996{
997 /*
998 * Validate input, don't lock it because we might want to interrupt a call
999 * active on a different thread.
1000 */
1001 RTSOCKETINT *pThis = hSocket;
1002 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1003 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1004 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
1005 AssertReturn(fRead || fWrite, VERR_INVALID_PARAMETER);
1006
1007 /*
1008 * Do the job.
1009 */
1010 int rc = VINF_SUCCESS;
1011 int fHow;
1012 if (fRead && fWrite)
1013 fHow = SHUT_RDWR;
1014 else if (fRead)
1015 fHow = SHUT_RD;
1016 else
1017 fHow = SHUT_WR;
1018 if (shutdown(pThis->hNative, fHow) == -1)
1019 rc = rtSocketError();
1020
1021 return rc;
1022}
1023
1024
1025/**
1026 * Converts from a native socket address to a generic IPRT network address.
1027 *
1028 * @returns IPRT status code.
1029 * @param pSrc The source address.
1030 * @param cbSrc The size of the source address.
1031 * @param pAddr Where to return the generic IPRT network
1032 * address.
1033 */
1034static int rtSocketConvertAddress(RTSOCKADDRUNION const *pSrc, size_t cbSrc, PRTNETADDR pAddr)
1035{
1036 /*
1037 * Convert the address.
1038 */
1039 if ( cbSrc == sizeof(struct sockaddr_in)
1040 && pSrc->Addr.sa_family == AF_INET)
1041 {
1042 RT_ZERO(*pAddr);
1043 pAddr->enmType = RTNETADDRTYPE_IPV4;
1044 pAddr->uPort = RT_N2H_U16(pSrc->Ipv4.sin_port);
1045 pAddr->uAddr.IPv4.u = pSrc->Ipv4.sin_addr.s_addr;
1046 }
1047#ifdef IPRT_WITH_TCPIP_V6
1048 else if ( cbSrc == sizeof(struct sockaddr_in6)
1049 && pSrc->Addr.sa_family == AF_INET6)
1050 {
1051 RT_ZERO(*pAddr);
1052 pAddr->enmType = RTNETADDRTYPE_IPV6;
1053 pAddr->uPort = RT_N2H_U16(pSrc->Ipv6.sin6_port);
1054 pAddr->uAddr.IPv6.au32[0] = pSrc->Ipv6.sin6_addr.s6_addr32[0];
1055 pAddr->uAddr.IPv6.au32[1] = pSrc->Ipv6.sin6_addr.s6_addr32[1];
1056 pAddr->uAddr.IPv6.au32[2] = pSrc->Ipv6.sin6_addr.s6_addr32[2];
1057 pAddr->uAddr.IPv6.au32[3] = pSrc->Ipv6.sin6_addr.s6_addr32[3];
1058 }
1059#endif
1060 else
1061 return VERR_NET_ADDRESS_FAMILY_NOT_SUPPORTED;
1062 return VINF_SUCCESS;
1063}
1064
1065
1066RTDECL(int) RTSocketGetLocalAddress(RTSOCKET hSocket, PRTNETADDR pAddr)
1067{
1068 /*
1069 * Validate input.
1070 */
1071 RTSOCKETINT *pThis = hSocket;
1072 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1073 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1074 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
1075
1076 /*
1077 * Get the address and convert it.
1078 */
1079 int rc;
1080 RTSOCKADDRUNION u;
1081#ifdef RT_OS_WINDOWS
1082 int cbAddr = sizeof(u);
1083#else
1084 socklen_t cbAddr = sizeof(u);
1085#endif
1086 RT_ZERO(u);
1087 if (getsockname(pThis->hNative, &u.Addr, &cbAddr) == 0)
1088 rc = rtSocketConvertAddress(&u, cbAddr, pAddr);
1089 else
1090 rc = rtSocketError();
1091
1092 return rc;
1093}
1094
1095
1096RTDECL(int) RTSocketGetPeerAddress(RTSOCKET hSocket, PRTNETADDR pAddr)
1097{
1098 /*
1099 * Validate input.
1100 */
1101 RTSOCKETINT *pThis = hSocket;
1102 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1103 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1104 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
1105
1106 /*
1107 * Get the address and convert it.
1108 */
1109 int rc;
1110 RTSOCKADDRUNION u;
1111#ifdef RT_OS_WINDOWS
1112 int cbAddr = sizeof(u);
1113#else
1114 socklen_t cbAddr = sizeof(u);
1115#endif
1116 RT_ZERO(u);
1117 if (getpeername(pThis->hNative, &u.Addr, &cbAddr) == 0)
1118 rc = rtSocketConvertAddress(&u, cbAddr, pAddr);
1119 else
1120 rc = rtSocketError();
1121
1122 return rc;
1123}
1124
1125
1126
1127/**
1128 * Wrapper around bind.
1129 *
1130 * @returns IPRT status code.
1131 * @param hSocket The socket handle.
1132 * @param pAddr The socket address to bind to.
1133 * @param cbAddr The size of the address structure @a pAddr
1134 * points to.
1135 */
1136int rtSocketBind(RTSOCKET hSocket, const struct sockaddr *pAddr, int cbAddr)
1137{
1138 /*
1139 * Validate input.
1140 */
1141 RTSOCKETINT *pThis = hSocket;
1142 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1143 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1144 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1145
1146 int rc = VINF_SUCCESS;
1147 if (bind(pThis->hNative, pAddr, cbAddr) != 0)
1148 rc = rtSocketError();
1149
1150 rtSocketUnlock(pThis);
1151 return rc;
1152}
1153
1154
1155/**
1156 * Wrapper around listen.
1157 *
1158 * @returns IPRT status code.
1159 * @param hSocket The socket handle.
1160 * @param cMaxPending The max number of pending connections.
1161 */
1162int rtSocketListen(RTSOCKET hSocket, int cMaxPending)
1163{
1164 /*
1165 * Validate input.
1166 */
1167 RTSOCKETINT *pThis = hSocket;
1168 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1169 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1170 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1171
1172 int rc = VINF_SUCCESS;
1173 if (listen(pThis->hNative, cMaxPending) != 0)
1174 rc = rtSocketError();
1175
1176 rtSocketUnlock(pThis);
1177 return rc;
1178}
1179
1180
1181/**
1182 * Wrapper around accept.
1183 *
1184 * @returns IPRT status code.
1185 * @param hSocket The socket handle.
1186 * @param phClient Where to return the client socket handle on
1187 * success.
1188 * @param pAddr Where to return the client address.
1189 * @param pcbAddr On input this gives the size buffer size of what
1190 * @a pAddr point to. On return this contains the
1191 * size of what's stored at @a pAddr.
1192 */
1193int rtSocketAccept(RTSOCKET hSocket, PRTSOCKET phClient, struct sockaddr *pAddr, size_t *pcbAddr)
1194{
1195 /*
1196 * Validate input.
1197 * Only lock the socket temporarily while we get the native handle, so that
1198 * we can safely shutdown and destroy the socket from a different thread.
1199 */
1200 RTSOCKETINT *pThis = hSocket;
1201 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1202 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1203 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1204
1205 /*
1206 * Call accept().
1207 */
1208 rtSocketErrorReset();
1209 int rc = VINF_SUCCESS;
1210#ifdef RT_OS_WINDOWS
1211 int cbAddr = (int)*pcbAddr;
1212#else
1213 socklen_t cbAddr = *pcbAddr;
1214#endif
1215 RTSOCKETNATIVE hNativeClient = accept(pThis->hNative, pAddr, &cbAddr);
1216 if (hNativeClient != NIL_RTSOCKETNATIVE)
1217 {
1218 *pcbAddr = cbAddr;
1219
1220 /*
1221 * Wrap the client socket.
1222 */
1223 rc = rtSocketCreateForNative(phClient, hNativeClient);
1224 if (RT_FAILURE(rc))
1225 {
1226#ifdef RT_OS_WINDOWS
1227 closesocket(hNativeClient);
1228#else
1229 close(hNativeClient);
1230#endif
1231 }
1232 }
1233 else
1234 rc = rtSocketError();
1235
1236 rtSocketUnlock(pThis);
1237 return rc;
1238}
1239
1240
1241/**
1242 * Wrapper around connect.
1243 *
1244 * @returns IPRT status code.
1245 * @param hSocket The socket handle.
1246 * @param pAddr The socket address to connect to.
1247 * @param cbAddr The size of the address structure @a pAddr
1248 * points to.
1249 */
1250int rtSocketConnect(RTSOCKET hSocket, const struct sockaddr *pAddr, int cbAddr)
1251{
1252 /*
1253 * Validate input.
1254 */
1255 RTSOCKETINT *pThis = hSocket;
1256 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1257 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1258 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1259
1260 int rc = VINF_SUCCESS;
1261 if (connect(pThis->hNative, pAddr, cbAddr) != 0)
1262 rc = rtSocketError();
1263
1264 rtSocketUnlock(pThis);
1265 return rc;
1266}
1267
1268
1269/**
1270 * Wrapper around setsockopt.
1271 *
1272 * @returns IPRT status code.
1273 * @param hSocket The socket handle.
1274 * @param iLevel The protocol level, e.g. IPPORTO_TCP.
1275 * @param iOption The option, e.g. TCP_NODELAY.
1276 * @param pvValue The value buffer.
1277 * @param cbValue The size of the value pointed to by pvValue.
1278 */
1279int rtSocketSetOpt(RTSOCKET hSocket, int iLevel, int iOption, void const *pvValue, int cbValue)
1280{
1281 /*
1282 * Validate input.
1283 */
1284 RTSOCKETINT *pThis = hSocket;
1285 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1286 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1287 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1288
1289 int rc = VINF_SUCCESS;
1290 if (setsockopt(pThis->hNative, iLevel, iOption, (const char *)pvValue, cbValue) != 0)
1291 rc = rtSocketError();
1292
1293 rtSocketUnlock(pThis);
1294 return rc;
1295}
1296
1297#ifdef RT_OS_WINDOWS
1298
1299/**
1300 * Internal RTPollSetAdd helper that returns the handle that should be added to
1301 * the pollset.
1302 *
1303 * @returns Valid handle on success, INVALID_HANDLE_VALUE on failure.
1304 * @param hSocket The socket handle.
1305 * @param fEvents The events we're polling for.
1306 * @param ph wher to put the primary handle.
1307 */
1308int rtSocketPollGetHandle(RTSOCKET hSocket, uint32_t fEvents, PHANDLE ph)
1309{
1310 RTSOCKETINT *pThis = hSocket;
1311 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1312 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1313 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1314
1315 int rc = VINF_SUCCESS;
1316 if (pThis->hEvent != WSA_INVALID_EVENT)
1317 *ph = pThis->hEvent;
1318 else
1319 {
1320 *ph = pThis->hEvent = WSACreateEvent();
1321 if (pThis->hEvent == WSA_INVALID_EVENT)
1322 rc = rtSocketError();
1323 }
1324
1325 rtSocketUnlock(pThis);
1326 return rc;
1327}
1328
1329
1330/**
1331 * Undos the harm done by WSAEventSelect.
1332 *
1333 * @returns IPRT status code.
1334 * @param pThis The socket handle.
1335 */
1336static int rtSocketPollClearEventAndRestoreBlocking(RTSOCKETINT *pThis)
1337{
1338 int rc = VINF_SUCCESS;
1339 if (pThis->fSubscribedEvts)
1340 {
1341 if (WSAEventSelect(pThis->hNative, WSA_INVALID_EVENT, 0) == 0)
1342 {
1343 pThis->fSubscribedEvts = 0;
1344
1345 /*
1346 * Switch back to blocking mode if that was the state before the
1347 * operation.
1348 */
1349 if (pThis->fBlocking)
1350 {
1351 u_long fNonBlocking = 0;
1352 int rc2 = ioctlsocket(pThis->hNative, FIONBIO, &fNonBlocking);
1353 if (rc2 != 0)
1354 {
1355 rc = rtSocketError();
1356 AssertMsgFailed(("%Rrc; rc2=%d\n", rc, rc2));
1357 }
1358 }
1359 }
1360 else
1361 {
1362 rc = rtSocketError();
1363 AssertMsgFailed(("%Rrc\n", rc));
1364 }
1365 }
1366 return rc;
1367}
1368
1369
1370/**
1371 * Updates the mask of events we're subscribing to.
1372 *
1373 * @returns IPRT status code.
1374 * @param pThis The socket handle.
1375 * @param fEvents The events we want to subscribe to.
1376 */
1377static int rtSocketPollUpdateEvents(RTSOCKETINT *pThis, uint32_t fEvents)
1378{
1379 LONG fNetworkEvents = 0;
1380 if (fEvents & RTPOLL_EVT_READ)
1381 fNetworkEvents |= FD_READ;
1382 if (fEvents & RTPOLL_EVT_WRITE)
1383 fNetworkEvents |= FD_WRITE;
1384 if (fEvents & RTPOLL_EVT_ERROR)
1385 fNetworkEvents |= FD_CLOSE;
1386 if (WSAEventSelect(pThis->hNative, pThis->hEvent, fNetworkEvents) == 0)
1387 {
1388 pThis->fSubscribedEvts = fEvents;
1389 return VINF_SUCCESS;
1390 }
1391
1392 int rc = rtSocketError();
1393 AssertMsgFailed(("fNetworkEvents=%#x rc=%Rrc\n", fNetworkEvents, rtSocketError()));
1394 return rc;
1395}
1396
1397
1398/**
1399 * Checks for pending events.
1400 *
1401 * @returns Event mask or 0.
1402 * @param pThis The socket handle.
1403 * @param fEvents The desired events.
1404 */
1405static uint32_t rtSocketPollCheck(RTSOCKETINT *pThis, uint32_t fEvents)
1406{
1407 int rc = VINF_SUCCESS;
1408 uint32_t fRetEvents = 0;
1409
1410 /* Make sure WSAEnumNetworkEvents returns what we want. */
1411 if ((pThis->fSubscribedEvts & fEvents) != fEvents)
1412 rc = rtSocketPollUpdateEvents(pThis, pThis->fSubscribedEvts | fEvents);
1413
1414 /* Get the event mask, ASSUMES that WSAEnumNetworkEvents doesn't clear stuff. */
1415 WSANETWORKEVENTS NetEvts;
1416 RT_ZERO(NetEvts);
1417 if (WSAEnumNetworkEvents(pThis->hNative, pThis->hEvent, &NetEvts) == 0)
1418 {
1419 if ( (NetEvts.lNetworkEvents & FD_READ)
1420 && (fEvents & RTPOLL_EVT_READ)
1421 && NetEvts.iErrorCode[FD_READ_BIT] == 0)
1422 fRetEvents |= RTPOLL_EVT_READ;
1423
1424 if ( (NetEvts.lNetworkEvents & FD_WRITE)
1425 && (fEvents & RTPOLL_EVT_WRITE)
1426 && NetEvts.iErrorCode[FD_WRITE_BIT] == 0)
1427 fRetEvents |= RTPOLL_EVT_WRITE;
1428
1429 if (fEvents & RTPOLL_EVT_ERROR)
1430 {
1431 if (NetEvts.lNetworkEvents & FD_CLOSE)
1432 fRetEvents |= RTPOLL_EVT_ERROR;
1433 else
1434 for (uint32_t i = 0; i < FD_MAX_EVENTS; i++)
1435 if ( (NetEvts.lNetworkEvents & (1L << i))
1436 && NetEvts.iErrorCode[i] != 0)
1437 fRetEvents |= RTPOLL_EVT_ERROR;
1438 }
1439 }
1440 else
1441 rc = rtSocketError();
1442
1443 /* Fall back on select if we hit an error above. */
1444 if (RT_FAILURE(rc))
1445 {
1446 /** @todo */
1447 }
1448
1449 return fRetEvents;
1450}
1451
1452
1453/**
1454 * Internal RTPoll helper that polls the socket handle and, if @a fNoWait is
1455 * clear, starts whatever actions we've got running during the poll call.
1456 *
1457 * @returns 0 if no pending events, actions initiated if @a fNoWait is clear.
1458 * Event mask (in @a fEvents) and no actions if the handle is ready
1459 * already.
1460 * UINT32_MAX (asserted) if the socket handle is busy in I/O or a
1461 * different poll set.
1462 *
1463 * @param hSocket The socket handle.
1464 * @param hPollSet The poll set handle (for access checks).
1465 * @param fEvents The events we're polling for.
1466 * @param fFinalEntry Set if this is the final entry for this handle
1467 * in this poll set. This can be used for dealing
1468 * with duplicate entries.
1469 * @param fNoWait Set if it's a zero-wait poll call. Clear if
1470 * we'll wait for an event to occur.
1471 *
1472 * @remarks There is a potential race wrt duplicate handles when @a fNoWait is
1473 * @c true, we don't currently care about that oddity...
1474 */
1475uint32_t rtSocketPollStart(RTSOCKET hSocket, RTPOLLSET hPollSet, uint32_t fEvents, bool fFinalEntry, bool fNoWait)
1476{
1477 RTSOCKETINT *pThis = hSocket;
1478 AssertPtrReturn(pThis, UINT32_MAX);
1479 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, UINT32_MAX);
1480 if (rtSocketTryLock(pThis))
1481 pThis->hPollSet = hPollSet;
1482 else
1483 {
1484 AssertReturn(pThis->hPollSet == hPollSet, UINT32_MAX);
1485 ASMAtomicIncU32(&pThis->cUsers);
1486 }
1487
1488 /* (rtSocketPollCheck will reset the event object). */
1489 uint32_t fRetEvents = rtSocketPollCheck(pThis, fEvents);
1490 if ( !fRetEvents
1491 && !fNoWait)
1492 {
1493 pThis->fPollEvts |= fEvents;
1494 if ( fFinalEntry
1495 && pThis->fSubscribedEvts != pThis->fPollEvts)
1496 {
1497 int rc = rtSocketPollUpdateEvents(pThis, pThis->fPollEvts);
1498 if (RT_FAILURE(rc))
1499 {
1500 pThis->fPollEvts = 0;
1501 fRetEvents = UINT32_MAX;
1502 }
1503 }
1504 }
1505
1506 if (fRetEvents || fNoWait)
1507 {
1508 if (pThis->cUsers == 1)
1509 {
1510 rtSocketPollClearEventAndRestoreBlocking(pThis);
1511 pThis->hPollSet = NIL_RTPOLLSET;
1512 }
1513 ASMAtomicDecU32(&pThis->cUsers);
1514 }
1515
1516 return fRetEvents;
1517}
1518
1519
1520/**
1521 * Called after a WaitForMultipleObjects returned in order to check for pending
1522 * events and stop whatever actions that rtSocketPollStart() initiated.
1523 *
1524 * @returns Event mask or 0.
1525 *
1526 * @param hSocket The socket handle.
1527 * @param fEvents The events we're polling for.
1528 * @param fFinalEntry Set if this is the final entry for this handle
1529 * in this poll set. This can be used for dealing
1530 * with duplicate entries. Only keep in mind that
1531 * this method is called in reverse order, so the
1532 * first call will have this set (when the entire
1533 * set was processed).
1534 */
1535uint32_t rtSocketPollDone(RTSOCKET hSocket, uint32_t fEvents, bool fFinalEntry)
1536{
1537 RTSOCKETINT *pThis = hSocket;
1538 AssertPtrReturn(pThis, 0);
1539 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, 0);
1540 Assert(pThis->cUsers > 0);
1541 Assert(pThis->hPollSet != NIL_RTPOLLSET);
1542
1543 /* Harvest events and clear the event mask for the next round of polling. */
1544 uint32_t fRetEvents = rtSocketPollCheck(pThis, fEvents);
1545 pThis->fPollEvts = 0;
1546
1547 /* Make the socket blocking again and unlock the handle. */
1548 if (pThis->cUsers == 1)
1549 {
1550 rtSocketPollClearEventAndRestoreBlocking(pThis);
1551 pThis->hPollSet = NIL_RTPOLLSET;
1552 }
1553 ASMAtomicDecU32(&pThis->cUsers);
1554 return fRetEvents;
1555}
1556
1557#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