VirtualBox

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

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

Fix windows burn

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