VirtualBox

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

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

compile fix

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 35.6 KB
Line 
1/* $Id: socket.cpp 30307 2010-06-18 11:46:22Z 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 AssertCompileSize(WSABUF, sizeof(RTSGSEG));
599 AssertCompileMemberSize(WSABUF, buf, RT_SIZEOFMEMB(RTSGSEG, pvSeg));
600
601 LPWSABUF paMsg = (LPWSABUF)RTMemTmpAllocZ(pSgBuf->cSeg * sizeof(WSABUF));
602 AssertPtrBreakStmt(paMsg, rc = VERR_NO_MEMORY);
603 for (unsigned i = 0; i < pSgBuf->cSeg; i++)
604 {
605 paMsg[i].buf = (char *)pSgBuf->pcaSeg[i].pvSeg;
606 paMsg[i].len = (u_long)pSgBuf->pcaSeg[i].cbSeg;
607 }
608
609 DWORD dwSent;
610 int hrc = WSASend(pThis->hNative, paMsg, pSgBuf->cSeg, &dwSent,
611 MSG_NOSIGNAL, NULL, NULL);
612 ssize_t cbWritten;
613 if (!hrc)
614 {
615 /* avoid overflowing ssize_t, the exact value isn't important */
616 cbWritten = RT_MIN(dwSent, INT_MAX);
617 }
618 else
619 cbWritten = -1;
620#else
621 AssertCompileSize(struct iovec, sizeof(RTSGSEG));
622 AssertCompileMemberSize(struct iovec, iov_base, RT_SIZEOFMEMB(RTSGSEG, pvSeg));
623 AssertCompileMemberSize(struct iovec, iov_len, RT_SIZEOFMEMB(RTSGSEG, cbSeg));
624
625 struct iovec *paMsg = (struct iovec *)RTMemTmpAllocZ(pSgBuf->cSeg * sizeof(struct iovec));
626 AssertPtrBreakStmt(paMsg, rc = VERR_NO_MEMORY);
627 for (unsigned i = 0; i < pSgBuf->cSeg; i++)
628 {
629 paMsg[i].iov_base = pSgBuf->pcaSeg[i].pvSeg;
630 paMsg[i].iov_len = pSgBuf->pcaSeg[i].cbSeg;
631 }
632
633 struct msghdr msgHdr;
634 memset(&msgHdr, '\0', sizeof(msgHdr));
635 msgHdr.msg_iov = paMsg;
636 msgHdr.msg_iovlen = pSgBuf->cSeg;
637 ssize_t cbWritten = sendmsg(pThis->hNative, &msgHdr, MSG_NOSIGNAL);
638#endif
639
640 RTMemTmpFree(paMsg);
641 if (RT_LIKELY(cbWritten >= 0))
642 rc = VINF_SUCCESS;
643 else
644 rc = rtSocketError();
645 } while (0);
646
647 rtSocketUnlock(pThis);
648 return rc;
649}
650
651
652RTDECL(int) RTSocketSelectOne(RTSOCKET hSocket, RTMSINTERVAL cMillies)
653{
654 /*
655 * Validate input.
656 */
657 RTSOCKETINT *pThis = hSocket;
658 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
659 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
660 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
661
662 /*
663 * Set up the file descriptor sets and do the select.
664 */
665 fd_set fdsetR;
666 FD_ZERO(&fdsetR);
667 FD_SET(pThis->hNative, &fdsetR);
668
669 fd_set fdsetE = fdsetR;
670
671 int rc;
672 if (cMillies == RT_INDEFINITE_WAIT)
673 rc = select(pThis->hNative + 1, &fdsetR, NULL, &fdsetE, NULL);
674 else
675 {
676 struct timeval timeout;
677 timeout.tv_sec = cMillies / 1000;
678 timeout.tv_usec = (cMillies % 1000) * 1000;
679 rc = select(pThis->hNative + 1, &fdsetR, NULL, &fdsetE, &timeout);
680 }
681 if (rc > 0)
682 rc = VINF_SUCCESS;
683 else if (rc == 0)
684 rc = VERR_TIMEOUT;
685 else
686 rc = rtSocketError();
687
688 return rc;
689}
690
691
692RTDECL(int) RTSocketShutdown(RTSOCKET hSocket, bool fRead, bool fWrite)
693{
694 /*
695 * Validate input, don't lock it because we might want to interrupt a call
696 * active on a different thread.
697 */
698 RTSOCKETINT *pThis = hSocket;
699 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
700 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
701 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
702 AssertReturn(fRead || fWrite, VERR_INVALID_PARAMETER);
703
704 /*
705 * Do the job.
706 */
707 int rc = VINF_SUCCESS;
708 int fHow;
709 if (fRead && fWrite)
710 fHow = SHUT_RDWR;
711 else if (fRead)
712 fHow = SHUT_RD;
713 else
714 fHow = SHUT_WR;
715 if (shutdown(pThis->hNative, fHow) == -1)
716 rc = rtSocketError();
717
718 return rc;
719}
720
721
722/**
723 * Converts from a native socket address to a generic IPRT network address.
724 *
725 * @returns IPRT status code.
726 * @param pSrc The source address.
727 * @param cbSrc The size of the source address.
728 * @param pAddr Where to return the generic IPRT network
729 * address.
730 */
731static int rtSocketConvertAddress(RTSOCKADDRUNION const *pSrc, size_t cbSrc, PRTNETADDR pAddr)
732{
733 /*
734 * Convert the address.
735 */
736 if ( cbSrc == sizeof(struct sockaddr_in)
737 && pSrc->Addr.sa_family == AF_INET)
738 {
739 RT_ZERO(*pAddr);
740 pAddr->enmType = RTNETADDRTYPE_IPV4;
741 pAddr->uPort = RT_N2H_U16(pSrc->Ipv4.sin_port);
742 pAddr->uAddr.IPv4.u = pSrc->Ipv4.sin_addr.s_addr;
743 }
744#ifdef IPRT_WITH_TCPIP_V6
745 else if ( cbSrc == sizeof(struct sockaddr_in6)
746 && pSrc->Addr.sa_family == AF_INET6)
747 {
748 RT_ZERO(*pAddr);
749 pAddr->enmType = RTNETADDRTYPE_IPV6;
750 pAddr->uPort = RT_N2H_U16(pSrc->Ipv6.sin6_port);
751 pAddr->uAddr.IPv6.au32[0] = pSrc->Ipv6.sin6_addr.s6_addr32[0];
752 pAddr->uAddr.IPv6.au32[1] = pSrc->Ipv6.sin6_addr.s6_addr32[1];
753 pAddr->uAddr.IPv6.au32[2] = pSrc->Ipv6.sin6_addr.s6_addr32[2];
754 pAddr->uAddr.IPv6.au32[3] = pSrc->Ipv6.sin6_addr.s6_addr32[3];
755 }
756#endif
757 else
758 return VERR_NET_ADDRESS_FAMILY_NOT_SUPPORTED;
759 return VINF_SUCCESS;
760}
761
762
763RTDECL(int) RTSocketGetLocalAddress(RTSOCKET hSocket, PRTNETADDR pAddr)
764{
765 /*
766 * Validate input.
767 */
768 RTSOCKETINT *pThis = hSocket;
769 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
770 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
771 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
772
773 /*
774 * Get the address and convert it.
775 */
776 int rc;
777 RTSOCKADDRUNION u;
778#ifdef RT_OS_WINDOWS
779 int cbAddr = sizeof(u);
780#else
781 socklen_t cbAddr = sizeof(u);
782#endif
783 RT_ZERO(u);
784 if (getsockname(pThis->hNative, &u.Addr, &cbAddr) == 0)
785 rc = rtSocketConvertAddress(&u, cbAddr, pAddr);
786 else
787 rc = rtSocketError();
788
789 return rc;
790}
791
792
793RTDECL(int) RTSocketGetPeerAddress(RTSOCKET hSocket, PRTNETADDR pAddr)
794{
795 /*
796 * Validate input.
797 */
798 RTSOCKETINT *pThis = hSocket;
799 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
800 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
801 AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
802
803 /*
804 * Get the address and convert it.
805 */
806 int rc;
807 RTSOCKADDRUNION u;
808#ifdef RT_OS_WINDOWS
809 int cbAddr = sizeof(u);
810#else
811 socklen_t cbAddr = sizeof(u);
812#endif
813 RT_ZERO(u);
814 if (getpeername(pThis->hNative, &u.Addr, &cbAddr) == 0)
815 rc = rtSocketConvertAddress(&u, cbAddr, pAddr);
816 else
817 rc = rtSocketError();
818
819 return rc;
820}
821
822
823
824/**
825 * Wrapper around bind.
826 *
827 * @returns IPRT status code.
828 * @param hSocket The socket handle.
829 * @param pAddr The socket address to bind to.
830 * @param cbAddr The size of the address structure @a pAddr
831 * points to.
832 */
833int rtSocketBind(RTSOCKET hSocket, const struct sockaddr *pAddr, int cbAddr)
834{
835 /*
836 * Validate input.
837 */
838 RTSOCKETINT *pThis = hSocket;
839 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
840 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
841 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
842
843 int rc = VINF_SUCCESS;
844 if (bind(pThis->hNative, pAddr, cbAddr) != 0)
845 rc = rtSocketError();
846
847 rtSocketUnlock(pThis);
848 return rc;
849}
850
851
852/**
853 * Wrapper around listen.
854 *
855 * @returns IPRT status code.
856 * @param hSocket The socket handle.
857 * @param cMaxPending The max number of pending connections.
858 */
859int rtSocketListen(RTSOCKET hSocket, int cMaxPending)
860{
861 /*
862 * Validate input.
863 */
864 RTSOCKETINT *pThis = hSocket;
865 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
866 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
867 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
868
869 int rc = VINF_SUCCESS;
870 if (listen(pThis->hNative, cMaxPending) != 0)
871 rc = rtSocketError();
872
873 rtSocketUnlock(pThis);
874 return rc;
875}
876
877
878/**
879 * Wrapper around accept.
880 *
881 * @returns IPRT status code.
882 * @param hSocket The socket handle.
883 * @param phClient Where to return the client socket handle on
884 * success.
885 * @param pAddr Where to return the client address.
886 * @param pcbAddr On input this gives the size buffer size of what
887 * @a pAddr point to. On return this contains the
888 * size of what's stored at @a pAddr.
889 */
890int rtSocketAccept(RTSOCKET hSocket, PRTSOCKET phClient, struct sockaddr *pAddr, size_t *pcbAddr)
891{
892 /*
893 * Validate input.
894 * Only lock the socket temporarily while we get the native handle, so that
895 * we can safely shutdown and destroy the socket from a different thread.
896 */
897 RTSOCKETINT *pThis = hSocket;
898 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
899 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
900 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
901
902 /*
903 * Call accept().
904 */
905 rtSocketErrorReset();
906 int rc = VINF_SUCCESS;
907#ifdef RT_OS_WINDOWS
908 int cbAddr = (int)*pcbAddr;
909#else
910 socklen_t cbAddr = *pcbAddr;
911#endif
912 RTSOCKETNATIVE hNativeClient = accept(pThis->hNative, pAddr, &cbAddr);
913 if (hNativeClient != NIL_RTSOCKETNATIVE)
914 {
915 *pcbAddr = cbAddr;
916
917 /*
918 * Wrap the client socket.
919 */
920 rc = rtSocketCreateForNative(phClient, hNativeClient);
921 if (RT_FAILURE(rc))
922 {
923#ifdef RT_OS_WINDOWS
924 closesocket(hNativeClient);
925#else
926 close(hNativeClient);
927#endif
928 }
929 }
930 else
931 rc = rtSocketError();
932
933 rtSocketUnlock(pThis);
934 return rc;
935}
936
937
938/**
939 * Wrapper around connect.
940 *
941 * @returns IPRT status code.
942 * @param hSocket The socket handle.
943 * @param pAddr The socket address to connect to.
944 * @param cbAddr The size of the address structure @a pAddr
945 * points to.
946 */
947int rtSocketConnect(RTSOCKET hSocket, const struct sockaddr *pAddr, int cbAddr)
948{
949 /*
950 * Validate input.
951 */
952 RTSOCKETINT *pThis = hSocket;
953 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
954 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
955 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
956
957 int rc = VINF_SUCCESS;
958 if (connect(pThis->hNative, pAddr, cbAddr) != 0)
959 rc = rtSocketError();
960
961 rtSocketUnlock(pThis);
962 return rc;
963}
964
965
966/**
967 * Wrapper around setsockopt.
968 *
969 * @returns IPRT status code.
970 * @param hSocket The socket handle.
971 * @param iLevel The protocol level, e.g. IPPORTO_TCP.
972 * @param iOption The option, e.g. TCP_NODELAY.
973 * @param pvValue The value buffer.
974 * @param cbValue The size of the value pointed to by pvValue.
975 */
976int rtSocketSetOpt(RTSOCKET hSocket, int iLevel, int iOption, void const *pvValue, int cbValue)
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 (setsockopt(pThis->hNative, iLevel, iOption, (const char *)pvValue, cbValue) != 0)
988 rc = rtSocketError();
989
990 rtSocketUnlock(pThis);
991 return rc;
992}
993
994#ifdef RT_OS_WINDOWS
995
996/**
997 * Internal RTPollSetAdd helper that returns the handle that should be added to
998 * the pollset.
999 *
1000 * @returns Valid handle on success, INVALID_HANDLE_VALUE on failure.
1001 * @param hSocket The socket handle.
1002 * @param fEvents The events we're polling for.
1003 * @param ph wher to put the primary handle.
1004 */
1005int rtSocketPollGetHandle(RTSOCKET hSocket, uint32_t fEvents, PHANDLE ph)
1006{
1007 RTSOCKETINT *pThis = hSocket;
1008 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1009 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
1010 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
1011
1012 int rc = VINF_SUCCESS;
1013 if (pThis->hEvent != WSA_INVALID_EVENT)
1014 *ph = pThis->hEvent;
1015 else
1016 {
1017 *ph = pThis->hEvent = WSACreateEvent();
1018 if (pThis->hEvent == WSA_INVALID_EVENT)
1019 rc = rtSocketError();
1020 }
1021
1022 rtSocketUnlock(pThis);
1023 return rc;
1024}
1025
1026
1027/**
1028 * Undos the harm done by WSAEventSelect.
1029 *
1030 * @returns IPRT status code.
1031 * @param pThis The socket handle.
1032 */
1033static int rtSocketPollClearEventAndMakeBlocking(RTSOCKETINT *pThis)
1034{
1035 int rc = VINF_SUCCESS;
1036 if (pThis->fSubscribedEvts)
1037 {
1038 if (WSAEventSelect(pThis->hNative, WSA_INVALID_EVENT, 0) == 0)
1039 {
1040 pThis->fSubscribedEvts = 0;
1041
1042 u_long fNonBlocking = 0;
1043 int rc2 = ioctlsocket(pThis->hNative, FIONBIO, &fNonBlocking);
1044 if (rc2 != 0)
1045 {
1046 rc = rtSocketError();
1047 AssertMsgFailed(("%Rrc; rc2=%d\n", rc, rc2));
1048 }
1049 }
1050 else
1051 {
1052 rc = rtSocketError();
1053 AssertMsgFailed(("%Rrc\n", rc));
1054 }
1055 }
1056 return rc;
1057}
1058
1059
1060/**
1061 * Updates the mask of events we're subscribing to.
1062 *
1063 * @returns IPRT status code.
1064 * @param pThis The socket handle.
1065 * @param fEvents The events we want to subscribe to.
1066 */
1067static int rtSocketPollUpdateEvents(RTSOCKETINT *pThis, uint32_t fEvents)
1068{
1069 LONG fNetworkEvents = 0;
1070 if (fEvents & RTPOLL_EVT_READ)
1071 fNetworkEvents |= FD_READ;
1072 if (fEvents & RTPOLL_EVT_WRITE)
1073 fNetworkEvents |= FD_WRITE;
1074 if (fEvents & RTPOLL_EVT_ERROR)
1075 fNetworkEvents |= FD_CLOSE;
1076 if (WSAEventSelect(pThis->hNative, pThis->hEvent, fNetworkEvents) == 0)
1077 {
1078 pThis->fSubscribedEvts = fEvents;
1079 return VINF_SUCCESS;
1080 }
1081
1082 int rc = rtSocketError();
1083 AssertMsgFailed(("fNetworkEvents=%#x rc=%Rrc\n", fNetworkEvents, rtSocketError()));
1084 return rc;
1085}
1086
1087
1088/**
1089 * Checks for pending events.
1090 *
1091 * @returns Event mask or 0.
1092 * @param pThis The socket handle.
1093 * @param fEvents The desired events.
1094 */
1095static uint32_t rtSocketPollCheck(RTSOCKETINT *pThis, uint32_t fEvents)
1096{
1097 int rc = VINF_SUCCESS;
1098 uint32_t fRetEvents = 0;
1099
1100 /* Make sure WSAEnumNetworkEvents returns what we want. */
1101 if ((pThis->fSubscribedEvts & fEvents) != fEvents)
1102 rc = rtSocketPollUpdateEvents(pThis, pThis->fSubscribedEvts | fEvents);
1103
1104 /* Get the event mask, ASSUMES that WSAEnumNetworkEvents doesn't clear stuff. */
1105 WSANETWORKEVENTS NetEvts;
1106 RT_ZERO(NetEvts);
1107 if (WSAEnumNetworkEvents(pThis->hNative, pThis->hEvent, &NetEvts) == 0)
1108 {
1109 if ( (NetEvts.lNetworkEvents & FD_READ)
1110 && (fEvents & RTPOLL_EVT_READ)
1111 && NetEvts.iErrorCode[FD_READ_BIT] == 0)
1112 fRetEvents |= RTPOLL_EVT_READ;
1113
1114 if ( (NetEvts.lNetworkEvents & FD_WRITE)
1115 && (fEvents & RTPOLL_EVT_WRITE)
1116 && NetEvts.iErrorCode[FD_WRITE_BIT] == 0)
1117 fRetEvents |= RTPOLL_EVT_WRITE;
1118
1119 if (fEvents & RTPOLL_EVT_ERROR)
1120 {
1121 if (NetEvts.lNetworkEvents & FD_CLOSE)
1122 fRetEvents |= RTPOLL_EVT_ERROR;
1123 else
1124 for (uint32_t i = 0; i < FD_MAX_EVENTS; i++)
1125 if ( (NetEvts.lNetworkEvents & (1L << i))
1126 && NetEvts.iErrorCode[i] != 0)
1127 fRetEvents |= RTPOLL_EVT_ERROR;
1128 }
1129 }
1130 else
1131 rc = rtSocketError();
1132
1133 /* Fall back on select if we hit an error above. */
1134 if (RT_FAILURE(rc))
1135 {
1136 /** @todo */
1137 }
1138
1139 return fRetEvents;
1140}
1141
1142
1143/**
1144 * Internal RTPoll helper that polls the socket handle and, if @a fNoWait is
1145 * clear, starts whatever actions we've got running during the poll call.
1146 *
1147 * @returns 0 if no pending events, actions initiated if @a fNoWait is clear.
1148 * Event mask (in @a fEvents) and no actions if the handle is ready
1149 * already.
1150 * UINT32_MAX (asserted) if the socket handle is busy in I/O or a
1151 * different poll set.
1152 *
1153 * @param hSocket The socket handle.
1154 * @param hPollSet The poll set handle (for access checks).
1155 * @param fEvents The events we're polling for.
1156 * @param fFinalEntry Set if this is the final entry for this handle
1157 * in this poll set. This can be used for dealing
1158 * with duplicate entries.
1159 * @param fNoWait Set if it's a zero-wait poll call. Clear if
1160 * we'll wait for an event to occur.
1161 *
1162 * @remarks There is a potential race wrt duplicate handles when @a fNoWait is
1163 * @c true, we don't currently care about that oddity...
1164 */
1165uint32_t rtSocketPollStart(RTSOCKET hSocket, RTPOLLSET hPollSet, uint32_t fEvents, bool fFinalEntry, bool fNoWait)
1166{
1167 RTSOCKETINT *pThis = hSocket;
1168 AssertPtrReturn(pThis, UINT32_MAX);
1169 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, UINT32_MAX);
1170 if (rtSocketTryLock(pThis))
1171 pThis->hPollSet = hPollSet;
1172 else
1173 {
1174 AssertReturn(pThis->hPollSet == hPollSet, UINT32_MAX);
1175 ASMAtomicIncU32(&pThis->cUsers);
1176 }
1177
1178 /* (rtSocketPollCheck will reset the event object). */
1179 uint32_t fRetEvents = rtSocketPollCheck(pThis, fEvents);
1180 if ( !fRetEvents
1181 && !fNoWait)
1182 {
1183 pThis->fPollEvts |= fEvents;
1184 if ( fFinalEntry
1185 && pThis->fSubscribedEvts != pThis->fPollEvts)
1186 {
1187 int rc = rtSocketPollUpdateEvents(pThis, pThis->fPollEvts);
1188 if (RT_FAILURE(rc))
1189 {
1190 pThis->fPollEvts = 0;
1191 fRetEvents = UINT32_MAX;
1192 }
1193 }
1194 }
1195
1196 if (fRetEvents || fNoWait)
1197 {
1198 if (pThis->cUsers == 1)
1199 {
1200 rtSocketPollClearEventAndMakeBlocking(pThis);
1201 pThis->hPollSet = NIL_RTPOLLSET;
1202 }
1203 ASMAtomicDecU32(&pThis->cUsers);
1204 }
1205
1206 return fRetEvents;
1207}
1208
1209
1210/**
1211 * Called after a WaitForMultipleObjects returned in order to check for pending
1212 * events and stop whatever actions that rtSocketPollStart() initiated.
1213 *
1214 * @returns Event mask or 0.
1215 *
1216 * @param hSocket The socket handle.
1217 * @param fEvents The events we're polling for.
1218 * @param fFinalEntry Set if this is the final entry for this handle
1219 * in this poll set. This can be used for dealing
1220 * with duplicate entries. Only keep in mind that
1221 * this method is called in reverse order, so the
1222 * first call will have this set (when the entire
1223 * set was processed).
1224 */
1225uint32_t rtSocketPollDone(RTSOCKET hSocket, uint32_t fEvents, bool fFinalEntry)
1226{
1227 RTSOCKETINT *pThis = hSocket;
1228 AssertPtrReturn(pThis, 0);
1229 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, 0);
1230 Assert(pThis->cUsers > 0);
1231 Assert(pThis->hPollSet != NIL_RTPOLLSET);
1232
1233 /* Harvest events and clear the event mask for the next round of polling. */
1234 uint32_t fRetEvents = rtSocketPollCheck(pThis, fEvents);
1235 pThis->fPollEvts = 0;
1236
1237 /* Make the socket blocking again and unlock the handle. */
1238 if (pThis->cUsers == 1)
1239 {
1240 rtSocketPollClearEventAndMakeBlocking(pThis);
1241 pThis->hPollSet = NIL_RTPOLLSET;
1242 }
1243 ASMAtomicDecU32(&pThis->cUsers);
1244 return fRetEvents;
1245}
1246
1247#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