VirtualBox

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

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

Runtime/socket: typo

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

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