VirtualBox

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

Last change on this file since 32315 was 32276, checked in by vboxsync, 14 years ago

IPRT/Socket: Add extended select API where the events to wait for can be provided

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