VirtualBox

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

Last change on this file since 31768 was 31585, checked in by vboxsync, 14 years ago

Another one

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

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