VirtualBox

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

Last change on this file since 30746 was 30468, checked in by vboxsync, 14 years ago

IPRT:

  • Corrected RTSGBUF member names.
  • Corrected RTSgBufInit parameter names.
  • Don't use AssertReturnVoid (and variations) in RTSgBuf* as there the result is that we use uninitialized structures. Better to crash and burn in IPRT then.
  • Added RTSocketSgWriteL/LV and RTTcpSgWriteL/LV for lazy guys like me.
  • RTSocketSgWrite doesn't need a do {} while (0).
  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 36.3 KB
Line 
1/* $Id: socket.cpp 30468 2010-06-28 13:58:04Z vboxsync $ */
2/** @file
3 * IPRT - Network Sockets.
4 */
5
6/*
7 * Copyright (C) 2006-2010 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 */
26
27
28/*******************************************************************************
29* Header Files *
30*******************************************************************************/
31#ifdef RT_OS_WINDOWS
32# include <winsock2.h>
33#else /* !RT_OS_WINDOWS */
34# include <errno.h>
35# include <sys/stat.h>
36# include <sys/socket.h>
37# include <netinet/in.h>
38# include <netinet/tcp.h>
39# include <arpa/inet.h>
40# ifdef IPRT_WITH_TCPIP_V6
41# include <netinet6/in6.h>
42# endif
43# include <sys/un.h>
44# include <netdb.h>
45# include <unistd.h>
46# include <fcntl.h>
47# include <sys/uio.h>
48#endif /* !RT_OS_WINDOWS */
49#include <limits.h>
50
51#include "internal/iprt.h"
52#include <iprt/socket.h>
53
54#include <iprt/alloca.h>
55#include <iprt/asm.h>
56#include <iprt/assert.h>
57#include <iprt/err.h>
58#include <iprt/mempool.h>
59#include <iprt/poll.h>
60#include <iprt/string.h>
61#include <iprt/thread.h>
62#include <iprt/time.h>
63#include <iprt/mem.h>
64#include <iprt/sg.h>
65
66#include "internal/magics.h"
67#include "internal/socket.h"
68
69
70/*******************************************************************************
71* Defined Constants And Macros *
72*******************************************************************************/
73/* non-standard linux stuff (it seems). */
74#ifndef MSG_NOSIGNAL
75# define MSG_NOSIGNAL 0
76#endif
77
78/* Windows has different names for SHUT_XXX. */
79#ifndef SHUT_RDWR
80# ifdef SD_BOTH
81# define SHUT_RDWR SD_BOTH
82# else
83# define SHUT_RDWR 2
84# endif
85#endif
86#ifndef SHUT_WR
87# ifdef SD_SEND
88# define SHUT_WR SD_SEND
89# else
90# define SHUT_WR 1
91# endif
92#endif
93#ifndef SHUT_RD
94# ifdef SD_RECEIVE
95# define SHUT_RD SD_RECEIVE
96# else
97# define SHUT_RD 0
98# endif
99#endif
100
101/* fixup backlevel OSes. */
102#if defined(RT_OS_OS2) || defined(RT_OS_WINDOWS)
103# define socklen_t int
104#endif
105
106/** How many pending connection. */
107#define RTTCP_SERVER_BACKLOG 10
108
109
110/*******************************************************************************
111* Structures and Typedefs *
112*******************************************************************************/
113/**
114 * Socket handle data.
115 *
116 * This is mainly required for implementing RTPollSet on Windows.
117 */
118typedef struct RTSOCKETINT
119{
120 /** Magic number (RTSOCKET_MAGIC). */
121 uint32_t u32Magic;
122 /** Exclusive user count.
123 * This is used to prevent two threads from accessing the handle concurrently.
124 * It can be higher than 1 if this handle is reference multiple times in a
125 * polling set (Windows). */
126 uint32_t volatile cUsers;
127 /** The native socket handle. */
128 RTSOCKETNATIVE hNative;
129 /** Indicates whether the handle has been closed or not. */
130 bool volatile fClosed;
131#ifdef RT_OS_WINDOWS
132 /** The event semaphore we've associated with the socket handle.
133 * This is WSA_INVALID_EVENT if not done. */
134 WSAEVENT hEvent;
135 /** The pollset currently polling this socket. This is NIL if no one is
136 * polling. */
137 RTPOLLSET hPollSet;
138 /** The events we're polling for. */
139 uint32_t fPollEvts;
140 /** The events we're currently subscribing to with WSAEventSelect.
141 * This is ZERO if we're currently not subscribing to anything. */
142 uint32_t fSubscribedEvts;
143#endif /* RT_OS_WINDOWS */
144} RTSOCKETINT;
145
146
147/**
148 * Address union used internally for things like getpeername and getsockname.
149 */
150typedef union RTSOCKADDRUNION
151{
152 struct sockaddr Addr;
153 struct sockaddr_in Ipv4;
154#ifdef IPRT_WITH_TCPIP_V6
155 struct sockaddr_in6 Ipv6;
156#endif
157} RTSOCKADDRUNION;
158
159
160/**
161 * Get the last error as an iprt status code.
162 *
163 * @returns IPRT status code.
164 */
165DECLINLINE(int) rtSocketError(void)
166{
167#ifdef RT_OS_WINDOWS
168 return RTErrConvertFromWin32(WSAGetLastError());
169#else
170 return RTErrConvertFromErrno(errno);
171#endif
172}
173
174
175/**
176 * Resets the last error.
177 */
178DECLINLINE(void) rtSocketErrorReset(void)
179{
180#ifdef RT_OS_WINDOWS
181 WSASetLastError(0);
182#else
183 errno = 0;
184#endif
185}
186
187
188/**
189 * Get the last resolver error as an iprt status code.
190 *
191 * @returns iprt status code.
192 */
193int rtSocketResolverError(void)
194{
195#ifdef RT_OS_WINDOWS
196 return RTErrConvertFromWin32(WSAGetLastError());
197#else
198 switch (h_errno)
199 {
200 case HOST_NOT_FOUND:
201 return VERR_NET_HOST_NOT_FOUND;
202 case NO_DATA:
203 return VERR_NET_ADDRESS_NOT_AVAILABLE;
204 case NO_RECOVERY:
205 return VERR_IO_GEN_FAILURE;
206 case TRY_AGAIN:
207 return VERR_TRY_AGAIN;
208
209 default:
210 return VERR_UNRESOLVED_ERROR;
211 }
212#endif
213}
214
215
216/**
217 * Tries to lock the socket for exclusive usage by the calling thread.
218 *
219 * Call rtSocketUnlock() to unlock.
220 *
221 * @returns @c true if locked, @c false if not.
222 * @param pThis The socket structure.
223 */
224DECLINLINE(bool) rtSocketTryLock(RTSOCKETINT *pThis)
225{
226 return ASMAtomicCmpXchgU32(&pThis->cUsers, 1, 0);
227}
228
229
230/**
231 * Unlocks the socket.
232 *
233 * @param pThis The socket structure.
234 */
235DECLINLINE(void) rtSocketUnlock(RTSOCKETINT *pThis)
236{
237 ASMAtomicCmpXchgU32(&pThis->cUsers, 0, 1);
238}
239
240
241/**
242 * Creates an IPRT socket handle for a native one.
243 *
244 * @returns IPRT status code.
245 * @param ppSocket Where to return the IPRT socket handle.
246 * @param hNative The native handle.
247 */
248int rtSocketCreateForNative(RTSOCKETINT **ppSocket, RTSOCKETNATIVE hNative)
249{
250 RTSOCKETINT *pThis = (RTSOCKETINT *)RTMemPoolAlloc(RTMEMPOOL_DEFAULT, sizeof(*pThis));
251 if (!pThis)
252 return VERR_NO_MEMORY;
253 pThis->u32Magic = RTSOCKET_MAGIC;
254 pThis->cUsers = 0;
255 pThis->hNative = hNative;
256 pThis->fClosed = false;
257#ifdef RT_OS_WINDOWS
258 pThis->hEvent = WSA_INVALID_EVENT;
259 pThis->hPollSet = NIL_RTPOLLSET;
260 pThis->fPollEvts = 0;
261 pThis->fSubscribedEvts = 0;
262#endif
263 *ppSocket = pThis;
264 return VINF_SUCCESS;
265}
266
267
268RTDECL(int) RTSocketFromNative(PRTSOCKET phSocket, RTHCINTPTR uNative)
269{
270 AssertReturn(uNative != NIL_RTSOCKETNATIVE, VERR_INVALID_PARAMETER);
271#ifndef RT_OS_WINDOWS
272 AssertReturn(uNative >= 0, VERR_INVALID_PARAMETER);
273#endif
274 AssertPtrReturn(phSocket, VERR_INVALID_POINTER);
275 return rtSocketCreateForNative(phSocket, uNative);
276}
277
278
279/**
280 * Wrapper around socket().
281 *
282 * @returns IPRT status code.
283 * @param phSocket Where to store the handle to the socket on
284 * success.
285 * @param iDomain The protocol family (PF_XXX).
286 * @param iType The socket type (SOCK_XXX).
287 * @param iProtocol Socket parameter, usually 0.
288 */
289int rtSocketCreate(PRTSOCKET phSocket, int iDomain, int iType, int iProtocol)
290{
291 /*
292 * Create the socket.
293 */
294 RTSOCKETNATIVE hNative = socket(iDomain, iType, iProtocol);
295 if (hNative == NIL_RTSOCKETNATIVE)
296 return rtSocketError();
297
298 /*
299 * Wrap it.
300 */
301 int rc = rtSocketCreateForNative(phSocket, hNative);
302 if (RT_FAILURE(rc))
303 {
304#ifdef RT_OS_WINDOWS
305 closesocket(hNative);
306#else
307 close(hNative);
308#endif
309 }
310 return rc;
311}
312
313
314RTDECL(uint32_t) RTSocketRetain(RTSOCKET hSocket)
315{
316 RTSOCKETINT *pThis = hSocket;
317 AssertPtrReturn(pThis, UINT32_MAX);
318 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, UINT32_MAX);
319 return RTMemPoolRetain(pThis);
320}
321
322
323/**
324 * Worker for RTSocketRelease and RTSocketClose.
325 *
326 * @returns IPRT status code.
327 * @param pThis The socket handle instance data.
328 * @param fDestroy Whether we're reaching ref count zero.
329 */
330static int rtSocketCloseIt(RTSOCKETINT *pThis, bool fDestroy)
331{
332 /*
333 * Invalidate the handle structure on destroy.
334 */
335 if (fDestroy)
336 {
337 Assert(ASMAtomicReadU32(&pThis->u32Magic) == RTSOCKET_MAGIC);
338 ASMAtomicWriteU32(&pThis->u32Magic, RTSOCKET_MAGIC_DEAD);
339 }
340
341 int rc = VINF_SUCCESS;
342 if (ASMAtomicCmpXchgBool(&pThis->fClosed, true, false))
343 {
344 /*
345 * Close the native handle.
346 */
347 RTSOCKETNATIVE hNative = pThis->hNative;
348 if (hNative != NIL_RTSOCKETNATIVE)
349 {
350 pThis->hNative = NIL_RTSOCKETNATIVE;
351
352#ifdef RT_OS_WINDOWS
353 if (closesocket(hNative))
354#else
355 if (close(hNative))
356#endif
357 {
358 rc = rtSocketError();
359#ifdef RT_OS_WINDOWS
360 AssertMsgFailed(("\"%s\": closesocket(%p) -> %Rrc\n", (uintptr_t)hNative, rc));
361#else
362 AssertMsgFailed(("\"%s\": close(%d) -> %Rrc\n", hNative, rc));
363#endif
364 }
365 }
366
367#ifdef RT_OS_WINDOWS
368 /*
369 * Close the event.
370 */
371 WSAEVENT hEvent = pThis->hEvent;
372 if (hEvent == WSA_INVALID_EVENT)
373 {
374 pThis->hEvent = WSA_INVALID_EVENT;
375 WSACloseEvent(hEvent);
376 }
377#endif
378 }
379
380 return rc;
381}
382
383
384RTDECL(uint32_t) RTSocketRelease(RTSOCKET hSocket)
385{
386 RTSOCKETINT *pThis = hSocket;
387 if (pThis == NIL_RTSOCKET)
388 return 0;
389 AssertPtrReturn(pThis, UINT32_MAX);
390 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, UINT32_MAX);
391
392 /* get the refcount without killing it... */
393 uint32_t cRefs = RTMemPoolRefCount(pThis);
394 AssertReturn(cRefs != UINT32_MAX, UINT32_MAX);
395 if (cRefs == 1)
396 rtSocketCloseIt(pThis, true);
397
398 return RTMemPoolRelease(RTMEMPOOL_DEFAULT, pThis);
399}
400
401
402RTDECL(int) RTSocketClose(RTSOCKET hSocket)
403{
404 RTSOCKETINT *pThis = hSocket;
405 if (pThis == NIL_RTSOCKET)
406 return VINF_SUCCESS;
407 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
408 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
409
410 uint32_t cRefs = RTMemPoolRefCount(pThis);
411 AssertReturn(cRefs != UINT32_MAX, UINT32_MAX);
412
413 int rc = rtSocketCloseIt(pThis, cRefs == 1);
414
415 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pThis);
416 return rc;
417}
418
419
420RTDECL(RTHCUINTPTR) RTSocketToNative(RTSOCKET hSocket)
421{
422 RTSOCKETINT *pThis = hSocket;
423 AssertPtrReturn(pThis, RTHCUINTPTR_MAX);
424 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, RTHCUINTPTR_MAX);
425 return (RTHCUINTPTR)pThis->hNative;
426}
427
428
429RTDECL(int) RTSocketSetInheritance(RTSOCKET hSocket, bool fInheritable)
430{
431 RTSOCKETINT *pThis = hSocket;
432 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
433 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
434 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
435
436 int rc = VINF_SUCCESS;
437#ifdef RT_OS_WINDOWS
438 if (!SetHandleInformation((HANDLE)pThis->hNative, HANDLE_FLAG_INHERIT, fInheritable ? HANDLE_FLAG_INHERIT : 0))
439 rc = RTErrConvertFromWin32(GetLastError());
440#else
441 if (fcntl(pThis->hNative, F_SETFD, fInheritable ? 0 : FD_CLOEXEC) < 0)
442 rc = RTErrConvertFromErrno(errno);
443#endif
444
445 return rc;
446}
447
448
449RTDECL(int) RTSocketRead(RTSOCKET hSocket, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
450{
451 /*
452 * Validate input.
453 */
454 RTSOCKETINT *pThis = hSocket;
455 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
456 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
457 AssertReturn(cbBuffer > 0, VERR_INVALID_PARAMETER);
458 AssertPtr(pvBuffer);
459 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
460
461 /*
462 * Read loop.
463 * If pcbRead is NULL we have to fill the entire buffer!
464 */
465 int rc = VINF_SUCCESS;
466 size_t cbRead = 0;
467 size_t cbToRead = cbBuffer;
468 for (;;)
469 {
470 rtSocketErrorReset();
471#ifdef RT_OS_WINDOWS
472 int cbNow = cbToRead >= INT_MAX/2 ? INT_MAX/2 : (int)cbToRead;
473#else
474 size_t cbNow = cbToRead;
475#endif
476 ssize_t cbBytesRead = recv(pThis->hNative, (char *)pvBuffer + cbRead, cbNow, MSG_NOSIGNAL);
477 if (cbBytesRead <= 0)
478 {
479 rc = rtSocketError();
480 Assert(RT_FAILURE_NP(rc) || cbBytesRead == 0);
481 if (RT_SUCCESS_NP(rc))
482 {
483 if (!pcbRead)
484 rc = VERR_NET_SHUTDOWN;
485 else
486 {
487 *pcbRead = 0;
488 rc = VINF_SUCCESS;
489 }
490 }
491 break;
492 }
493 if (pcbRead)
494 {
495 /* return partial data */
496 *pcbRead = cbBytesRead;
497 break;
498 }
499
500 /* read more? */
501 cbRead += cbBytesRead;
502 if (cbRead == cbBuffer)
503 break;
504
505 /* next */
506 cbToRead = cbBuffer - cbRead;
507 }
508
509 rtSocketUnlock(pThis);
510 return rc;
511}
512
513
514RTDECL(int) RTSocketWrite(RTSOCKET hSocket, const void *pvBuffer, size_t cbBuffer)
515{
516 /*
517 * Validate input.
518 */
519 RTSOCKETINT *pThis = hSocket;
520 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
521 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
522 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
523
524 /*
525 * Try write all at once.
526 */
527 int rc = VINF_SUCCESS;
528#ifdef RT_OS_WINDOWS
529 int cbNow = cbBuffer >= INT_MAX / 2 ? INT_MAX / 2 : (int)cbBuffer;
530#else
531 size_t cbNow = cbBuffer >= SSIZE_MAX ? SSIZE_MAX : cbBuffer;
532#endif
533 ssize_t cbWritten = send(pThis->hNative, (const char *)pvBuffer, cbNow, MSG_NOSIGNAL);
534 if (RT_LIKELY((size_t)cbWritten == cbBuffer && cbWritten >= 0))
535 rc = VINF_SUCCESS;
536 else if (cbWritten < 0)
537 rc = rtSocketError();
538 else
539 {
540 /*
541 * Unfinished business, write the remainder of the request. Must ignore
542 * VERR_INTERRUPTED here if we've managed to send something.
543 */
544 size_t cbSentSoFar = 0;
545 for (;;)
546 {
547 /* advance */
548 cbBuffer -= (size_t)cbWritten;
549 if (!cbBuffer)
550 break;
551 cbSentSoFar += (size_t)cbWritten;
552 pvBuffer = (char const *)pvBuffer + cbWritten;
553
554 /* send */
555#ifdef RT_OS_WINDOWS
556 cbNow = cbBuffer >= INT_MAX / 2 ? INT_MAX / 2 : (int)cbBuffer;
557#else
558 cbNow = cbBuffer >= SSIZE_MAX ? SSIZE_MAX : cbBuffer;
559#endif
560 cbWritten = send(pThis->hNative, (const char *)pvBuffer, cbNow, MSG_NOSIGNAL);
561 if (cbWritten >= 0)
562 AssertMsg(cbBuffer >= (size_t)cbWritten, ("Wrote more than we requested!!! cbWritten=%zu cbBuffer=%zu rtSocketError()=%d\n",
563 cbWritten, cbBuffer, rtSocketError()));
564 else
565 {
566 rc = rtSocketError();
567 if (rc != VERR_INTERNAL_ERROR || cbSentSoFar == 0)
568 break;
569 cbWritten = 0;
570 rc = VINF_SUCCESS;
571 }
572 }
573 }
574
575 rtSocketUnlock(pThis);
576 return rc;
577}
578
579
580RTDECL(int) RTSocketSgWrite(RTSOCKET hSocket, PCRTSGBUF pSgBuf)
581{
582 /*
583 * Validate input.
584 */
585 RTSOCKETINT *pThis = hSocket;
586 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
587 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
588 AssertPtrReturn(pSgBuf, VERR_INVALID_PARAMETER);
589 AssertReturn(pSgBuf->cSegs > 0, VERR_INVALID_PARAMETER);
590 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
591
592 /*
593 * Construct message descriptor (translate pSgBuf) and send it.
594 */
595 int rc = VERR_NO_TMP_MEMORY;
596#ifdef RT_OS_WINDOWS
597 AssertCompileSize(WSABUF, sizeof(RTSGSEG));
598 AssertCompileMemberSize(WSABUF, buf, RT_SIZEOFMEMB(RTSGSEG, pvSeg));
599
600 LPWSABUF paMsg = (LPWSABUF)RTMemTmpAllocZ(pSgBuf->cSegs * sizeof(WSABUF));
601 if (paMsg)
602 {
603 for (unsigned i = 0; i < pSgBuf->cSegs; i++)
604 {
605 paMsg[i].buf = (char *)pSgBuf->paSegs[i].pvSeg;
606 paMsg[i].len = (u_long)pSgBuf->paSegs[i].cbSeg;
607 }
608
609 DWORD dwSent;
610 int hrc = WSASend(pThis->hNative, paMsg, pSgBuf->cSegs, &dwSent,
611 MSG_NOSIGNAL, NULL, NULL);
612 if (!hrc)
613 rc = VINF_SUCCESS;
614/** @todo check for incomplete writes */
615 else
616 rc = rtSocketError();
617
618 RTMemTmpFree(paMsg);
619 }
620
621#else /* !RT_OS_WINDOWS */
622 AssertCompileSize(struct iovec, sizeof(RTSGSEG));
623 AssertCompileMemberSize(struct iovec, iov_base, RT_SIZEOFMEMB(RTSGSEG, pvSeg));
624 AssertCompileMemberSize(struct iovec, iov_len, RT_SIZEOFMEMB(RTSGSEG, cbSeg));
625
626 struct iovec *paMsg = (struct iovec *)RTMemTmpAllocZ(pSgBuf->cSegs * sizeof(struct iovec));
627 if (paMsg)
628 {
629 for (unsigned i = 0; i < pSgBuf->cSegs; i++)
630 {
631 paMsg[i].iov_base = pSgBuf->paSegs[i].pvSeg;
632 paMsg[i].iov_len = pSgBuf->paSegs[i].cbSeg;
633 }
634
635 struct msghdr msgHdr;
636 RT_ZERO(msgHdr);
637 msgHdr.msg_iov = paMsg;
638 msgHdr.msg_iovlen = pSgBuf->cSegs;
639 ssize_t cbWritten = sendmsg(pThis->hNative, &msgHdr, MSG_NOSIGNAL);
640 if (RT_LIKELY(cbWritten >= 0))
641 rc = VINF_SUCCESS;
642/** @todo check for incomplete writes */
643 else
644 rc = rtSocketError();
645
646 RTMemTmpFree(paMsg);
647 }
648#endif /* !RT_OS_WINDOWS */
649
650 rtSocketUnlock(pThis);
651 return rc;
652}
653
654
655RTDECL(int) RTSocketSgWriteL(RTSOCKET hSocket, size_t cSegs, ...)
656{
657 va_list va;
658 va_start(va, cSegs);
659 int rc = RTSocketSgWriteLV(hSocket, cSegs, va);
660 va_end(va);
661 return rc;
662}
663
664
665RTDECL(int) RTSocketSgWriteLV(RTSOCKET hSocket, size_t cSegs, va_list va)
666{
667 /*
668 * Set up a S/G segment array + buffer on the stack and pass it
669 * on to RTSocketSgWrite.
670 */
671 Assert(cSegs <= 16);
672 PRTSGSEG paSegs = (PRTSGSEG)alloca(cSegs * sizeof(RTSGSEG));
673 AssertReturn(paSegs, VERR_NO_TMP_MEMORY);
674 for (size_t i = 0; i < cSegs; i++)
675 {
676 paSegs[i].pvSeg = va_arg(va, void *);
677 paSegs[i].cbSeg = va_arg(va, size_t);
678 }
679
680 RTSGBUF SgBuf;
681 RTSgBufInit(&SgBuf, paSegs, cSegs);
682 return RTSocketSgWrite(hSocket, &SgBuf);
683}
684
685
686RTDECL(int) RTSocketSelectOne(RTSOCKET hSocket, RTMSINTERVAL cMillies)
687{
688 /*
689 * Validate input.
690 */
691 RTSOCKETINT *pThis = hSocket;
692 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
693 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
694 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
695
696 /*
697 * Set up the file descriptor sets and do the select.
698 */
699 fd_set fdsetR;
700 FD_ZERO(&fdsetR);
701 FD_SET(pThis->hNative, &fdsetR);
702
703 fd_set fdsetE = fdsetR;
704
705 int rc;
706 if (cMillies == RT_INDEFINITE_WAIT)
707 rc = select(pThis->hNative + 1, &fdsetR, NULL, &fdsetE, NULL);
708 else
709 {
710 struct timeval timeout;
711 timeout.tv_sec = cMillies / 1000;
712 timeout.tv_usec = (cMillies % 1000) * 1000;
713 rc = select(pThis->hNative + 1, &fdsetR, NULL, &fdsetE, &timeout);
714 }
715 if (rc > 0)
716 rc = VINF_SUCCESS;
717 else if (rc == 0)
718 rc = VERR_TIMEOUT;
719 else
720 rc = rtSocketError();
721
722 return rc;
723}
724
725
726RTDECL(int) RTSocketShutdown(RTSOCKET hSocket, bool fRead, bool fWrite)
727{
728 /*
729 * Validate input, don't lock it because we might want to interrupt a call
730 * active on a different thread.
731 */
732 RTSOCKETINT *pThis = hSocket;
733 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
734 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
735 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
736 AssertReturn(fRead || fWrite, VERR_INVALID_PARAMETER);
737
738 /*
739 * Do the job.
740 */
741 int rc = VINF_SUCCESS;
742 int fHow;
743 if (fRead && fWrite)
744 fHow = SHUT_RDWR;
745 else if (fRead)
746 fHow = SHUT_RD;
747 else
748 fHow = SHUT_WR;
749 if (shutdown(pThis->hNative, fHow) == -1)
750 rc = rtSocketError();
751
752 return rc;
753}
754
755
756/**
757 * Converts from a native socket address to a generic IPRT network address.
758 *
759 * @returns IPRT status code.
760 * @param pSrc The source address.
761 * @param cbSrc The size of the source address.
762 * @param pAddr Where to return the generic IPRT network
763 * address.
764 */
765static int rtSocketConvertAddress(RTSOCKADDRUNION const *pSrc, size_t cbSrc, PRTNETADDR pAddr)
766{
767 /*
768 * Convert the address.
769 */
770 if ( cbSrc == sizeof(struct sockaddr_in)
771 && pSrc->Addr.sa_family == AF_INET)
772 {
773 RT_ZERO(*pAddr);
774 pAddr->enmType = RTNETADDRTYPE_IPV4;
775 pAddr->uPort = RT_N2H_U16(pSrc->Ipv4.sin_port);
776 pAddr->uAddr.IPv4.u = pSrc->Ipv4.sin_addr.s_addr;
777 }
778#ifdef IPRT_WITH_TCPIP_V6
779 else if ( cbSrc == sizeof(struct sockaddr_in6)
780 && pSrc->Addr.sa_family == AF_INET6)
781 {
782 RT_ZERO(*pAddr);
783 pAddr->enmType = RTNETADDRTYPE_IPV6;
784 pAddr->uPort = RT_N2H_U16(pSrc->Ipv6.sin6_port);
785 pAddr->uAddr.IPv6.au32[0] = pSrc->Ipv6.sin6_addr.s6_addr32[0];
786 pAddr->uAddr.IPv6.au32[1] = pSrc->Ipv6.sin6_addr.s6_addr32[1];
787 pAddr->uAddr.IPv6.au32[2] = pSrc->Ipv6.sin6_addr.s6_addr32[2];
788 pAddr->uAddr.IPv6.au32[3] = pSrc->Ipv6.sin6_addr.s6_addr32[3];
789 }
790#endif
791 else
792 return VERR_NET_ADDRESS_FAMILY_NOT_SUPPORTED;
793 return VINF_SUCCESS;
794}
795
796
797RTDECL(int) RTSocketGetLocalAddress(RTSOCKET hSocket, PRTNETADDR pAddr)
798{
799 /*
800 * Validate input.
801 */
802 RTSOCKETINT *pThis = hSocket;
803 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
804 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
805 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
806
807 /*
808 * Get the address and convert it.
809 */
810 int rc;
811 RTSOCKADDRUNION u;
812#ifdef RT_OS_WINDOWS
813 int cbAddr = sizeof(u);
814#else
815 socklen_t cbAddr = sizeof(u);
816#endif
817 RT_ZERO(u);
818 if (getsockname(pThis->hNative, &u.Addr, &cbAddr) == 0)
819 rc = rtSocketConvertAddress(&u, cbAddr, pAddr);
820 else
821 rc = rtSocketError();
822
823 return rc;
824}
825
826
827RTDECL(int) RTSocketGetPeerAddress(RTSOCKET hSocket, PRTNETADDR pAddr)
828{
829 /*
830 * Validate input.
831 */
832 RTSOCKETINT *pThis = hSocket;
833 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
834 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
835 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
836
837 /*
838 * Get the address and convert it.
839 */
840 int rc;
841 RTSOCKADDRUNION u;
842#ifdef RT_OS_WINDOWS
843 int cbAddr = sizeof(u);
844#else
845 socklen_t cbAddr = sizeof(u);
846#endif
847 RT_ZERO(u);
848 if (getpeername(pThis->hNative, &u.Addr, &cbAddr) == 0)
849 rc = rtSocketConvertAddress(&u, cbAddr, pAddr);
850 else
851 rc = rtSocketError();
852
853 return rc;
854}
855
856
857
858/**
859 * Wrapper around bind.
860 *
861 * @returns IPRT status code.
862 * @param hSocket The socket handle.
863 * @param pAddr The socket address to bind to.
864 * @param cbAddr The size of the address structure @a pAddr
865 * points to.
866 */
867int rtSocketBind(RTSOCKET hSocket, const struct sockaddr *pAddr, int cbAddr)
868{
869 /*
870 * Validate input.
871 */
872 RTSOCKETINT *pThis = hSocket;
873 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
874 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
875 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
876
877 int rc = VINF_SUCCESS;
878 if (bind(pThis->hNative, pAddr, cbAddr) != 0)
879 rc = rtSocketError();
880
881 rtSocketUnlock(pThis);
882 return rc;
883}
884
885
886/**
887 * Wrapper around listen.
888 *
889 * @returns IPRT status code.
890 * @param hSocket The socket handle.
891 * @param cMaxPending The max number of pending connections.
892 */
893int rtSocketListen(RTSOCKET hSocket, int cMaxPending)
894{
895 /*
896 * Validate input.
897 */
898 RTSOCKETINT *pThis = hSocket;
899 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
900 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
901 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
902
903 int rc = VINF_SUCCESS;
904 if (listen(pThis->hNative, cMaxPending) != 0)
905 rc = rtSocketError();
906
907 rtSocketUnlock(pThis);
908 return rc;
909}
910
911
912/**
913 * Wrapper around accept.
914 *
915 * @returns IPRT status code.
916 * @param hSocket The socket handle.
917 * @param phClient Where to return the client socket handle on
918 * success.
919 * @param pAddr Where to return the client address.
920 * @param pcbAddr On input this gives the size buffer size of what
921 * @a pAddr point to. On return this contains the
922 * size of what's stored at @a pAddr.
923 */
924int rtSocketAccept(RTSOCKET hSocket, PRTSOCKET phClient, struct sockaddr *pAddr, size_t *pcbAddr)
925{
926 /*
927 * Validate input.
928 * Only lock the socket temporarily while we get the native handle, so that
929 * we can safely shutdown and destroy the socket from a different thread.
930 */
931 RTSOCKETINT *pThis = hSocket;
932 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
933 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
934 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
935
936 /*
937 * Call accept().
938 */
939 rtSocketErrorReset();
940 int rc = VINF_SUCCESS;
941#ifdef RT_OS_WINDOWS
942 int cbAddr = (int)*pcbAddr;
943#else
944 socklen_t cbAddr = *pcbAddr;
945#endif
946 RTSOCKETNATIVE hNativeClient = accept(pThis->hNative, pAddr, &cbAddr);
947 if (hNativeClient != NIL_RTSOCKETNATIVE)
948 {
949 *pcbAddr = cbAddr;
950
951 /*
952 * Wrap the client socket.
953 */
954 rc = rtSocketCreateForNative(phClient, hNativeClient);
955 if (RT_FAILURE(rc))
956 {
957#ifdef RT_OS_WINDOWS
958 closesocket(hNativeClient);
959#else
960 close(hNativeClient);
961#endif
962 }
963 }
964 else
965 rc = rtSocketError();
966
967 rtSocketUnlock(pThis);
968 return rc;
969}
970
971
972/**
973 * Wrapper around connect.
974 *
975 * @returns IPRT status code.
976 * @param hSocket The socket handle.
977 * @param pAddr The socket address to connect to.
978 * @param cbAddr The size of the address structure @a pAddr
979 * points to.
980 */
981int rtSocketConnect(RTSOCKET hSocket, const struct sockaddr *pAddr, int cbAddr)
982{
983 /*
984 * Validate input.
985 */
986 RTSOCKETINT *pThis = hSocket;
987 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
988 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
989 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
990
991 int rc = VINF_SUCCESS;
992 if (connect(pThis->hNative, pAddr, cbAddr) != 0)
993 rc = rtSocketError();
994
995 rtSocketUnlock(pThis);
996 return rc;
997}
998
999
1000/**
1001 * Wrapper around setsockopt.
1002 *
1003 * @returns IPRT status code.
1004 * @param hSocket The socket handle.
1005 * @param iLevel The protocol level, e.g. IPPORTO_TCP.
1006 * @param iOption The option, e.g. TCP_NODELAY.
1007 * @param pvValue The value buffer.
1008 * @param cbValue The size of the value pointed to by pvValue.
1009 */
1010int rtSocketSetOpt(RTSOCKET hSocket, int iLevel, int iOption, void const *pvValue, int cbValue)
1011{
1012 /*
1013 * Validate input.
1014 */
1015 RTSOCKETINT *pThis = hSocket;
1016 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1017 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1018 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1019
1020 int rc = VINF_SUCCESS;
1021 if (setsockopt(pThis->hNative, iLevel, iOption, (const char *)pvValue, cbValue) != 0)
1022 rc = rtSocketError();
1023
1024 rtSocketUnlock(pThis);
1025 return rc;
1026}
1027
1028#ifdef RT_OS_WINDOWS
1029
1030/**
1031 * Internal RTPollSetAdd helper that returns the handle that should be added to
1032 * the pollset.
1033 *
1034 * @returns Valid handle on success, INVALID_HANDLE_VALUE on failure.
1035 * @param hSocket The socket handle.
1036 * @param fEvents The events we're polling for.
1037 * @param ph wher to put the primary handle.
1038 */
1039int rtSocketPollGetHandle(RTSOCKET hSocket, uint32_t fEvents, PHANDLE ph)
1040{
1041 RTSOCKETINT *pThis = hSocket;
1042 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1043 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1044 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1045
1046 int rc = VINF_SUCCESS;
1047 if (pThis->hEvent != WSA_INVALID_EVENT)
1048 *ph = pThis->hEvent;
1049 else
1050 {
1051 *ph = pThis->hEvent = WSACreateEvent();
1052 if (pThis->hEvent == WSA_INVALID_EVENT)
1053 rc = rtSocketError();
1054 }
1055
1056 rtSocketUnlock(pThis);
1057 return rc;
1058}
1059
1060
1061/**
1062 * Undos the harm done by WSAEventSelect.
1063 *
1064 * @returns IPRT status code.
1065 * @param pThis The socket handle.
1066 */
1067static int rtSocketPollClearEventAndMakeBlocking(RTSOCKETINT *pThis)
1068{
1069 int rc = VINF_SUCCESS;
1070 if (pThis->fSubscribedEvts)
1071 {
1072 if (WSAEventSelect(pThis->hNative, WSA_INVALID_EVENT, 0) == 0)
1073 {
1074 pThis->fSubscribedEvts = 0;
1075
1076 u_long fNonBlocking = 0;
1077 int rc2 = ioctlsocket(pThis->hNative, FIONBIO, &fNonBlocking);
1078 if (rc2 != 0)
1079 {
1080 rc = rtSocketError();
1081 AssertMsgFailed(("%Rrc; rc2=%d\n", rc, rc2));
1082 }
1083 }
1084 else
1085 {
1086 rc = rtSocketError();
1087 AssertMsgFailed(("%Rrc\n", rc));
1088 }
1089 }
1090 return rc;
1091}
1092
1093
1094/**
1095 * Updates the mask of events we're subscribing to.
1096 *
1097 * @returns IPRT status code.
1098 * @param pThis The socket handle.
1099 * @param fEvents The events we want to subscribe to.
1100 */
1101static int rtSocketPollUpdateEvents(RTSOCKETINT *pThis, uint32_t fEvents)
1102{
1103 LONG fNetworkEvents = 0;
1104 if (fEvents & RTPOLL_EVT_READ)
1105 fNetworkEvents |= FD_READ;
1106 if (fEvents & RTPOLL_EVT_WRITE)
1107 fNetworkEvents |= FD_WRITE;
1108 if (fEvents & RTPOLL_EVT_ERROR)
1109 fNetworkEvents |= FD_CLOSE;
1110 if (WSAEventSelect(pThis->hNative, pThis->hEvent, fNetworkEvents) == 0)
1111 {
1112 pThis->fSubscribedEvts = fEvents;
1113 return VINF_SUCCESS;
1114 }
1115
1116 int rc = rtSocketError();
1117 AssertMsgFailed(("fNetworkEvents=%#x rc=%Rrc\n", fNetworkEvents, rtSocketError()));
1118 return rc;
1119}
1120
1121
1122/**
1123 * Checks for pending events.
1124 *
1125 * @returns Event mask or 0.
1126 * @param pThis The socket handle.
1127 * @param fEvents The desired events.
1128 */
1129static uint32_t rtSocketPollCheck(RTSOCKETINT *pThis, uint32_t fEvents)
1130{
1131 int rc = VINF_SUCCESS;
1132 uint32_t fRetEvents = 0;
1133
1134 /* Make sure WSAEnumNetworkEvents returns what we want. */
1135 if ((pThis->fSubscribedEvts & fEvents) != fEvents)
1136 rc = rtSocketPollUpdateEvents(pThis, pThis->fSubscribedEvts | fEvents);
1137
1138 /* Get the event mask, ASSUMES that WSAEnumNetworkEvents doesn't clear stuff. */
1139 WSANETWORKEVENTS NetEvts;
1140 RT_ZERO(NetEvts);
1141 if (WSAEnumNetworkEvents(pThis->hNative, pThis->hEvent, &NetEvts) == 0)
1142 {
1143 if ( (NetEvts.lNetworkEvents & FD_READ)
1144 && (fEvents & RTPOLL_EVT_READ)
1145 && NetEvts.iErrorCode[FD_READ_BIT] == 0)
1146 fRetEvents |= RTPOLL_EVT_READ;
1147
1148 if ( (NetEvts.lNetworkEvents & FD_WRITE)
1149 && (fEvents & RTPOLL_EVT_WRITE)
1150 && NetEvts.iErrorCode[FD_WRITE_BIT] == 0)
1151 fRetEvents |= RTPOLL_EVT_WRITE;
1152
1153 if (fEvents & RTPOLL_EVT_ERROR)
1154 {
1155 if (NetEvts.lNetworkEvents & FD_CLOSE)
1156 fRetEvents |= RTPOLL_EVT_ERROR;
1157 else
1158 for (uint32_t i = 0; i < FD_MAX_EVENTS; i++)
1159 if ( (NetEvts.lNetworkEvents & (1L << i))
1160 && NetEvts.iErrorCode[i] != 0)
1161 fRetEvents |= RTPOLL_EVT_ERROR;
1162 }
1163 }
1164 else
1165 rc = rtSocketError();
1166
1167 /* Fall back on select if we hit an error above. */
1168 if (RT_FAILURE(rc))
1169 {
1170 /** @todo */
1171 }
1172
1173 return fRetEvents;
1174}
1175
1176
1177/**
1178 * Internal RTPoll helper that polls the socket handle and, if @a fNoWait is
1179 * clear, starts whatever actions we've got running during the poll call.
1180 *
1181 * @returns 0 if no pending events, actions initiated if @a fNoWait is clear.
1182 * Event mask (in @a fEvents) and no actions if the handle is ready
1183 * already.
1184 * UINT32_MAX (asserted) if the socket handle is busy in I/O or a
1185 * different poll set.
1186 *
1187 * @param hSocket The socket handle.
1188 * @param hPollSet The poll set handle (for access checks).
1189 * @param fEvents The events we're polling for.
1190 * @param fFinalEntry Set if this is the final entry for this handle
1191 * in this poll set. This can be used for dealing
1192 * with duplicate entries.
1193 * @param fNoWait Set if it's a zero-wait poll call. Clear if
1194 * we'll wait for an event to occur.
1195 *
1196 * @remarks There is a potential race wrt duplicate handles when @a fNoWait is
1197 * @c true, we don't currently care about that oddity...
1198 */
1199uint32_t rtSocketPollStart(RTSOCKET hSocket, RTPOLLSET hPollSet, uint32_t fEvents, bool fFinalEntry, bool fNoWait)
1200{
1201 RTSOCKETINT *pThis = hSocket;
1202 AssertPtrReturn(pThis, UINT32_MAX);
1203 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, UINT32_MAX);
1204 if (rtSocketTryLock(pThis))
1205 pThis->hPollSet = hPollSet;
1206 else
1207 {
1208 AssertReturn(pThis->hPollSet == hPollSet, UINT32_MAX);
1209 ASMAtomicIncU32(&pThis->cUsers);
1210 }
1211
1212 /* (rtSocketPollCheck will reset the event object). */
1213 uint32_t fRetEvents = rtSocketPollCheck(pThis, fEvents);
1214 if ( !fRetEvents
1215 && !fNoWait)
1216 {
1217 pThis->fPollEvts |= fEvents;
1218 if ( fFinalEntry
1219 && pThis->fSubscribedEvts != pThis->fPollEvts)
1220 {
1221 int rc = rtSocketPollUpdateEvents(pThis, pThis->fPollEvts);
1222 if (RT_FAILURE(rc))
1223 {
1224 pThis->fPollEvts = 0;
1225 fRetEvents = UINT32_MAX;
1226 }
1227 }
1228 }
1229
1230 if (fRetEvents || fNoWait)
1231 {
1232 if (pThis->cUsers == 1)
1233 {
1234 rtSocketPollClearEventAndMakeBlocking(pThis);
1235 pThis->hPollSet = NIL_RTPOLLSET;
1236 }
1237 ASMAtomicDecU32(&pThis->cUsers);
1238 }
1239
1240 return fRetEvents;
1241}
1242
1243
1244/**
1245 * Called after a WaitForMultipleObjects returned in order to check for pending
1246 * events and stop whatever actions that rtSocketPollStart() initiated.
1247 *
1248 * @returns Event mask or 0.
1249 *
1250 * @param hSocket The socket handle.
1251 * @param fEvents The events we're polling for.
1252 * @param fFinalEntry Set if this is the final entry for this handle
1253 * in this poll set. This can be used for dealing
1254 * with duplicate entries. Only keep in mind that
1255 * this method is called in reverse order, so the
1256 * first call will have this set (when the entire
1257 * set was processed).
1258 */
1259uint32_t rtSocketPollDone(RTSOCKET hSocket, uint32_t fEvents, bool fFinalEntry)
1260{
1261 RTSOCKETINT *pThis = hSocket;
1262 AssertPtrReturn(pThis, 0);
1263 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, 0);
1264 Assert(pThis->cUsers > 0);
1265 Assert(pThis->hPollSet != NIL_RTPOLLSET);
1266
1267 /* Harvest events and clear the event mask for the next round of polling. */
1268 uint32_t fRetEvents = rtSocketPollCheck(pThis, fEvents);
1269 pThis->fPollEvts = 0;
1270
1271 /* Make the socket blocking again and unlock the handle. */
1272 if (pThis->cUsers == 1)
1273 {
1274 rtSocketPollClearEventAndMakeBlocking(pThis);
1275 pThis->hPollSet = NIL_RTPOLLSET;
1276 }
1277 ASMAtomicDecU32(&pThis->cUsers);
1278 return fRetEvents;
1279}
1280
1281#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