VirtualBox

source: vbox/trunk/src/VBox/Runtime/r3/tcp.cpp@ 27499

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

build fix

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 53.7 KB
Line 
1/* $Id: tcp.cpp 27499 2010-03-18 20:02:50Z vboxsync $ */
2/** @file
3 * IPRT - TCP/IP.
4 */
5
6/*
7 * Copyright (C) 2006-2010 Sun Microsystems, Inc.
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.215389.xyz. 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 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
27 * Clara, CA 95054 USA or visit http://www.sun.com if you need
28 * additional information or have any questions.
29 */
30
31
32/*******************************************************************************
33* Header Files *
34*******************************************************************************/
35#ifdef RT_OS_WINDOWS
36# include <winsock.h>
37#else /* !RT_OS_WINDOWS */
38# include <errno.h>
39# include <sys/stat.h>
40# include <sys/socket.h>
41# include <netinet/in.h>
42# include <netinet/tcp.h>
43# include <arpa/inet.h>
44# ifdef IPRT_WITH_TCPIP_V6
45# include <netinet6/in6.h>
46# endif
47# include <sys/un.h>
48# include <netdb.h>
49# include <unistd.h>
50# include <fcntl.h>
51#endif /* !RT_OS_WINDOWS */
52#include <limits.h>
53
54#include "internal/iprt.h"
55#include <iprt/tcp.h>
56
57#include <iprt/asm.h>
58#include <iprt/assert.h>
59#include <iprt/err.h>
60#include <iprt/mempool.h>
61#include <iprt/mem.h>
62#include <iprt/string.h>
63#include <iprt/thread.h>
64#include <iprt/time.h>
65
66#include "internal/magics.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#ifndef SHUT_RDWR
77# ifdef SD_BOTH
78# define SHUT_RDWR SD_BOTH
79# else
80# define SHUT_RDWR 2
81# endif
82#endif
83#ifndef SHUT_WR
84# ifdef SD_SEND
85# define SHUT_WR SD_SEND
86# else
87# define SHUT_WR 1
88# endif
89#endif
90
91/* fixup backlevel OSes. */
92#if defined(RT_OS_OS2) || defined(RT_OS_WINDOWS)
93# define socklen_t int
94#endif
95
96/** How many pending connection. */
97#define RTTCP_SERVER_BACKLOG 10
98
99
100/*******************************************************************************
101* Structures and Typedefs *
102*******************************************************************************/
103/**
104 * Socket handle data.
105 *
106 * This is mainly required for implementing RTPollSet on Windows.
107 */
108typedef struct RTSOCKETINT
109{
110 /** Magic number (RTTCPSOCKET_MAGIC). */
111 uint32_t u32Magic;
112 /** Usage count. This is used to prevent two threads from accessing the
113 * handle concurrently. */
114 uint32_t volatile cUsers;
115#ifdef RT_OS_WINDOWS
116 /** The native socket handle. */
117 SOCKET hNative;
118 /** The event semaphore we've associated with the socket handle.
119 * This is INVALID_HANDLE_VALUE if not done. */
120 WSAEVENT hEvent;
121 /** The pollset currently polling this socket. This is NIL if no one is
122 * polling. */
123 RTPOLLSET hPollSet;
124 /** The events we're polling for. */
125 uint32_t fPollEvts;
126#else
127 /** The native socket handle. */
128 int hNative;
129#endif
130} RTSOCKETINT;
131
132
133/**
134 * Address union used internally for things like getpeername and getsockname.
135 */
136typedef union RTSOCKADDRUNION
137{
138 struct sockaddr Addr;
139 struct sockaddr_in Ipv4;
140#ifdef IPRT_WITH_TCPIP_V6
141 struct sockaddr_in6 Ipv6;
142#endif
143} RTSOCKADDRUNION;
144
145
146
147/**
148 * TCP Server state.
149 */
150typedef enum RTTCPSERVERSTATE
151{
152 /** Invalid. */
153 RTTCPSERVERSTATE_INVALID = 0,
154 /** Created. */
155 RTTCPSERVERSTATE_CREATED,
156 /** Listener thread is starting up. */
157 RTTCPSERVERSTATE_STARTING,
158 /** Accepting client connections. */
159 RTTCPSERVERSTATE_ACCEPTING,
160 /** Serving a client. */
161 RTTCPSERVERSTATE_SERVING,
162 /** Listener terminating. */
163 RTTCPSERVERSTATE_STOPPING,
164 /** Listener terminated. */
165 RTTCPSERVERSTATE_STOPPED,
166 /** Listener cleans up. */
167 RTTCPSERVERSTATE_DESTROYING
168} RTTCPSERVERSTATE;
169
170/*
171 * Internal representation of the TCP Server handle.
172 */
173typedef struct RTTCPSERVER
174{
175 /** The magic value (RTTCPSERVER_MAGIC). */
176 uint32_t volatile u32Magic;
177 /** The server state. */
178 RTTCPSERVERSTATE volatile enmState;
179 /** The server thread. */
180 RTTHREAD Thread;
181 /** The server socket. */
182 RTSOCKET volatile SockServer;
183 /** The socket to the client currently being serviced.
184 * This is NIL_RTSOCKET when no client is serviced. */
185 RTSOCKET volatile SockClient;
186 /** The connection function. */
187 PFNRTTCPSERVE pfnServe;
188 /** Argument to pfnServer. */
189 void *pvUser;
190} RTTCPSERVER;
191
192
193/*******************************************************************************
194* Internal Functions *
195*******************************************************************************/
196static DECLCALLBACK(int) rtTcpServerThread(RTTHREAD ThreadSelf, void *pvServer);
197static int rtTcpServerListen(PRTTCPSERVER pServer);
198static int rtTcpServerListenCleanup(PRTTCPSERVER pServer);
199static int rtTcpServerDestroySocket(RTSOCKET volatile *pSockClient, const char *pszMsg);
200static int rtTcpClose(RTSOCKET Sock, const char *pszMsg, bool fTryGracefulShutdown);
201
202
203
204/**
205 * Get the last error as an iprt status code.
206 *
207 * @returns IPRT status code.
208 */
209DECLINLINE(int) rtSocketError(void)
210{
211#ifdef RT_OS_WINDOWS
212 return RTErrConvertFromWin32(WSAGetLastError());
213#else
214 return RTErrConvertFromErrno(errno);
215#endif
216}
217
218
219/**
220 * Resets the last error.
221 */
222DECLINLINE(void) rtSocketErrorReset(void)
223{
224#ifdef RT_OS_WINDOWS
225 WSASetLastError(0);
226#else
227 errno = 0;
228#endif
229}
230
231
232/**
233 * Get the last resolver error as an iprt status code.
234 *
235 * @returns iprt status code.
236 */
237DECLINLINE(int) rtSocketResolverError(void)
238{
239#ifdef RT_OS_WINDOWS
240 return RTErrConvertFromWin32(WSAGetLastError());
241#else
242 switch (h_errno)
243 {
244 case HOST_NOT_FOUND:
245 return VERR_NET_HOST_NOT_FOUND;
246 case NO_DATA:
247 return VERR_NET_ADDRESS_NOT_AVAILABLE;
248 case NO_RECOVERY:
249 return VERR_IO_GEN_FAILURE;
250 case TRY_AGAIN:
251 return VERR_TRY_AGAIN;
252
253 default:
254 return VERR_UNRESOLVED_ERROR;
255 }
256#endif
257}
258
259
260/**
261 * Tries to lock the socket for exclusive usage by the calling thread.
262 *
263 * Call rtSocketUnlock() to unlock.
264 *
265 * @returns @c true if locked, @c false if not.
266 * @param pThis The socket structure.
267 */
268DECLINLINE(bool) rtSocketTryLock(RTSOCKETINT *pThis)
269{
270 return ASMAtomicCmpXchgU32(&pThis->cUsers, 1, 0);
271}
272
273
274/**
275 * Unlocks the socket.
276 *
277 * @param pThis The socket structure.
278 */
279DECLINLINE(void) rtSocketUnlock(RTSOCKETINT *pThis)
280{
281 ASMAtomicCmpXchgU32(&pThis->cUsers, 0, 1);
282}
283
284
285/**
286 * Creates an IPRT socket handle for a native one.
287 *
288 * @returns IPRT status code.
289 * @param ppSocket Where to return the IPRT socket handle.
290 * @param hNative The native handle.
291 */
292int rtSocketCreateForNative(RTSOCKETINT **ppSocket,
293#ifdef RT_OS_WINDOWS
294 HANDLE hNative
295#else
296 int hNative
297#endif
298 )
299{
300 RTSOCKETINT *pThis = (RTSOCKETINT *)RTMemAlloc(sizeof(*pThis));
301 if (!pThis)
302 return VERR_NO_MEMORY;
303 pThis->u32Magic = RTSOCKET_MAGIC;
304 pThis->cUsers = 0;
305 pThis->hNative = hNative;
306#ifdef RT_OS_WINDOWS
307 pThis->hEvent = INVALID_HANDLE_VALUE;
308 pThis->hPollSet = 0;
309 pThis->fPollEvts = 0;
310#endif
311 *ppSocket = pThis;
312 return VINF_SUCCESS;
313}
314
315
316/**
317 * Wrapper around socket().
318 *
319 * @returns IPRT status code.
320 * @param phSocket Where to store the handle to the socket on
321 * success.
322 * @param iDomain The protocol family (PF_XXX).
323 * @param iType The socket type (SOCK_XXX).
324 * @param iProtocol Socket parameter, usually 0.
325 */
326static int rtSocketCreate(PRTSOCKET phSocket, int iDomain, int iType, int iProtocol)
327{
328 /*
329 * Create the socket.
330 */
331#ifdef RT_OS_WINDOWS
332 SOCKET hNative = socket(iDomain, iType, iProtocol);
333 if (hNative == INVALID_SOCKET)
334 return rtSocketError();
335#else
336 int hNative = socket(iDomain, iType, iProtocol);
337 if (hNative == -1)
338 return rtSocketError();
339#endif
340
341 /*
342 * Wrap it.
343 */
344 int rc = rtSocketCreateForNative(phSocket, hNative);
345 if (RT_FAILURE(rc))
346 {
347#ifdef RT_OS_WINDOWS
348 closesocket(hNative);
349#else
350 close(hNative);
351#endif
352 }
353 return rc;
354}
355
356
357/**
358 * Destroys the specified handle, freeing associated resources and closing the
359 * socket.
360 *
361 * @returns IPRT status code.
362 * @param hSocket The socket handle. NIL is ignored.
363 *
364 * @remarks This will not perform a graceful shutdown of the socket, it will
365 * just destroy it. Use the protocol specific close method if this is
366 * desired.
367 */
368int rtSocketDestroy(RTSOCKET hSocket)
369{
370 RTSOCKETINT *pThis = hSocket;
371 if (pThis == NIL_RTSOCKET)
372 return VINF_SUCCESS;
373 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
374 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
375
376 Assert(pThis->cUsers == 0);
377 AssertReturn(ASMAtomicCmpXchgU32(&pThis->u32Magic, RTSOCKET_MAGIC_DEAD, RTSOCKET_MAGIC), VERR_INVALID_HANDLE);
378
379 /*
380 * Do the cleanup.
381 */
382 int rc = VINF_SUCCESS;
383#ifdef RT_OS_WINDOWS
384 if (pThis->hEvent == INVALID_HANDLE_VALUE)
385 {
386 CloseHandle(pThis->hEvent);
387 pThis->hEvent = INVALID_HANDLE_VALUE;
388 }
389
390 if (pThis->hNative != INVALID_HANDLE_VALUE)
391 {
392 rc = closesocket(pThis->hNative);
393 if (!rc)
394 rc = VINF_SUCCESS;
395 else
396 {
397 rc = rtSocketError();
398 AssertMsgFailed(("\"%s\": closesocket(%p) -> %Rrc\n", pThis->hNative, rc));
399 }
400 pThis->hNative = INVALID_HANDLE_VALUE;
401 }
402
403#else
404 if (pThis->hNative != -1)
405 {
406 if (close(pThis->hNative))
407 {
408 rc = rtSocketError();
409 AssertMsgFailed(("\"%s\": close(%d) -> %Rrc\n", pThis->hNative, rc));
410 }
411 pThis->hNative = -1;
412 }
413#endif
414
415 return rc;
416}
417
418
419/**
420 * Gets the native socket handle.
421 *
422 * @returns The native socket handle or RTHCUINTPTR_MAX if not invalid.
423 * @param hSocket The socket handle.
424 */
425RTHCUINTPTR rtSocketNative(RTSOCKET hSocket)
426{
427 RTSOCKETINT *pThis = hSocket;
428 AssertPtrReturn(pThis, RTHCUINTPTR_MAX);
429 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, RTHCUINTPTR_MAX);
430 return (RTHCUINTPTR)pThis->hNative;
431}
432
433
434/**
435 * Helper that ensures the correct inheritability of a socket.
436 *
437 * We're currently ignoring failures.
438 *
439 * @returns IPRT status code
440 * @param hSocket The socket handle.
441 * @param fInheritable The desired inheritability state.
442 */
443int rtSocketSetInheritance(RTSOCKET hSocket, bool fInheritable)
444{
445 RTSOCKETINT *pThis = hSocket;
446 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
447 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
448 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
449
450 int rc = VINF_SUCCESS;
451#ifdef RT_OS_WINDOWS
452 if (!SetHandleInformation(pThis->hNative, HANDLE_FLAG_INHERIT, fInheritable ? HANDLE_FLAG_INHERIT : 0))
453 rc = RTErrConvertFromWin32(GetLastError());
454#else
455 if (fcntl(pThis->hNative, F_SETFD, fInheritable ? 0 : FD_CLOEXEC) < 0)
456 rc = RTErrConvertFromErrno(errno);
457#endif
458 AssertRC(rc); /// @todo remove later.
459
460 rtSocketUnlock(pThis);
461 return rc;
462}
463
464
465/**
466 * Receive data from a socket.
467 *
468 * @returns IPRT status code.
469 * @param hSocket The socket handle.
470 * @param pvBuffer Where to put the data we read.
471 * @param cbBuffer Read buffer size.
472 * @param pcbRead Number of bytes read. If NULL the entire buffer
473 * will be filled upon successful return. If not NULL a
474 * partial read can be done successfully.
475 */
476int rtSocketRead(RTSOCKET hSocket, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
477{
478 /*
479 * Validate input.
480 */
481 RTSOCKETINT *pThis = hSocket;
482 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
483 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
484 AssertReturn(cbBuffer > 0, VERR_INVALID_PARAMETER);
485 AssertPtr(pvBuffer);
486 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
487
488 /*
489 * Read loop.
490 * If pcbRead is NULL we have to fill the entire buffer!
491 */
492 int rc = VINF_SUCCESS;
493 size_t cbRead = 0;
494 size_t cbToRead = cbBuffer;
495 for (;;)
496 {
497 rtSocketErrorReset();
498#ifdef RT_OS_WINDOWS
499 int cbNow = cbToRead >= INT_MAX/2 ? INT_MAX/2 : (int)cbToRead;
500#else
501 size_t cbNow = cbToRead;
502#endif
503 ssize_t cbBytesRead = recv(pThis->hNative, (char *)pvBuffer + cbRead, cbNow, MSG_NOSIGNAL);
504 if (cbBytesRead <= 0)
505 {
506 rc = rtSocketError();
507 Assert(RT_FAILURE_NP(rc) || cbBytesRead == 0);
508 if (RT_SUCCESS_NP(rc))
509 {
510 if (!pcbRead)
511 rc = VERR_NET_SHUTDOWN;
512 else
513 {
514 *pcbRead = 0;
515 rc = VINF_SUCCESS;
516 }
517 }
518 break;
519 }
520 if (pcbRead)
521 {
522 /* return partial data */
523 *pcbRead = cbBytesRead;
524 break;
525 }
526
527 /* read more? */
528 cbRead += cbBytesRead;
529 if (cbRead == cbBuffer)
530 break;
531
532 /* next */
533 cbToRead = cbBuffer - cbRead;
534 }
535
536 rtSocketUnlock(pThis);
537 return rc;
538}
539
540
541/**
542 * Send data to a socket.
543 *
544 * @returns IPRT status code.
545 * @retval VERR_INTERRUPTED if interrupted before anything was written.
546 *
547 * @param hSocket The socket handle.
548 * @param pvBuffer Buffer to write data to socket.
549 * @param cbBuffer How much to write.
550 */
551int rtSocketWrite(RTSOCKET hSocket, const void *pvBuffer, size_t cbBuffer)
552{
553 /*
554 * Validate input.
555 */
556 RTSOCKETINT *pThis = hSocket;
557 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
558 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
559 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
560
561 /*
562 * Try write all at once.
563 */
564 int rc = VINF_SUCCESS;
565#ifdef RT_OS_WINDOWS
566 int cbNow = cbBuffer >= INT_MAX / 2 ? INT_MAX / 2 : (int)cbBuffer;
567#else
568 size_t cbNow = cbBuffer >= SSIZE_MAX ? SSIZE_MAX : cbBuffer;
569#endif
570 ssize_t cbWritten = send(pThis->hNative, (const char *)pvBuffer, cbNow, MSG_NOSIGNAL);
571 if (RT_LIKELY((size_t)cbWritten == cbBuffer && cbWritten >= 0))
572 rc = VINF_SUCCESS;
573 else if (cbWritten < 0)
574 rc = rtSocketError();
575 else
576 {
577 /*
578 * Unfinished business, write the remainder of the request. Must ignore
579 * VERR_INTERRUPTED here if we've managed to send something.
580 */
581 size_t cbSentSoFar = 0;
582 for (;;)
583 {
584 /* advance */
585 cbBuffer -= (size_t)cbWritten;
586 if (!cbBuffer)
587 break;
588 cbSentSoFar += (size_t)cbWritten;
589 pvBuffer = (char const *)pvBuffer + cbWritten;
590
591 /* send */
592#ifdef RT_OS_WINDOWS
593 cbNow = cbBuffer >= INT_MAX / 2 ? INT_MAX / 2 : (int)cbBuffer;
594#else
595 cbNow = cbBuffer >= SSIZE_MAX ? SSIZE_MAX : cbBuffer;
596#endif
597 cbWritten = send(pThis->hNative, (const char *)pvBuffer, cbNow, MSG_NOSIGNAL);
598 if (cbWritten >= 0)
599 AssertMsg(cbBuffer >= (size_t)cbWritten, ("Wrote more than we requested!!! cbWritten=%zu cbBuffer=%zu rtSocketError()=%d\n",
600 cbWritten, cbBuffer, rtSocketError()));
601 else
602 {
603 rc = rtSocketError();
604 if (rc != VERR_INTERNAL_ERROR || cbSentSoFar == 0)
605 break;
606 cbWritten = 0;
607 rc = VINF_SUCCESS;
608 }
609 }
610 }
611
612 rtSocketUnlock(pThis);
613 return rc;
614}
615
616
617/**
618 * Checks if the socket is ready for reading (for I/O multiplexing).
619 *
620 * @returns IPRT status code.
621 * @param hSocket The socket handle.
622 * @param cMillies Number of milliseconds to wait for the socket. Use
623 * RT_INDEFINITE_WAIT to wait for ever.
624 */
625int rtSocketSelectOne(RTSOCKET hSocket, RTMSINTERVAL cMillies)
626{
627 /*
628 * Validate input.
629 */
630 RTSOCKETINT *pThis = hSocket;
631 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
632 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
633 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
634
635 /*
636 * Set up the file descriptor sets and do the select.
637 */
638 fd_set fdsetR;
639 FD_ZERO(&fdsetR);
640 FD_SET(pThis->hNative, &fdsetR);
641
642 fd_set fdsetE = fdsetR;
643
644 int rc;
645 if (cMillies == RT_INDEFINITE_WAIT)
646 rc = select(pThis->hNative + 1, &fdsetR, NULL, &fdsetE, NULL);
647 else
648 {
649 struct timeval timeout;
650 timeout.tv_sec = cMillies / 1000;
651 timeout.tv_usec = (cMillies % 1000) * 1000;
652 rc = select(pThis->hNative + 1, &fdsetR, NULL, &fdsetE, &timeout);
653 }
654 if (rc > 0)
655 rc = VINF_SUCCESS;
656 else if (rc == 0)
657 rc = VERR_TIMEOUT;
658 else
659 rc = rtSocketError();
660
661 rtSocketUnlock(pThis);
662 return rc;
663}
664
665
666/**
667 * Shuts down one or both directions of communciation.
668 *
669 * @returns IPRT status code.
670 * @param hSocket The socket handle.
671 * @param fRead Whether to shutdown our read direction.
672 * @param fWrite Whether to shutdown our write direction.
673 */
674static int rtSocketShutdown(RTSOCKET hSocket, bool fRead, bool fWrite)
675{
676 /*
677 * Validate input.
678 */
679 RTSOCKETINT *pThis = hSocket;
680 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
681 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
682 AssertReturn(fRead || fWrite, VERR_INVALID_PARAMETER);
683 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
684
685 /*
686 * Do the job.
687 */
688 int rc = VINF_SUCCESS;
689 int fHow;
690 if (fRead && fWrite)
691 fHow = SHUT_RDWR;
692 else if (fRead)
693 fHow = SHUT_RD;
694 else
695 fHow = SHUT_WR;
696 if (shutdown(pThis->hNative, fHow) == -1)
697 rc = rtSocketError();
698
699 rtSocketUnlock(pThis);
700 return rc;
701}
702
703
704/**
705 * Converts from a native socket address to a generic IPRT network address.
706 *
707 * @returns IPRT status code.
708 * @param pSrc The source address.
709 * @param cbSrc The size of the source address.
710 * @param pAddr Where to return the generic IPRT network
711 * address.
712 */
713static int rtSocketConvertAddress(RTSOCKADDRUNION const *pSrc, size_t cbSrc, PRTNETADDR pAddr)
714{
715 /*
716 * Convert the address.
717 */
718 if ( cbSrc == sizeof(struct sockaddr_in)
719 && pSrc->Addr.sa_family == AF_INET)
720 {
721 RT_ZERO(*pAddr);
722 pAddr->enmType = RTNETADDRTYPE_IPV4;
723 pAddr->uPort = RT_N2H_U16(pSrc->Ipv4.sin_port);
724 pAddr->uAddr.IPv4.u = pSrc->Ipv4.sin_addr.s_addr;
725 }
726#ifdef IPRT_WITH_TCPIP_V6
727 else if ( cbSrc == sizeof(struct sockaddr_in6)
728 && pSrc->Addr.sa_family == AF_INET6)
729 {
730 RT_ZERO(*pAddr);
731 pAddr->enmType = RTNETADDRTYPE_IPV6;
732 pAddr->uPort = RT_N2H_U16(pSrc->Ipv6.sin6_port);
733 pAddr->uAddr.IPv6.au32[0] = pSrc->Ipv6.sin6_addr.s6_addr32[0];
734 pAddr->uAddr.IPv6.au32[1] = pSrc->Ipv6.sin6_addr.s6_addr32[1];
735 pAddr->uAddr.IPv6.au32[2] = pSrc->Ipv6.sin6_addr.s6_addr32[2];
736 pAddr->uAddr.IPv6.au32[3] = pSrc->Ipv6.sin6_addr.s6_addr32[3];
737 }
738#endif
739 else
740 return VERR_NET_ADDRESS_FAMILY_NOT_SUPPORTED;
741 return VINF_SUCCESS;
742}
743
744
745/**
746 * Gets the address of the local side.
747 *
748 * @returns IPRT status code.
749 * @param Sock Socket descriptor.
750 * @param pAddr Where to store the local address on success.
751 */
752int rtSocketGetLocalAddress(RTSOCKET hSocket, PRTNETADDR pAddr)
753{
754 /*
755 * Validate input.
756 */
757 RTSOCKETINT *pThis = hSocket;
758 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
759 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
760 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
761
762 /*
763 * Get the address and convert it.
764 */
765 int rc;
766 RTSOCKADDRUNION u;
767#ifdef RT_OS_WINDOWS
768 int cbAddr = sizeof(u);
769#else
770 socklen_t cbAddr = sizeof(u);
771#endif
772 RT_ZERO(u);
773 if (getsockname(pThis->hNative, &u.Addr, &cbAddr) == 0)
774 rc = rtSocketConvertAddress(&u, cbAddr, pAddr);
775 else
776 rc = rtSocketError();
777
778 rtSocketUnlock(pThis);
779 return rc;
780}
781
782
783/**
784 * Gets the address of the other party.
785 *
786 * @returns IPRT status code.
787 * @param Sock Socket descriptor.
788 * @param pAddr Where to store the peer address on success.
789 */
790int rtSocketGetPeerAddress(RTSOCKET hSocket, PRTNETADDR pAddr)
791{
792 /*
793 * Validate input.
794 */
795 RTSOCKETINT *pThis = hSocket;
796 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
797 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
798 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
799
800 /*
801 * Get the address and convert it.
802 */
803 int rc;
804 RTSOCKADDRUNION u;
805#ifdef RT_OS_WINDOWS
806 int cbAddr = sizeof(u);
807#else
808 socklen_t cbAddr = sizeof(u);
809#endif
810 RT_ZERO(u);
811 if (getpeername(pThis->hNative, &u.Addr, &cbAddr) == 0)
812 rc = rtSocketConvertAddress(&u, cbAddr, pAddr);
813 else
814 rc = rtSocketError();
815
816 rtSocketUnlock(pThis);
817 return rc;
818}
819
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 */
895 RTSOCKETINT *pThis = hSocket;
896 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
897 AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
898 AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
899
900 /*
901 * Call accept().
902 */
903 rtSocketErrorReset();
904 int rc = VINF_SUCCESS;
905#ifdef RT_OS_WINDOWS
906 int cbAddr = (int)*pcbAddr;
907 SOCKET hNative = accept(pThis->hNative, pAddr, &cbAddr);
908 if (hNative != INVALID_SOCKET)
909#else
910 socklen_t cbAddr = *pcbAddr;
911 int hNative = accept(pThis->hNative, pAddr, &cbAddr);
912 if (hNative != -1)
913#endif
914 {
915 *pcbAddr = cbAddr;
916
917 /*
918 * Wrap the client socket.
919 */
920 rc = rtSocketCreateForNative(phClient, hNative);
921 if (RT_FAILURE(rc))
922 {
923#ifdef RT_OS_WINDOWS
924 closesocket(hNative);
925#else
926 close(hNative);
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
995
996/////////////////////////////////////////////////////////////////////////////////
997/////////////////////////////////////////////////////////////////////////////////
998/////////////////////////////////////////////////////////////////////////////////
999/////////////////////////////////////////////////////////////////////////////////
1000/////////////////////////////////////////////////////////////////////////////////
1001
1002
1003
1004/**
1005 * Atomicly updates a socket variable.
1006 * @returns The old value.
1007 * @param pSock The socket variable to update.
1008 * @param Sock The new value.
1009 */
1010DECLINLINE(RTSOCKET) rtTcpAtomicXchgSock(RTSOCKET volatile *pSock, const RTSOCKET Sock)
1011{
1012 switch (sizeof(RTSOCKET))
1013 {
1014 case 4: return (RTSOCKET)ASMAtomicXchgS32((int32_t volatile *)pSock, (int32_t)(uintptr_t)Sock);
1015 case 8: return (RTSOCKET)ASMAtomicXchgS64((int64_t volatile *)pSock, (int64_t)(uintptr_t)Sock);
1016 default:
1017 AssertReleaseFailed();
1018 return NIL_RTSOCKET;
1019 }
1020}
1021
1022
1023/**
1024 * Tries to change the TCP server state.
1025 */
1026DECLINLINE(bool) rtTcpServerTrySetState(PRTTCPSERVER pServer, RTTCPSERVERSTATE enmStateNew, RTTCPSERVERSTATE enmStateOld)
1027{
1028 bool fRc;
1029 ASMAtomicCmpXchgSize(&pServer->enmState, enmStateNew, enmStateOld, fRc);
1030 return fRc;
1031}
1032
1033/**
1034 * Changes the TCP server state.
1035 */
1036DECLINLINE(void) rtTcpServerSetState(PRTTCPSERVER pServer, RTTCPSERVERSTATE enmStateNew, RTTCPSERVERSTATE enmStateOld)
1037{
1038 bool fRc;
1039 ASMAtomicCmpXchgSize(&pServer->enmState, enmStateNew, enmStateOld, fRc);
1040 Assert(fRc); NOREF(fRc);
1041}
1042
1043
1044/**
1045 * Closes the a socket (client or server).
1046 *
1047 * @returns IPRT status code.
1048 */
1049static int rtTcpServerDestroySocket(RTSOCKET volatile *pSock, const char *pszMsg, bool fTryGracefulShutdown)
1050{
1051 RTSOCKET hSocket = rtTcpAtomicXchgSock(pSock, NIL_RTSOCKET);
1052 if (hSocket != NIL_RTSOCKET)
1053 {
1054 if (!fTryGracefulShutdown)
1055 rtSocketShutdown(hSocket, true /*fRead*/, true /*fWrite*/);
1056 return rtTcpClose(hSocket, pszMsg, fTryGracefulShutdown);
1057 }
1058 return VINF_TCP_SERVER_NO_CLIENT;
1059}
1060
1061
1062/**
1063 * Create single connection at a time TCP Server in a separate thread.
1064 *
1065 * The thread will loop accepting connections and call pfnServe for
1066 * each of the incoming connections in turn. The pfnServe function can
1067 * return VERR_TCP_SERVER_STOP too terminate this loop. RTTcpServerDestroy()
1068 * should be used to terminate the server.
1069 *
1070 * @returns iprt status code.
1071 * @param pszAddress The address for creating a listening socket.
1072 * If NULL or empty string the server is bound to all interfaces.
1073 * @param uPort The port for creating a listening socket.
1074 * @param enmType The thread type.
1075 * @param pszThrdName The name of the worker thread.
1076 * @param pfnServe The function which will serve a new client connection.
1077 * @param pvUser User argument passed to pfnServe.
1078 * @param ppServer Where to store the serverhandle.
1079 */
1080RTR3DECL(int) RTTcpServerCreate(const char *pszAddress, unsigned uPort, RTTHREADTYPE enmType, const char *pszThrdName,
1081 PFNRTTCPSERVE pfnServe, void *pvUser, PPRTTCPSERVER ppServer)
1082{
1083 /*
1084 * Validate input.
1085 */
1086 AssertReturn(uPort > 0, VERR_INVALID_PARAMETER);
1087 AssertPtrReturn(pfnServe, VERR_INVALID_POINTER);
1088 AssertPtrReturn(pszThrdName, VERR_INVALID_POINTER);
1089 AssertPtrReturn(ppServer, VERR_INVALID_POINTER);
1090
1091 /*
1092 * Create the server.
1093 */
1094 PRTTCPSERVER pServer;
1095 int rc = RTTcpServerCreateEx(pszAddress, uPort, &pServer);
1096 if (RT_SUCCESS(rc))
1097 {
1098 /*
1099 * Create the listener thread.
1100 */
1101 RTMemPoolRetain(pServer);
1102 pServer->enmState = RTTCPSERVERSTATE_STARTING;
1103 pServer->pvUser = pvUser;
1104 pServer->pfnServe = pfnServe;
1105 rc = RTThreadCreate(&pServer->Thread, rtTcpServerThread, pServer, 0, enmType, /*RTTHREADFLAGS_WAITABLE*/0, pszThrdName);
1106 if (RT_SUCCESS(rc))
1107 {
1108 /* done */
1109 if (ppServer)
1110 *ppServer = pServer;
1111 else
1112 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
1113 return rc;
1114 }
1115 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
1116
1117 /*
1118 * Destroy the server.
1119 */
1120 rtTcpServerSetState(pServer, RTTCPSERVERSTATE_CREATED, RTTCPSERVERSTATE_STARTING);
1121 RTTcpServerDestroy(pServer);
1122 }
1123
1124 return rc;
1125}
1126
1127
1128/**
1129 * Server thread, loops accepting connections until it's terminated.
1130 *
1131 * @returns iprt status code. (ignored).
1132 * @param ThreadSelf Thread handle.
1133 * @param pvServer Server handle.
1134 */
1135static DECLCALLBACK(int) rtTcpServerThread(RTTHREAD ThreadSelf, void *pvServer)
1136{
1137 PRTTCPSERVER pServer = (PRTTCPSERVER)pvServer;
1138 int rc;
1139 if (rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_ACCEPTING, RTTCPSERVERSTATE_STARTING))
1140 rc = rtTcpServerListen(pServer);
1141 else
1142 rc = rtTcpServerListenCleanup(pServer);
1143 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
1144 NOREF(ThreadSelf);
1145 return VINF_SUCCESS;
1146}
1147
1148
1149/**
1150 * Create single connection at a time TCP Server.
1151 * The caller must call RTTcpServerListen() to actually start the server.
1152 *
1153 * @returns iprt status code.
1154 * @param pszAddress The address for creating a listening socket.
1155 * If NULL the server is bound to all interfaces.
1156 * @param uPort The port for creating a listening socket.
1157 * @param ppServer Where to store the serverhandle.
1158 */
1159RTR3DECL(int) RTTcpServerCreateEx(const char *pszAddress, uint32_t uPort, PPRTTCPSERVER ppServer)
1160{
1161 int rc;
1162
1163 /*
1164 * Validate input.
1165 */
1166 AssertReturn(uPort > 0, VERR_INVALID_PARAMETER);
1167 AssertPtrReturn(ppServer, VERR_INVALID_PARAMETER);
1168
1169#ifdef RT_OS_WINDOWS
1170 /*
1171 * Initialize WinSock and check version.
1172 */
1173 WORD wVersionRequested = MAKEWORD(1, 1);
1174 WSADATA wsaData;
1175 rc = WSAStartup(wVersionRequested, &wsaData);
1176 if (wsaData.wVersion != wVersionRequested)
1177 {
1178 AssertMsgFailed(("Wrong winsock version\n"));
1179 return VERR_NOT_SUPPORTED;
1180 }
1181#endif
1182
1183 /*
1184 * Get host listening address.
1185 */
1186 struct hostent *pHostEnt = NULL;
1187 if (pszAddress != NULL && *pszAddress)
1188 {
1189 pHostEnt = gethostbyname(pszAddress);
1190 if (!pHostEnt)
1191 {
1192 struct in_addr InAddr;
1193 InAddr.s_addr = inet_addr(pszAddress);
1194 pHostEnt = gethostbyaddr((char *)&InAddr, 4, AF_INET);
1195 if (!pHostEnt)
1196 {
1197 rc = rtSocketResolverError();
1198 AssertMsgFailed(("Could not get host address rc=%Rrc\n", rc));
1199 return rc;
1200 }
1201 }
1202 }
1203
1204 /*
1205 * Setting up socket.
1206 */
1207 RTSOCKET WaitSock;
1208 rc = rtSocketCreate(&WaitSock, AF_INET, SOCK_STREAM, IPPROTO_TCP);
1209 if (RT_SUCCESS(rc))
1210 {
1211 rtSocketSetInheritance(WaitSock, false /*fInheritable*/);
1212
1213 /*
1214 * Set socket options.
1215 */
1216 int fFlag = 1;
1217 if (!rtSocketSetOpt(WaitSock, SOL_SOCKET, SO_REUSEADDR, &fFlag, sizeof(fFlag)))
1218 {
1219 /*
1220 * Set socket family, address and port.
1221 */
1222 struct sockaddr_in LocalAddr;
1223 RT_ZERO(LocalAddr);
1224 LocalAddr.sin_family = AF_INET;
1225 LocalAddr.sin_port = htons(uPort);
1226 /* if address not specified, use INADDR_ANY. */
1227 if (!pHostEnt)
1228 LocalAddr.sin_addr.s_addr = INADDR_ANY;
1229 else
1230 LocalAddr.sin_addr = *((struct in_addr *)pHostEnt->h_addr);
1231
1232 /*
1233 * Bind a name to a socket and set it listening for connections.
1234 */
1235 rc = rtSocketBind(WaitSock, (struct sockaddr *)&LocalAddr, sizeof(LocalAddr));
1236 if (RT_SUCCESS(rc))
1237 rc = rtSocketListen(WaitSock, RTTCP_SERVER_BACKLOG);
1238 if (RT_SUCCESS(rc))
1239 {
1240 /*
1241 * Create the server handle.
1242 */
1243 PRTTCPSERVER pServer = (PRTTCPSERVER)RTMemPoolAlloc(RTMEMPOOL_DEFAULT, sizeof(*pServer));
1244 if (pServer)
1245 {
1246 pServer->u32Magic = RTTCPSERVER_MAGIC;
1247 pServer->enmState = RTTCPSERVERSTATE_CREATED;
1248 pServer->Thread = NIL_RTTHREAD;
1249 pServer->SockServer = WaitSock;
1250 pServer->SockClient = NIL_RTSOCKET;
1251 pServer->pfnServe = NULL;
1252 pServer->pvUser = NULL;
1253 *ppServer = pServer;
1254 return VINF_SUCCESS;
1255 }
1256
1257 /* bail out */
1258 rc = VERR_NO_MEMORY;
1259 }
1260 }
1261 else
1262 AssertMsgFailed(("rtSocketSetOpt: %Rrc\n", rc));
1263 rtTcpClose(WaitSock, "RTServerCreateEx", false /*fTryGracefulShutdown*/);
1264 }
1265
1266 return rc;
1267}
1268
1269
1270/**
1271 * Listen for incoming connections.
1272 *
1273 * The function will loop accepting connections and call pfnServe for
1274 * each of the incoming connections in turn. The pfnServe function can
1275 * return VERR_TCP_SERVER_STOP too terminate this loop. A stopped server
1276 * can only be destroyed.
1277 *
1278 * @returns IPRT status code.
1279 * @retval VERR_TCP_SERVER_STOP if stopped by pfnServe.
1280 * @retval VERR_TCP_SERVER_SHUTDOWN if shut down by RTTcpServerShutdown.
1281 *
1282 * @param pServer The server handle as returned from RTTcpServerCreateEx().
1283 * @param pfnServe The function which will serve a new client connection.
1284 * @param pvUser User argument passed to pfnServe.
1285 */
1286RTR3DECL(int) RTTcpServerListen(PRTTCPSERVER pServer, PFNRTTCPSERVE pfnServe, void *pvUser)
1287{
1288 /*
1289 * Validate input and retain the instance.
1290 */
1291 AssertPtrReturn(pfnServe, VERR_INVALID_POINTER);
1292 AssertPtrReturn(pServer, VERR_INVALID_HANDLE);
1293 AssertReturn(pServer->u32Magic == RTTCPSERVER_MAGIC, VERR_INVALID_HANDLE);
1294 AssertReturn(RTMemPoolRetain(pServer) != UINT32_MAX, VERR_INVALID_HANDLE);
1295
1296 int rc = VERR_INVALID_STATE;
1297 if (rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_ACCEPTING, RTTCPSERVERSTATE_CREATED))
1298 {
1299 Assert(!pServer->pfnServe);
1300 Assert(!pServer->pvUser);
1301 Assert(pServer->Thread == NIL_RTTHREAD);
1302 Assert(pServer->SockClient == NIL_RTSOCKET);
1303
1304 pServer->pfnServe = pfnServe;
1305 pServer->pvUser = pvUser;
1306 pServer->Thread = RTThreadSelf();
1307 Assert(pServer->Thread != NIL_RTTHREAD);
1308 rc = rtTcpServerListen(pServer);
1309 }
1310 else
1311 {
1312 AssertMsgFailed(("enmState=%d\n", pServer->enmState));
1313 rc = VERR_INVALID_STATE;
1314 }
1315 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
1316 return rc;
1317}
1318
1319
1320/**
1321 * Internal worker common for RTTcpServerListen and the thread created by
1322 * RTTcpServerCreate().
1323 *
1324 * The caller makes sure it has its own memory reference and releases it upon
1325 * return.
1326 */
1327static int rtTcpServerListen(PRTTCPSERVER pServer)
1328{
1329 /*
1330 * Accept connection loop.
1331 */
1332 for (;;)
1333 {
1334 /*
1335 * Change state.
1336 */
1337 RTTCPSERVERSTATE enmState = pServer->enmState;
1338 RTSOCKET SockServer = pServer->SockServer;
1339 if ( enmState != RTTCPSERVERSTATE_ACCEPTING
1340 && enmState != RTTCPSERVERSTATE_SERVING)
1341 return rtTcpServerListenCleanup(pServer);
1342 if (!rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_ACCEPTING, enmState))
1343 continue;
1344
1345 /*
1346 * Accept connection.
1347 */
1348 struct sockaddr_in RemoteAddr;
1349 size_t cbRemoteAddr = sizeof(RemoteAddr);
1350 RTSOCKET Socket;
1351 RT_ZERO(RemoteAddr);
1352 int rc = rtSocketAccept(SockServer, &Socket, (struct sockaddr *)&RemoteAddr, &cbRemoteAddr);
1353 if (RT_FAILURE(rc))
1354 {
1355 /* These are typical for what can happen during destruction. */
1356 if ( rc == VERR_INVALID_HANDLE
1357 || rc == VERR_INVALID_PARAMETER
1358 || rc == VERR_NET_NOT_SOCKET)
1359 return rtTcpServerListenCleanup(pServer);
1360 continue;
1361 }
1362 rtSocketSetInheritance(Socket, false /*fInheritable*/);
1363
1364 /*
1365 * Run a pfnServe callback.
1366 */
1367 if (!rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_SERVING, RTTCPSERVERSTATE_ACCEPTING))
1368 {
1369 rtTcpClose(Socket, "rtTcpServerListen", true /*fTryGracefulShutdown*/);
1370 return rtTcpServerListenCleanup(pServer);
1371 }
1372 rtTcpAtomicXchgSock(&pServer->SockClient, Socket);
1373 rc = pServer->pfnServe(Socket, pServer->pvUser);
1374 rtTcpServerDestroySocket(&pServer->SockClient, "Listener: client", true /*fTryGracefulShutdown*/);
1375
1376 /*
1377 * Stop the server?
1378 */
1379 if (rc == VERR_TCP_SERVER_STOP)
1380 {
1381 if (rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_STOPPING, RTTCPSERVERSTATE_SERVING))
1382 {
1383 /*
1384 * Reset the server socket and change the state to stopped. After that state change
1385 * we cannot safely access the handle so we'll have to return here.
1386 */
1387 SockServer = rtTcpAtomicXchgSock(&pServer->SockServer, NIL_RTSOCKET);
1388 rtTcpServerSetState(pServer, RTTCPSERVERSTATE_STOPPED, RTTCPSERVERSTATE_STOPPING);
1389 rtTcpClose(SockServer, "Listener: server stopped", false /*fTryGracefulShutdown*/);
1390 }
1391 else
1392 rtTcpServerListenCleanup(pServer); /* ignore rc */
1393 return rc;
1394 }
1395 }
1396}
1397
1398
1399/**
1400 * Clean up after listener.
1401 */
1402static int rtTcpServerListenCleanup(PRTTCPSERVER pServer)
1403{
1404 /*
1405 * Close the server socket, the client one shouldn't be set.
1406 */
1407 rtTcpServerDestroySocket(&pServer->SockServer, "ListenCleanup", false /*fTryGracefulShutdown*/);
1408 Assert(pServer->SockClient == NIL_RTSOCKET);
1409
1410 /*
1411 * Figure the return code and make sure the state is OK.
1412 */
1413 RTTCPSERVERSTATE enmState = pServer->enmState;
1414 switch (enmState)
1415 {
1416 case RTTCPSERVERSTATE_STOPPING:
1417 case RTTCPSERVERSTATE_STOPPED:
1418 return VERR_TCP_SERVER_SHUTDOWN;
1419
1420 case RTTCPSERVERSTATE_ACCEPTING:
1421 rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_STOPPED, enmState);
1422 return VERR_TCP_SERVER_DESTROYED;
1423
1424 case RTTCPSERVERSTATE_DESTROYING:
1425 return VERR_TCP_SERVER_DESTROYED;
1426
1427 case RTTCPSERVERSTATE_STARTING:
1428 case RTTCPSERVERSTATE_SERVING:
1429 default:
1430 AssertMsgFailedReturn(("pServer=%p enmState=%d\n", pServer, enmState), VERR_INTERNAL_ERROR_4);
1431 }
1432}
1433
1434
1435/**
1436 * Listen and accept one incomming connection.
1437 *
1438 * This is an alternative to RTTcpServerListen for the use the callbacks are not
1439 * possible.
1440 *
1441 * @returns IPRT status code.
1442 * @retval VERR_TCP_SERVER_SHUTDOWN if shut down by RTTcpServerShutdown.
1443 * @retval VERR_INTERRUPTED if the listening was interrupted.
1444 *
1445 * @param pServer The server handle as returned from RTTcpServerCreateEx().
1446 * @param pSockClient Where to return the socket handle to the client
1447 * connection (on success only). Use
1448 * RTTcpServerDisconnectClient() to clean it, this must
1449 * be done before the next call to RTTcpServerListen2.
1450 *
1451 * @todo This can easily be extended to support multiple connections by
1452 * adding a new state and a RTTcpServerDisconnectClient variant for
1453 * closing client sockets.
1454 */
1455RTR3DECL(int) RTTcpServerListen2(PRTTCPSERVER pServer, PRTSOCKET pSockClient)
1456{
1457 /*
1458 * Validate input and retain the instance.
1459 */
1460 AssertPtrReturn(pSockClient, VERR_INVALID_HANDLE);
1461 *pSockClient = NIL_RTSOCKET;
1462 AssertReturn(pServer->u32Magic == RTTCPSERVER_MAGIC, VERR_INVALID_HANDLE);
1463 AssertReturn(RTMemPoolRetain(pServer) != UINT32_MAX, VERR_INVALID_HANDLE);
1464
1465 int rc = VERR_INVALID_STATE;
1466 for (;;)
1467 {
1468 /*
1469 * Change state to accepting.
1470 */
1471 RTTCPSERVERSTATE enmState = pServer->enmState;
1472 RTSOCKET SockServer = pServer->SockServer;
1473 if ( enmState != RTTCPSERVERSTATE_SERVING
1474 && enmState != RTTCPSERVERSTATE_CREATED)
1475 {
1476 rc = rtTcpServerListenCleanup(pServer);
1477 break;
1478 }
1479 if (!rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_ACCEPTING, enmState))
1480 continue;
1481 Assert(!pServer->pfnServe);
1482 Assert(!pServer->pvUser);
1483 Assert(pServer->Thread == NIL_RTTHREAD);
1484 Assert(pServer->SockClient == NIL_RTSOCKET);
1485
1486 /*
1487 * Accept connection.
1488 */
1489 struct sockaddr_in RemoteAddr;
1490 size_t cbRemoteAddr = sizeof(RemoteAddr);
1491 RTSOCKET Socket;
1492 RT_ZERO(RemoteAddr);
1493 rc = rtSocketAccept(SockServer, &Socket, (struct sockaddr *)&RemoteAddr, &cbRemoteAddr);
1494 if (RT_FAILURE(rc))
1495 {
1496 if (!rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_CREATED, RTTCPSERVERSTATE_ACCEPTING))
1497 rc = rtTcpServerListenCleanup(pServer);
1498 if (RT_FAILURE(rc))
1499 break;
1500 continue;
1501 }
1502 rtSocketSetInheritance(Socket, false /*fInheritable*/);
1503
1504 /*
1505 * Chance to the 'serving' state and return the socket.
1506 */
1507 if (rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_SERVING, RTTCPSERVERSTATE_ACCEPTING))
1508 {
1509 RTSOCKET OldSocket = rtTcpAtomicXchgSock(&pServer->SockClient, Socket);
1510 Assert(OldSocket == NIL_RTSOCKET); NOREF(OldSocket);
1511 *pSockClient = Socket;
1512 rc = VINF_SUCCESS;
1513 }
1514 else
1515 {
1516 rtTcpClose(Socket, "RTTcpServerListen2", true /*fTryGracefulShutdown*/);
1517 rc = rtTcpServerListenCleanup(pServer);
1518 }
1519 break;
1520 }
1521
1522 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
1523 return rc;
1524}
1525
1526
1527/**
1528 * Terminate the open connection to the server.
1529 *
1530 * @returns iprt status code.
1531 * @param pServer Handle to the server.
1532 */
1533RTR3DECL(int) RTTcpServerDisconnectClient(PRTTCPSERVER pServer)
1534{
1535 /*
1536 * Validate input and retain the instance.
1537 */
1538 AssertPtrReturn(pServer, VERR_INVALID_HANDLE);
1539 AssertReturn(pServer->u32Magic == RTTCPSERVER_MAGIC, VERR_INVALID_HANDLE);
1540 AssertReturn(RTMemPoolRetain(pServer) != UINT32_MAX, VERR_INVALID_HANDLE);
1541
1542 int rc = rtTcpServerDestroySocket(&pServer->SockClient, "DisconnectClient: client", true /*fTryGracefulShutdown*/);
1543
1544 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
1545 return rc;
1546}
1547
1548
1549/**
1550 * Shuts down the server, leaving client connections open.
1551 *
1552 * @returns IPRT status code.
1553 * @param pServer Handle to the server.
1554 */
1555RTR3DECL(int) RTTcpServerShutdown(PRTTCPSERVER pServer)
1556{
1557 /*
1558 * Validate input and retain the instance.
1559 */
1560 AssertPtrReturn(pServer, VERR_INVALID_HANDLE);
1561 AssertReturn(pServer->u32Magic == RTTCPSERVER_MAGIC, VERR_INVALID_HANDLE);
1562 AssertReturn(RTMemPoolRetain(pServer) != UINT32_MAX, VERR_INVALID_HANDLE);
1563
1564 /*
1565 * Try change the state to stopping, then replace and destroy the server socket.
1566 */
1567 for (;;)
1568 {
1569 RTTCPSERVERSTATE enmState = pServer->enmState;
1570 if ( enmState != RTTCPSERVERSTATE_ACCEPTING
1571 && enmState != RTTCPSERVERSTATE_SERVING)
1572 {
1573 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
1574 switch (enmState)
1575 {
1576 case RTTCPSERVERSTATE_CREATED:
1577 case RTTCPSERVERSTATE_STARTING:
1578 default:
1579 AssertMsgFailed(("%d\n", enmState));
1580 return VERR_INVALID_STATE;
1581
1582 case RTTCPSERVERSTATE_STOPPING:
1583 case RTTCPSERVERSTATE_STOPPED:
1584 return VINF_SUCCESS;
1585
1586 case RTTCPSERVERSTATE_DESTROYING:
1587 return VERR_TCP_SERVER_DESTROYED;
1588 }
1589 }
1590 if (rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_STOPPING, enmState))
1591 {
1592 rtTcpServerDestroySocket(&pServer->SockServer, "RTTcpServerShutdown", false /*fTryGracefulShutdown*/);
1593 rtTcpServerSetState(pServer, RTTCPSERVERSTATE_STOPPED, RTTCPSERVERSTATE_STOPPING);
1594
1595 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
1596 return VINF_SUCCESS;
1597 }
1598 }
1599}
1600
1601
1602/**
1603 * Closes down and frees a TCP Server.
1604 * This will also terminate any open connections to the server.
1605 *
1606 * @returns iprt status code.
1607 * @param pServer Handle to the server.
1608 */
1609RTR3DECL(int) RTTcpServerDestroy(PRTTCPSERVER pServer)
1610{
1611 /*
1612 * Validate input and retain the instance.
1613 */
1614 AssertPtrReturn(pServer, VERR_INVALID_HANDLE);
1615 AssertReturn(pServer->u32Magic == RTTCPSERVER_MAGIC, VERR_INVALID_HANDLE);
1616 AssertReturn(RTMemPoolRetain(pServer) != UINT32_MAX, VERR_INVALID_HANDLE); /* paranoia */
1617
1618 /*
1619 * Move the state along so the listener can figure out what's going on.
1620 */
1621 for (;;)
1622 {
1623 bool fDestroyable;
1624 RTTCPSERVERSTATE enmState = pServer->enmState;
1625 switch (enmState)
1626 {
1627 case RTTCPSERVERSTATE_STARTING:
1628 case RTTCPSERVERSTATE_ACCEPTING:
1629 case RTTCPSERVERSTATE_SERVING:
1630 case RTTCPSERVERSTATE_CREATED:
1631 case RTTCPSERVERSTATE_STOPPED:
1632 fDestroyable = rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_DESTROYING, enmState);
1633 break;
1634
1635 /* destroyable states */
1636 case RTTCPSERVERSTATE_STOPPING:
1637 fDestroyable = true;
1638 break;
1639
1640 /*
1641 * Everything else means user or internal misbehavior.
1642 */
1643 default:
1644 AssertMsgFailed(("pServer=%p enmState=%d\n", pServer, enmState));
1645 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
1646 return VERR_INTERNAL_ERROR;
1647 }
1648 if (fDestroyable)
1649 break;
1650 }
1651
1652 /*
1653 * Destroy it.
1654 */
1655 ASMAtomicWriteU32(&pServer->u32Magic, ~RTTCPSERVER_MAGIC);
1656 rtTcpServerDestroySocket(&pServer->SockServer, "Destroyer: server", false /*fTryGracefulShutdown*/);
1657 rtTcpServerDestroySocket(&pServer->SockClient, "Destroyer: client", true /*fTryGracefulShutdown*/);
1658
1659 /*
1660 * Release it.
1661 */
1662 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
1663 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
1664 return VINF_SUCCESS;
1665}
1666
1667
1668RTR3DECL(int) RTTcpClientConnect(const char *pszAddress, uint32_t uPort, PRTSOCKET pSock)
1669{
1670 int rc;
1671
1672 /*
1673 * Validate input.
1674 */
1675 AssertReturn(uPort > 0, VERR_INVALID_PARAMETER);
1676 AssertPtrReturn(pszAddress, VERR_INVALID_POINTER);
1677
1678#ifdef RT_OS_WINDOWS
1679 /*
1680 * Initialize WinSock and check version.
1681 */
1682 WORD wVersionRequested = MAKEWORD(1, 1);
1683 WSADATA wsaData;
1684 rc = WSAStartup(wVersionRequested, &wsaData);
1685 if (wsaData.wVersion != wVersionRequested)
1686 {
1687 AssertMsgFailed(("Wrong winsock version\n"));
1688 return VERR_NOT_SUPPORTED;
1689 }
1690#endif
1691
1692 /*
1693 * Resolve the address.
1694 */
1695 struct hostent *pHostEnt = NULL;
1696 pHostEnt = gethostbyname(pszAddress);
1697 if (!pHostEnt)
1698 {
1699 struct in_addr InAddr;
1700 InAddr.s_addr = inet_addr(pszAddress);
1701 pHostEnt = gethostbyaddr((char *)&InAddr, 4, AF_INET);
1702 if (!pHostEnt)
1703 {
1704 rc = rtSocketError();
1705 AssertMsgFailed(("Could not resolve '%s', rc=%Rrc\n", pszAddress, rc));
1706 return rc;
1707 }
1708 }
1709
1710 /*
1711 * Create the socket and connect.
1712 */
1713 RTSOCKET Sock;
1714 rc = rtSocketCreate(&Sock, PF_INET, SOCK_STREAM, 0);
1715 if (RT_SUCCESS(rc))
1716 {
1717 rtSocketSetInheritance(Sock, false /*fInheritable*/);
1718
1719 struct sockaddr_in InAddr;
1720 RT_ZERO(InAddr);
1721 InAddr.sin_family = AF_INET;
1722 InAddr.sin_port = htons(uPort);
1723 InAddr.sin_addr = *((struct in_addr *)pHostEnt->h_addr);
1724 rc = rtSocketConnect(Sock, (struct sockaddr *)&InAddr, sizeof(InAddr));
1725 if (RT_SUCCESS(rc))
1726 {
1727 *pSock = Sock;
1728 return VINF_SUCCESS;
1729 }
1730
1731 rtTcpClose(Sock, "RTTcpClientConnect", false /*fTryGracefulShutdown*/);
1732 }
1733 return rc;
1734}
1735
1736
1737RTR3DECL(int) RTTcpClientClose(RTSOCKET Sock)
1738{
1739 return rtTcpClose(Sock, "RTTcpClientClose", true /*fTryGracefulShutdown*/);
1740}
1741
1742
1743/**
1744 * Internal close function which does all the proper bitching.
1745 */
1746static int rtTcpClose(RTSOCKET Sock, const char *pszMsg, bool fTryGracefulShutdown)
1747{
1748 int rc;
1749
1750 /* ignore nil handles. */
1751 if (Sock == NIL_RTSOCKET)
1752 return VINF_SUCCESS;
1753
1754 /*
1755 * Try to gracefully shut it down.
1756 */
1757 if (fTryGracefulShutdown)
1758 {
1759 rc = rtSocketShutdown(Sock, false /*fRead*/, true /*fWrite*/);
1760 if (RT_SUCCESS(rc))
1761 {
1762 uint64_t u64Start = RTTimeMilliTS();
1763 for (;;)
1764 {
1765 rc = rtSocketSelectOne(Sock, 1000);
1766 if (rc == VERR_TIMEOUT)
1767 {
1768 if (RTTimeMilliTS() - u64Start > 30000)
1769 break;
1770 }
1771 else if (rc != VINF_SUCCESS)
1772 break;
1773 {
1774 char abBitBucket[16*_1K];
1775 ssize_t cbBytesRead = recv(rtSocketNative(Sock), &abBitBucket[0], sizeof(abBitBucket), MSG_NOSIGNAL);
1776 if (cbBytesRead == 0)
1777 break; /* orderly shutdown in progress */
1778 if (cbBytesRead < 0)
1779 break; /* some kind of error, never mind which... */
1780 }
1781 } /* forever */
1782 }
1783 }
1784
1785 /*
1786 * Destroy the socket handle.
1787 */
1788 return rtSocketDestroy(Sock);
1789}
1790
1791
1792RTR3DECL(int) RTTcpRead(RTSOCKET Sock, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
1793{
1794 return rtSocketRead(Sock, pvBuffer, cbBuffer, pcbRead);
1795}
1796
1797
1798RTR3DECL(int) RTTcpWrite(RTSOCKET Sock, const void *pvBuffer, size_t cbBuffer)
1799{
1800 return rtSocketWrite(Sock, pvBuffer, cbBuffer);
1801}
1802
1803
1804RTR3DECL(int) RTTcpFlush(RTSOCKET Sock)
1805{
1806
1807 int fFlag = 1;
1808 int rc = rtSocketSetOpt(Sock, IPPROTO_TCP, TCP_NODELAY, &fFlag, sizeof(fFlag));
1809 if (RT_SUCCESS(rc))
1810 {
1811 fFlag = 0;
1812 rc = rtSocketSetOpt(Sock, IPPROTO_TCP, TCP_NODELAY, &fFlag, sizeof(fFlag));
1813 }
1814 return rc;
1815}
1816
1817
1818RTR3DECL(int) RTTcpSelectOne(RTSOCKET Sock, RTMSINTERVAL cMillies)
1819{
1820 return rtSocketSelectOne(Sock, cMillies);
1821}
1822
1823
1824RTR3DECL(int) RTTcpGetLocalAddress(RTSOCKET Sock, PRTNETADDR pAddr)
1825{
1826 return rtSocketGetLocalAddress(Sock, pAddr);
1827}
1828
1829
1830RTR3DECL(int) RTTcpGetPeerAddress(RTSOCKET Sock, PRTNETADDR pAddr)
1831{
1832 return rtSocketGetPeerAddress(Sock, pAddr);
1833}
1834
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