VirtualBox

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

最後變更 在這個檔案從30270是 30270,由 vboxsync 提交於 15 年 前

Runtime/tcp+socket: Add function to write to a socket using a scatter/gather buffer

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

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