VirtualBox

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

Last change on this file since 32439 was 32320, checked in by vboxsync, 14 years ago

oops

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