VirtualBox

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

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

Runtime/tcp: new function to query the local address of a socket.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 36.8 KB
Line 
1/* $Id: tcp.cpp 26915 2010-03-01 14:50:21Z 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.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 * 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#endif /* !RT_OS_WINDOWS */
51#include <limits.h>
52
53#include "internal/iprt.h"
54#include <iprt/tcp.h>
55
56#include <iprt/asm.h>
57#include <iprt/assert.h>
58#include <iprt/err.h>
59#include <iprt/mempool.h>
60#include <iprt/string.h>
61#include <iprt/thread.h>
62#include <iprt/time.h>
63
64#include "internal/magics.h"
65
66
67/*******************************************************************************
68* Defined Constants And Macros *
69*******************************************************************************/
70/* non-standard linux stuff (it seems). */
71#ifndef MSG_NOSIGNAL
72# define MSG_NOSIGNAL 0
73#endif
74#ifndef SHUT_RDWR
75# ifdef SD_BOTH
76# define SHUT_RDWR SD_BOTH
77# else
78# define SHUT_RDWR 2
79# endif
80#endif
81#ifndef SHUT_WR
82# ifdef SD_SEND
83# define SHUT_WR SD_SEND
84# else
85# define SHUT_WR 1
86# endif
87#endif
88
89/* fixup backlevel OSes. */
90#if defined(RT_OS_OS2) || defined(RT_OS_WINDOWS)
91# define socklen_t int
92#endif
93
94/** How many pending connection. */
95#define RTTCP_SERVER_BACKLOG 10
96
97
98/*******************************************************************************
99* Structures and Typedefs *
100*******************************************************************************/
101/**
102 * TCP Server state.
103 */
104typedef enum RTTCPSERVERSTATE
105{
106 /** Invalid. */
107 RTTCPSERVERSTATE_INVALID = 0,
108 /** Created. */
109 RTTCPSERVERSTATE_CREATED,
110 /** Listener thread is starting up. */
111 RTTCPSERVERSTATE_STARTING,
112 /** Accepting client connections. */
113 RTTCPSERVERSTATE_ACCEPTING,
114 /** Serving a client. */
115 RTTCPSERVERSTATE_SERVING,
116 /** Listener terminating. */
117 RTTCPSERVERSTATE_STOPPING,
118 /** Listener terminated. */
119 RTTCPSERVERSTATE_STOPPED,
120 /** Listener cleans up. */
121 RTTCPSERVERSTATE_DESTROYING
122} RTTCPSERVERSTATE;
123
124/*
125 * Internal representation of the TCP Server handle.
126 */
127typedef struct RTTCPSERVER
128{
129 /** The magic value (RTTCPSERVER_MAGIC). */
130 uint32_t volatile u32Magic;
131 /** The server state. */
132 RTTCPSERVERSTATE volatile enmState;
133 /** The server thread. */
134 RTTHREAD Thread;
135 /** The server socket. */
136 RTSOCKET volatile SockServer;
137 /** The socket to the client currently being serviced.
138 * This is NIL_RTSOCKET when no client is serviced. */
139 RTSOCKET volatile SockClient;
140 /** The connection function. */
141 PFNRTTCPSERVE pfnServe;
142 /** Argument to pfnServer. */
143 void *pvUser;
144} RTTCPSERVER;
145
146typedef union RTSOCKADDRUNION
147{
148 struct sockaddr Addr;
149 struct sockaddr_in Ipv4;
150#ifdef IPRT_WITH_TCPIP_V6
151 struct sockaddr_in6 Ipv6;
152#endif
153} RTSOCKADDRUNION;
154
155/*******************************************************************************
156* Internal Functions *
157*******************************************************************************/
158static DECLCALLBACK(int) rtTcpServerThread(RTTHREAD ThreadSelf, void *pvServer);
159static int rtTcpServerListen(PRTTCPSERVER pServer);
160static int rcTcpServerListenCleanup(PRTTCPSERVER pServer);
161static int rtTcpServerDestroySocket(RTSOCKET volatile *pSockClient, const char *pszMsg);
162static int rtTcpClose(RTSOCKET Sock, const char *pszMsg, bool fTryGracefulShutdown);
163static int rtTcpConvertAddress(RTSOCKADDRUNION *pSrc, size_t cbSrc, PRTNETADDR pAddr);
164
165
166
167/**
168 * Get the last error as an iprt status code.
169 *
170 * @returns iprt status code.
171 */
172DECLINLINE(int) rtTcpError(void)
173{
174#ifdef RT_OS_WINDOWS
175 return RTErrConvertFromWin32(WSAGetLastError());
176#else
177 return RTErrConvertFromErrno(errno);
178#endif
179}
180
181
182/**
183 * Resets the last error.
184 */
185DECLINLINE(void) rtTcpErrorReset(void)
186{
187#ifdef RT_OS_WINDOWS
188 WSASetLastError(0);
189#else
190 errno = 0;
191#endif
192}
193
194
195/**
196 * Get the last resolver error as an iprt status code.
197 *
198 * @returns iprt status code.
199 */
200DECLINLINE(int) rtTcpResolverError(void)
201{
202#ifdef RT_OS_WINDOWS
203 return RTErrConvertFromWin32(WSAGetLastError());
204#else
205 switch (h_errno)
206 {
207 case HOST_NOT_FOUND:
208 return VERR_NET_HOST_NOT_FOUND;
209 case NO_DATA:
210 return VERR_NET_ADDRESS_NOT_AVAILABLE;
211 case NO_RECOVERY:
212 return VERR_IO_GEN_FAILURE;
213 case TRY_AGAIN:
214 return VERR_TRY_AGAIN;
215
216 default:
217 return VERR_UNRESOLVED_ERROR;
218 }
219#endif
220}
221
222
223/**
224 * Atomicly updates a socket variable.
225 * @returns The old value.
226 * @param pSock The socket variable to update.
227 * @param Sock The new value.
228 */
229DECLINLINE(RTSOCKET) rtTcpAtomicXchgSock(RTSOCKET volatile *pSock, const RTSOCKET Sock)
230{
231 switch (sizeof(RTSOCKET))
232 {
233 case 4: return (RTSOCKET)ASMAtomicXchgS32((int32_t volatile *)pSock, (int32_t)Sock);
234 default:
235 AssertReleaseFailed();
236 return NIL_RTSOCKET;
237 }
238}
239
240
241/**
242 * Tries to change the TCP server state.
243 */
244DECLINLINE(bool) rtTcpServerTrySetState(PRTTCPSERVER pServer, RTTCPSERVERSTATE enmStateNew, RTTCPSERVERSTATE enmStateOld)
245{
246 bool fRc;
247 ASMAtomicCmpXchgSize(&pServer->enmState, enmStateNew, enmStateOld, fRc);
248 return fRc;
249}
250
251/**
252 * Changes the TCP server state.
253 */
254DECLINLINE(void) rtTcpServerSetState(PRTTCPSERVER pServer, RTTCPSERVERSTATE enmStateNew, RTTCPSERVERSTATE enmStateOld)
255{
256 bool fRc;
257 ASMAtomicCmpXchgSize(&pServer->enmState, enmStateNew, enmStateOld, fRc);
258 Assert(fRc); NOREF(fRc);
259}
260
261/**
262 * Closes the a socket (client or server).
263 *
264 * @returns IPRT status code.
265 */
266static int rtTcpServerDestroySocket(RTSOCKET volatile *pSock, const char *pszMsg, bool fTryGracefulShutdown)
267{
268 RTSOCKET Sock = rtTcpAtomicXchgSock(pSock, NIL_RTSOCKET);
269 if (Sock != NIL_RTSOCKET)
270 {
271 if (!fTryGracefulShutdown)
272 shutdown(Sock, SHUT_RDWR);
273 return rtTcpClose(Sock, pszMsg, fTryGracefulShutdown);
274 }
275 return VINF_TCP_SERVER_NO_CLIENT;
276}
277
278
279/**
280 * Create single connection at a time TCP Server in a separate thread.
281 *
282 * The thread will loop accepting connections and call pfnServe for
283 * each of the incoming connections in turn. The pfnServe function can
284 * return VERR_TCP_SERVER_STOP too terminate this loop. RTTcpServerDestroy()
285 * should be used to terminate the server.
286 *
287 * @returns iprt status code.
288 * @param pszAddress The address for creating a listening socket.
289 * If NULL or empty string the server is bound to all interfaces.
290 * @param uPort The port for creating a listening socket.
291 * @param enmType The thread type.
292 * @param pszThrdName The name of the worker thread.
293 * @param pfnServe The function which will serve a new client connection.
294 * @param pvUser User argument passed to pfnServe.
295 * @param ppServer Where to store the serverhandle.
296 */
297RTR3DECL(int) RTTcpServerCreate(const char *pszAddress, unsigned uPort, RTTHREADTYPE enmType, const char *pszThrdName,
298 PFNRTTCPSERVE pfnServe, void *pvUser, PPRTTCPSERVER ppServer)
299{
300 /*
301 * Validate input.
302 */
303 AssertReturn(uPort > 0, VERR_INVALID_PARAMETER);
304 AssertPtrReturn(pfnServe, VERR_INVALID_POINTER);
305 AssertPtrReturn(pszThrdName, VERR_INVALID_POINTER);
306 AssertPtrReturn(ppServer, VERR_INVALID_POINTER);
307
308 /*
309 * Create the server.
310 */
311 PRTTCPSERVER pServer;
312 int rc = RTTcpServerCreateEx(pszAddress, uPort, &pServer);
313 if (RT_SUCCESS(rc))
314 {
315 /*
316 * Create the listener thread.
317 */
318 RTMemPoolRetain(pServer);
319 pServer->enmState = RTTCPSERVERSTATE_STARTING;
320 pServer->pvUser = pvUser;
321 pServer->pfnServe = pfnServe;
322 rc = RTThreadCreate(&pServer->Thread, rtTcpServerThread, pServer, 0, enmType, /*RTTHREADFLAGS_WAITABLE*/0, pszThrdName);
323 if (RT_SUCCESS(rc))
324 {
325 /* done */
326 if (ppServer)
327 *ppServer = pServer;
328 else
329 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
330 return rc;
331 }
332 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
333
334 /*
335 * Destroy the server.
336 */
337 rtTcpServerSetState(pServer, RTTCPSERVERSTATE_CREATED, RTTCPSERVERSTATE_STARTING);
338 RTTcpServerDestroy(pServer);
339 }
340
341 return rc;
342}
343
344
345/**
346 * Server thread, loops accepting connections until it's terminated.
347 *
348 * @returns iprt status code. (ignored).
349 * @param ThreadSelf Thread handle.
350 * @param pvServer Server handle.
351 */
352static DECLCALLBACK(int) rtTcpServerThread(RTTHREAD ThreadSelf, void *pvServer)
353{
354 PRTTCPSERVER pServer = (PRTTCPSERVER)pvServer;
355 int rc;
356 if (rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_ACCEPTING, RTTCPSERVERSTATE_STARTING))
357 rc = rtTcpServerListen(pServer);
358 else
359 rc = rcTcpServerListenCleanup(pServer);
360 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
361 NOREF(ThreadSelf);
362 return VINF_SUCCESS;
363}
364
365
366/**
367 * Create single connection at a time TCP Server.
368 * The caller must call RTTcpServerListen() to actually start the server.
369 *
370 * @returns iprt status code.
371 * @param pszAddress The address for creating a listening socket.
372 * If NULL the server is bound to all interfaces.
373 * @param uPort The port for creating a listening socket.
374 * @param ppServer Where to store the serverhandle.
375 */
376RTR3DECL(int) RTTcpServerCreateEx(const char *pszAddress, uint32_t uPort, PPRTTCPSERVER ppServer)
377{
378 int rc;
379
380 /*
381 * Validate input.
382 */
383 AssertReturn(uPort > 0, VERR_INVALID_PARAMETER);
384 AssertPtrReturn(ppServer, VERR_INVALID_PARAMETER);
385
386#ifdef RT_OS_WINDOWS
387 /*
388 * Initialize WinSock and check version.
389 */
390 WORD wVersionRequested = MAKEWORD(1, 1);
391 WSADATA wsaData;
392 rc = WSAStartup(wVersionRequested, &wsaData);
393 if (wsaData.wVersion != wVersionRequested)
394 {
395 AssertMsgFailed(("Wrong winsock version\n"));
396 return VERR_NOT_SUPPORTED;
397 }
398#endif
399
400 /*
401 * Get host listening address.
402 */
403 struct hostent *pHostEnt = NULL;
404 if (pszAddress != NULL && *pszAddress)
405 {
406 pHostEnt = gethostbyname(pszAddress);
407 if (!pHostEnt)
408 {
409 struct in_addr InAddr;
410 InAddr.s_addr = inet_addr(pszAddress);
411 pHostEnt = gethostbyaddr((char *)&InAddr, 4, AF_INET);
412 if (!pHostEnt)
413 {
414 rc = rtTcpResolverError();
415 AssertMsgFailed(("Could not get host address rc=%Rrc\n", rc));
416 return rc;
417 }
418 }
419 }
420
421 /*
422 * Setting up socket.
423 */
424 RTSOCKET WaitSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
425 if (WaitSock != -1)
426 {
427 /*
428 * Set socket options.
429 */
430 int fFlag = 1;
431 if (!setsockopt(WaitSock, SOL_SOCKET, SO_REUSEADDR, (const char *)&fFlag, sizeof(fFlag)))
432 {
433 /*
434 * Set socket family, address and port.
435 */
436 struct sockaddr_in LocalAddr;
437 RT_ZERO(LocalAddr);
438 LocalAddr.sin_family = AF_INET;
439 LocalAddr.sin_port = htons(uPort);
440 /* if address not specified, use INADDR_ANY. */
441 if (!pHostEnt)
442 LocalAddr.sin_addr.s_addr = INADDR_ANY;
443 else
444 LocalAddr.sin_addr = *((struct in_addr *)pHostEnt->h_addr);
445
446 /*
447 * Bind a name to a socket.
448 */
449 if (bind(WaitSock, (struct sockaddr *)&LocalAddr, sizeof(LocalAddr)) != -1)
450 {
451 /*
452 * Listen for connections on a socket.
453 */
454 if (listen(WaitSock, RTTCP_SERVER_BACKLOG) != -1)
455 {
456 /*
457 * Create the server handle.
458 */
459 PRTTCPSERVER pServer = (PRTTCPSERVER)RTMemPoolAlloc(RTMEMPOOL_DEFAULT, sizeof(*pServer));
460 if (pServer)
461 {
462 pServer->u32Magic = RTTCPSERVER_MAGIC;
463 pServer->enmState = RTTCPSERVERSTATE_CREATED;
464 pServer->Thread = NIL_RTTHREAD;
465 pServer->SockServer = WaitSock;
466 pServer->SockClient = NIL_RTSOCKET;
467 pServer->pfnServe = NULL;
468 pServer->pvUser = NULL;
469 *ppServer = pServer;
470 return VINF_SUCCESS;
471 }
472
473 /* bail out */
474 rc = VERR_NO_MEMORY;
475 }
476 else
477 {
478 rc = rtTcpError();
479 AssertMsgFailed(("listen() %Rrc\n", rc));
480 }
481 }
482 else
483 {
484 rc = rtTcpError();
485 }
486 }
487 else
488 {
489 rc = rtTcpError();
490 AssertMsgFailed(("setsockopt() %Rrc\n", rc));
491 }
492 rtTcpClose(WaitSock, "RTServerCreateEx", false /*fTryGracefulShutdown*/);
493 }
494 else
495 {
496 rc = rtTcpError();
497 AssertMsgFailed(("socket() %Rrc\n", rc));
498 }
499
500 return rc;
501}
502
503
504/**
505 * Listen for incoming connections.
506 *
507 * The function will loop accepting connections and call pfnServe for
508 * each of the incoming connections in turn. The pfnServe function can
509 * return VERR_TCP_SERVER_STOP too terminate this loop. A stopped server
510 * can only be destroyed.
511 *
512 * @returns IPRT status code.
513 * @retval VERR_TCP_SERVER_STOP if stopped by pfnServe.
514 * @retval VERR_TCP_SERVER_SHUTDOWN if shut down by RTTcpServerShutdown.
515 *
516 * @param pServer The server handle as returned from RTTcpServerCreateEx().
517 * @param pfnServe The function which will serve a new client connection.
518 * @param pvUser User argument passed to pfnServe.
519 */
520RTR3DECL(int) RTTcpServerListen(PRTTCPSERVER pServer, PFNRTTCPSERVE pfnServe, void *pvUser)
521{
522 /*
523 * Validate input and retain the instance.
524 */
525 AssertPtrReturn(pfnServe, VERR_INVALID_POINTER);
526 AssertPtrReturn(pServer, VERR_INVALID_HANDLE);
527 AssertReturn(pServer->u32Magic == RTTCPSERVER_MAGIC, VERR_INVALID_HANDLE);
528 AssertReturn(RTMemPoolRetain(pServer) != UINT32_MAX, VERR_INVALID_HANDLE);
529
530 int rc = VERR_INVALID_STATE;
531 if (rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_ACCEPTING, RTTCPSERVERSTATE_CREATED))
532 {
533 Assert(!pServer->pfnServe);
534 Assert(!pServer->pvUser);
535 Assert(pServer->Thread == NIL_RTTHREAD);
536 Assert(pServer->SockClient == NIL_RTSOCKET);
537
538 pServer->pfnServe = pfnServe;
539 pServer->pvUser = pvUser;
540 pServer->Thread = RTThreadSelf();
541 Assert(pServer->Thread != NIL_RTTHREAD);
542 rc = rtTcpServerListen(pServer);
543 }
544 else
545 {
546 AssertMsgFailed(("enmState=%d\n", pServer->enmState));
547 rc = VERR_INVALID_STATE;
548 }
549 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
550 return rc;
551}
552
553
554/**
555 * Internal worker common for RTTcpServerListen and the thread created by
556 * RTTcpServerCreate().
557 *
558 * The caller makes sure it has its own memory reference and releases it upon
559 * return.
560 */
561static int rtTcpServerListen(PRTTCPSERVER pServer)
562{
563 /*
564 * Accept connection loop.
565 */
566 for (;;)
567 {
568 /*
569 * Change state.
570 */
571 RTTCPSERVERSTATE enmState = pServer->enmState;
572 RTSOCKET SockServer = pServer->SockServer;
573 if ( enmState != RTTCPSERVERSTATE_ACCEPTING
574 && enmState != RTTCPSERVERSTATE_SERVING)
575 return rcTcpServerListenCleanup(pServer);
576 if (!rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_ACCEPTING, enmState))
577 continue;
578
579 /*
580 * Accept connection.
581 */
582 struct sockaddr_in RemoteAddr;
583 RT_ZERO(RemoteAddr);
584 socklen_t cbRemoteAddr = sizeof(RemoteAddr);
585 RTSOCKET Socket = accept(SockServer, (struct sockaddr *)&RemoteAddr, &cbRemoteAddr);
586 if (Socket == -1)
587 {
588#ifndef RT_OS_WINDOWS
589 /* These are typical for what can happen during destruction. */
590 if (errno == EBADF || errno == EINVAL || errno == ENOTSOCK)
591 return rcTcpServerListenCleanup(pServer);
592#endif
593 continue;
594 }
595
596 /*
597 * Run a pfnServe callback.
598 */
599 if (!rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_SERVING, RTTCPSERVERSTATE_ACCEPTING))
600 {
601 rtTcpClose(Socket, "rtTcpServerListen", true /*fTryGracefulShutdown*/);
602 return rcTcpServerListenCleanup(pServer);
603 }
604 rtTcpAtomicXchgSock(&pServer->SockClient, Socket);
605 int rc = pServer->pfnServe(Socket, pServer->pvUser);
606 rtTcpServerDestroySocket(&pServer->SockClient, "Listener: client", true /*fTryGracefulShutdown*/);
607
608 /*
609 * Stop the server?
610 */
611 if (rc == VERR_TCP_SERVER_STOP)
612 {
613 if (rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_STOPPING, RTTCPSERVERSTATE_SERVING))
614 {
615 /*
616 * Reset the server socket and change the state to stopped. After that state change
617 * we cannot safely access the handle so we'll have to return here.
618 */
619 SockServer = rtTcpAtomicXchgSock(&pServer->SockServer, NIL_RTSOCKET);
620 rtTcpServerSetState(pServer, RTTCPSERVERSTATE_STOPPED, RTTCPSERVERSTATE_STOPPING);
621 rtTcpClose(SockServer, "Listener: server stopped", false /*fTryGracefulShutdown*/);
622 }
623 else
624 rcTcpServerListenCleanup(pServer); /* ignore rc */
625 return rc;
626 }
627 }
628}
629
630
631/**
632 * Clean up after listener.
633 */
634static int rcTcpServerListenCleanup(PRTTCPSERVER pServer)
635{
636 /*
637 * Close the server socket, the client one shouldn't be set.
638 */
639 rtTcpServerDestroySocket(&pServer->SockServer, "ListenCleanup", false /*fTryGracefulShutdown*/);
640 Assert(pServer->SockClient == NIL_RTSOCKET);
641
642 /*
643 * Figure the return code and make sure the state is OK.
644 */
645 RTTCPSERVERSTATE enmState = pServer->enmState;
646 switch (enmState)
647 {
648 case RTTCPSERVERSTATE_STOPPING:
649 case RTTCPSERVERSTATE_STOPPED:
650 return VERR_TCP_SERVER_SHUTDOWN;
651
652 case RTTCPSERVERSTATE_ACCEPTING:
653 rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_STOPPED, enmState);
654 return VERR_TCP_SERVER_DESTROYED;
655
656 case RTTCPSERVERSTATE_DESTROYING:
657 return VERR_TCP_SERVER_DESTROYED;
658
659 case RTTCPSERVERSTATE_STARTING:
660 case RTTCPSERVERSTATE_SERVING:
661 default:
662 AssertMsgFailedReturn(("pServer=%p enmState=%d\n", pServer, enmState), VERR_INTERNAL_ERROR_4);
663 }
664}
665
666
667/**
668 * Listen and accept one incomming connection.
669 *
670 * This is an alternative to RTTcpServerListen for the use the callbacks are not
671 * possible.
672 *
673 * @returns IPRT status code.
674 * @retval VERR_TCP_SERVER_SHUTDOWN if shut down by RTTcpServerShutdown.
675 * @retval VERR_INTERRUPTED if the listening was interrupted.
676 *
677 * @param pServer The server handle as returned from RTTcpServerCreateEx().
678 * @param pSockClient Where to return the socket handle to the client
679 * connection (on success only). Use
680 * RTTcpServerDisconnectClient() to clean it, this must
681 * be done before the next call to RTTcpServerListen2.
682 *
683 * @todo This can easily be extended to support multiple connections by
684 * adding a new state and a RTTcpServerDisconnectClient variant for
685 * closing client sockets.
686 */
687RTR3DECL(int) RTTcpServerListen2(PRTTCPSERVER pServer, PRTSOCKET pSockClient)
688{
689 /*
690 * Validate input and retain the instance.
691 */
692 AssertPtrReturn(pSockClient, VERR_INVALID_HANDLE);
693 *pSockClient = NIL_RTSOCKET;
694 AssertReturn(pServer->u32Magic == RTTCPSERVER_MAGIC, VERR_INVALID_HANDLE);
695 AssertReturn(RTMemPoolRetain(pServer) != UINT32_MAX, VERR_INVALID_HANDLE);
696
697 int rc = VERR_INVALID_STATE;
698 for (;;)
699 {
700 /*
701 * Change state to accepting.
702 */
703 RTTCPSERVERSTATE enmState = pServer->enmState;
704 RTSOCKET SockServer = pServer->SockServer;
705 if ( enmState != RTTCPSERVERSTATE_SERVING
706 && enmState != RTTCPSERVERSTATE_CREATED)
707 {
708 rc = rcTcpServerListenCleanup(pServer);
709 break;
710 }
711 if (!rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_ACCEPTING, enmState))
712 continue;
713 Assert(!pServer->pfnServe);
714 Assert(!pServer->pvUser);
715 Assert(pServer->Thread == NIL_RTTHREAD);
716 Assert(pServer->SockClient == NIL_RTSOCKET);
717
718 /*
719 * Accept connection.
720 */
721 struct sockaddr_in RemoteAddr;
722 socklen_t cbRemoteAddr = sizeof(RemoteAddr);
723 RTSOCKET Socket;
724 RT_ZERO(RemoteAddr);
725 rtTcpErrorReset();
726 Socket = accept(SockServer, (struct sockaddr *)&RemoteAddr, &cbRemoteAddr);
727 if (Socket == -1)
728 {
729 rc = rtTcpError();
730 if (!rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_CREATED, RTTCPSERVERSTATE_ACCEPTING))
731 rc = rcTcpServerListenCleanup(pServer);
732 if (RT_FAILURE(rc))
733 break;
734 continue;
735 }
736
737 /*
738 * Chance to the 'serving' state and return the socket.
739 */
740 if (rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_SERVING, RTTCPSERVERSTATE_ACCEPTING))
741 {
742 *pSockClient = Socket;
743 rc = VINF_SUCCESS;
744 }
745 else
746 {
747 rtTcpClose(Socket, "RTTcpServerListen2", true /*fTryGracefulShutdown*/);
748 rc = rcTcpServerListenCleanup(pServer);
749 }
750 break;
751 }
752
753 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
754 return rc;
755}
756
757
758/**
759 * Terminate the open connection to the server.
760 *
761 * @returns iprt status code.
762 * @param pServer Handle to the server.
763 */
764RTR3DECL(int) RTTcpServerDisconnectClient(PRTTCPSERVER pServer)
765{
766 /*
767 * Validate input and retain the instance.
768 */
769 AssertPtrReturn(pServer, VERR_INVALID_HANDLE);
770 AssertReturn(pServer->u32Magic == RTTCPSERVER_MAGIC, VERR_INVALID_HANDLE);
771 AssertReturn(RTMemPoolRetain(pServer) != UINT32_MAX, VERR_INVALID_HANDLE);
772
773 int rc = rtTcpServerDestroySocket(&pServer->SockClient, "DisconnectClient: client", true /*fTryGracefulShutdown*/);
774
775 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
776 return rc;
777}
778
779
780/**
781 * Shuts down the server, leaving client connections open.
782 *
783 * @returns IPRT status code.
784 * @param pServer Handle to the server.
785 */
786RTR3DECL(int) RTTcpServerShutdown(PRTTCPSERVER pServer)
787{
788 /*
789 * Validate input and retain the instance.
790 */
791 AssertPtrReturn(pServer, VERR_INVALID_HANDLE);
792 AssertReturn(pServer->u32Magic == RTTCPSERVER_MAGIC, VERR_INVALID_HANDLE);
793 AssertReturn(RTMemPoolRetain(pServer) != UINT32_MAX, VERR_INVALID_HANDLE);
794
795 /*
796 * Try change the state to stopping, then replace and destroy the server socket.
797 */
798 for (;;)
799 {
800 RTTCPSERVERSTATE enmState = pServer->enmState;
801 if ( enmState != RTTCPSERVERSTATE_ACCEPTING
802 && enmState != RTTCPSERVERSTATE_SERVING)
803 {
804 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
805 switch (enmState)
806 {
807 case RTTCPSERVERSTATE_CREATED:
808 case RTTCPSERVERSTATE_STARTING:
809 default:
810 AssertMsgFailed(("%d\n", enmState));
811 return VERR_INVALID_STATE;
812
813 case RTTCPSERVERSTATE_STOPPING:
814 case RTTCPSERVERSTATE_STOPPED:
815 return VINF_SUCCESS;
816
817 case RTTCPSERVERSTATE_DESTROYING:
818 return VERR_TCP_SERVER_DESTROYED;
819 }
820 }
821 if (rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_STOPPING, enmState))
822 {
823 rtTcpServerDestroySocket(&pServer->SockServer, "RTTcpServerShutdown", false /*fTryGracefulShutdown*/);
824 rtTcpServerSetState(pServer, RTTCPSERVERSTATE_STOPPED, RTTCPSERVERSTATE_STOPPING);
825
826 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
827 return VINF_SUCCESS;
828 }
829 }
830}
831
832
833/**
834 * Closes down and frees a TCP Server.
835 * This will also terminate any open connections to the server.
836 *
837 * @returns iprt status code.
838 * @param pServer Handle to the server.
839 */
840RTR3DECL(int) RTTcpServerDestroy(PRTTCPSERVER pServer)
841{
842 /*
843 * Validate input and retain the instance.
844 */
845 AssertPtrReturn(pServer, VERR_INVALID_HANDLE);
846 AssertReturn(pServer->u32Magic == RTTCPSERVER_MAGIC, VERR_INVALID_HANDLE);
847 AssertReturn(RTMemPoolRetain(pServer) != UINT32_MAX, VERR_INVALID_HANDLE); /* paranoia */
848
849 /*
850 * Move the state along so the listener can figure out what's going on.
851 */
852 for (;;)
853 {
854 bool fDestroyable;
855 RTTCPSERVERSTATE enmState = pServer->enmState;
856 switch (enmState)
857 {
858 case RTTCPSERVERSTATE_STARTING:
859 case RTTCPSERVERSTATE_ACCEPTING:
860 case RTTCPSERVERSTATE_SERVING:
861 case RTTCPSERVERSTATE_CREATED:
862 case RTTCPSERVERSTATE_STOPPED:
863 fDestroyable = rtTcpServerTrySetState(pServer, RTTCPSERVERSTATE_DESTROYING, enmState);
864 break;
865
866 /* destroyable states */
867 case RTTCPSERVERSTATE_STOPPING:
868 fDestroyable = true;
869 break;
870
871 /*
872 * Everything else means user or internal misbehavior.
873 */
874 default:
875 AssertMsgFailed(("pServer=%p enmState=%d\n", pServer, enmState));
876 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
877 return VERR_INTERNAL_ERROR;
878 }
879 if (fDestroyable)
880 break;
881 }
882
883 /*
884 * Destroy it.
885 */
886 ASMAtomicWriteU32(&pServer->u32Magic, ~RTTCPSERVER_MAGIC);
887 rtTcpServerDestroySocket(&pServer->SockServer, "Destroyer: server", false /*fTryGracefulShutdown*/);
888 rtTcpServerDestroySocket(&pServer->SockClient, "Destroyer: client", true /*fTryGracefulShutdown*/);
889
890 /*
891 * Release it.
892 */
893 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
894 RTMemPoolRelease(RTMEMPOOL_DEFAULT, pServer);
895 return VINF_SUCCESS;
896}
897
898
899RTR3DECL(int) RTTcpRead(RTSOCKET Sock, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
900{
901 /*
902 * Validate input.
903 */
904 AssertReturn(cbBuffer > 0, VERR_INVALID_PARAMETER);
905 AssertPtr(pvBuffer);
906
907 /*
908 * Read loop.
909 * If pcbRead is NULL we have to fill the entire buffer!
910 */
911 size_t cbRead = 0;
912 size_t cbToRead = cbBuffer;
913 for (;;)
914 {
915 rtTcpErrorReset();
916#ifdef RT_OS_WINDOWS
917 int cbNow = cbToRead >= INT_MAX/2 ? INT_MAX/2 : (int)cbToRead;
918#else
919 size_t cbNow = cbToRead;
920#endif
921 ssize_t cbBytesRead = recv(Sock, (char *)pvBuffer + cbRead, cbNow, MSG_NOSIGNAL);
922 if (cbBytesRead <= 0)
923 {
924 int rc = rtTcpError();
925 Assert(RT_FAILURE_NP(rc) || cbBytesRead == 0);
926 if (RT_FAILURE_NP(rc))
927 return rc;
928 if (pcbRead)
929 {
930 *pcbRead = 0;
931 return VINF_SUCCESS;
932 }
933 return VERR_NET_SHUTDOWN;
934 }
935 if (pcbRead)
936 {
937 /* return partial data */
938 *pcbRead = cbBytesRead;
939 break;
940 }
941
942 /* read more? */
943 cbRead += cbBytesRead;
944 if (cbRead == cbBuffer)
945 break;
946
947 /* next */
948 cbToRead = cbBuffer - cbRead;
949 }
950
951 return VINF_SUCCESS;
952}
953
954
955RTR3DECL(int) RTTcpWrite(RTSOCKET Sock, const void *pvBuffer, size_t cbBuffer)
956{
957 /*
958 * Try write all at once.
959 */
960#ifdef RT_OS_WINDOWS
961 int cbNow = cbBuffer >= INT_MAX / 2 ? INT_MAX / 2 : (int)cbBuffer;
962#else
963 size_t cbNow = cbBuffer >= SSIZE_MAX ? SSIZE_MAX : cbBuffer;
964#endif
965 ssize_t cbWritten = send(Sock, (const char *)pvBuffer, cbNow, MSG_NOSIGNAL);
966 if (RT_LIKELY((size_t)cbWritten == cbBuffer && cbWritten >= 0))
967 return VINF_SUCCESS;
968 if (cbWritten < 0)
969 return rtTcpError();
970
971 /*
972 * Unfinished business, write the remainder of the request. Must ignore
973 * VERR_INTERRUPTED here if we've managed to send something.
974 */
975 size_t cbSentSoFar = 0;
976 for (;;)
977 {
978 /* advance */
979 cbBuffer -= (size_t)cbWritten;
980 if (!cbBuffer)
981 return VINF_SUCCESS;
982 cbSentSoFar += (size_t)cbWritten;
983 pvBuffer = (char const *)pvBuffer + cbWritten;
984
985 /* send */
986#ifdef RT_OS_WINDOWS
987 cbNow = cbBuffer >= INT_MAX / 2 ? INT_MAX / 2 : (int)cbBuffer;
988#else
989 cbNow = cbBuffer >= SSIZE_MAX ? SSIZE_MAX : cbBuffer;
990#endif
991 cbWritten = send(Sock, (const char *)pvBuffer, cbNow, MSG_NOSIGNAL);
992 if (cbWritten >= 0)
993 AssertMsg(cbBuffer >= (size_t)cbWritten, ("Wrote more than we requested!!! cbWritten=%zu cbBuffer=%zu rtTcpError()=%d\n",
994 cbWritten, cbBuffer, rtTcpError()));
995 else
996 {
997 int rc = rtTcpError();
998 if (rc != VERR_INTERNAL_ERROR || cbSentSoFar == 0)
999 return rc;
1000 cbWritten = 0;
1001 }
1002 }
1003}
1004
1005
1006RTR3DECL(int) RTTcpFlush(RTSOCKET Sock)
1007{
1008 int fFlag = 1;
1009 setsockopt(Sock, IPPROTO_TCP, TCP_NODELAY, (const char *)&fFlag, sizeof(fFlag));
1010 fFlag = 0;
1011 setsockopt(Sock, IPPROTO_TCP, TCP_NODELAY, (const char *)&fFlag, sizeof(fFlag));
1012
1013 return VINF_SUCCESS;
1014}
1015
1016
1017RTR3DECL(int) RTTcpSelectOne(RTSOCKET Sock, RTMSINTERVAL cMillies)
1018{
1019 fd_set fdsetR;
1020 FD_ZERO(&fdsetR);
1021 FD_SET(Sock, &fdsetR);
1022
1023 fd_set fdsetE = fdsetR;
1024
1025 int rc;
1026 if (cMillies == RT_INDEFINITE_WAIT)
1027 rc = select(Sock + 1, &fdsetR, NULL, &fdsetE, NULL);
1028 else
1029 {
1030 struct timeval timeout;
1031 timeout.tv_sec = cMillies / 1000;
1032 timeout.tv_usec = (cMillies % 1000) * 1000;
1033 rc = select(Sock + 1, &fdsetR, NULL, &fdsetE, &timeout);
1034 }
1035 if (rc > 0)
1036 return VINF_SUCCESS;
1037 if (rc == 0)
1038 return VERR_TIMEOUT;
1039 return rtTcpError();
1040}
1041
1042
1043static int rtTcpConvertAddress(RTSOCKADDRUNION *pSrc, size_t cbSrc, PRTNETADDR pAddr)
1044{
1045 /*
1046 * Convert the address.
1047 */
1048 if ( cbSrc == sizeof(struct sockaddr_in)
1049 && pSrc->Addr.sa_family == AF_INET)
1050 {
1051 RT_ZERO(*pAddr);
1052 pAddr->enmType = RTNETADDRTYPE_IPV4;
1053 pAddr->uPort = RT_N2H_U16(pSrc->Ipv4.sin_port);
1054 pAddr->uAddr.IPv4.u = pSrc->Ipv4.sin_addr.s_addr;
1055 }
1056#ifdef IPRT_WITH_TCPIP_V6
1057 else if ( cbSrc == sizeof(struct sockaddr_in6)
1058 && pSrc->Addr.sa_family == AF_INET6)
1059 {
1060 RT_ZERO(*pAddr);
1061 pAddr->enmType = RTNETADDRTYPE_IPV6;
1062 pAddr->uPort = RT_N2H_U16(pSrc->Ipv6.sin6_port);
1063 pAddr->uAddr.IPv6.au32[0] = pSrc->Ipv6.sin6_addr.s6_addr32[0];
1064 pAddr->uAddr.IPv6.au32[1] = pSrc->Ipv6.sin6_addr.s6_addr32[1];
1065 pAddr->uAddr.IPv6.au32[2] = pSrc->Ipv6.sin6_addr.s6_addr32[2];
1066 pAddr->uAddr.IPv6.au32[3] = pSrc->Ipv6.sin6_addr.s6_addr32[3];
1067 }
1068#endif
1069 else
1070 return VERR_NET_ADDRESS_FAMILY_NOT_SUPPORTED;
1071 return VINF_SUCCESS;
1072}
1073
1074
1075RTR3DECL(int) RTTcpGetLocalAddress(RTSOCKET Sock, PRTNETADDR pAddr)
1076{
1077 RTSOCKADDRUNION u;
1078#ifdef RT_OS_WINDOWS
1079 int cbAddr = sizeof(u);
1080#else
1081 socklen_t cbAddr = sizeof(u);
1082#endif
1083 RT_ZERO(u);
1084 if (!getsockname(Sock, &u.Addr, &cbAddr))
1085 return rtTcpConvertAddress(&u, cbAddr, pAddr);
1086 return rtTcpError();
1087}
1088
1089
1090RTR3DECL(int) RTTcpGetPeerAddress(RTSOCKET Sock, PRTNETADDR pAddr)
1091{
1092 RTSOCKADDRUNION u;
1093#ifdef RT_OS_WINDOWS
1094 int cbAddr = sizeof(u);
1095#else
1096 socklen_t cbAddr = sizeof(u);
1097#endif
1098 RT_ZERO(u);
1099 if (!getpeername(Sock, &u.Addr, &cbAddr))
1100 return rtTcpConvertAddress(&u, cbAddr, pAddr);
1101 return rtTcpError();
1102}
1103
1104
1105RTR3DECL(int) RTTcpClientConnect(const char *pszAddress, uint32_t uPort, PRTSOCKET pSock)
1106{
1107 int rc;
1108
1109 /*
1110 * Validate input.
1111 */
1112 AssertReturn(uPort > 0, VERR_INVALID_PARAMETER);
1113 AssertPtrReturn(pszAddress, VERR_INVALID_POINTER);
1114
1115#ifdef RT_OS_WINDOWS
1116 /*
1117 * Initialize WinSock and check version.
1118 */
1119 WORD wVersionRequested = MAKEWORD(1, 1);
1120 WSADATA wsaData;
1121 rc = WSAStartup(wVersionRequested, &wsaData);
1122 if (wsaData.wVersion != wVersionRequested)
1123 {
1124 AssertMsgFailed(("Wrong winsock version\n"));
1125 return VERR_NOT_SUPPORTED;
1126 }
1127#endif
1128
1129 /*
1130 * Resolve the address.
1131 */
1132 struct hostent *pHostEnt = NULL;
1133 pHostEnt = gethostbyname(pszAddress);
1134 if (!pHostEnt)
1135 {
1136 struct in_addr InAddr;
1137 InAddr.s_addr = inet_addr(pszAddress);
1138 pHostEnt = gethostbyaddr((char *)&InAddr, 4, AF_INET);
1139 if (!pHostEnt)
1140 {
1141 rc = rtTcpError();
1142 AssertMsgFailed(("Could not resolve '%s', rc=%Rrc\n", pszAddress, rc));
1143 return rc;
1144 }
1145 }
1146
1147 /*
1148 * Create the socket and connect.
1149 */
1150 RTSOCKET Sock = socket(PF_INET, SOCK_STREAM, 0);
1151 if (Sock != -1)
1152 {
1153 struct sockaddr_in InAddr;
1154 RT_ZERO(InAddr);
1155 InAddr.sin_family = AF_INET;
1156 InAddr.sin_port = htons(uPort);
1157 InAddr.sin_addr = *((struct in_addr *)pHostEnt->h_addr);
1158 if (!connect(Sock, (struct sockaddr *)&InAddr, sizeof(InAddr)))
1159 {
1160 *pSock = Sock;
1161 return VINF_SUCCESS;
1162 }
1163 rc = rtTcpError();
1164 rtTcpClose(Sock, "RTTcpClientConnect", false /*fTryGracefulShutdown*/);
1165 }
1166 else
1167 rc = rtTcpError();
1168 return rc;
1169}
1170
1171
1172RTR3DECL(int) RTTcpClientClose(RTSOCKET Sock)
1173{
1174 return rtTcpClose(Sock, "RTTcpClientClose", true /*fTryGracefulShutdown*/);
1175}
1176
1177
1178/**
1179 * Internal close function which does all the proper bitching.
1180 */
1181static int rtTcpClose(RTSOCKET Sock, const char *pszMsg, bool fTryGracefulShutdown)
1182{
1183 int rc;
1184
1185 /* ignore nil handles. */
1186 if (Sock == NIL_RTSOCKET)
1187 return VINF_SUCCESS;
1188
1189 /*
1190 * Try to gracefully shut it down.
1191 */
1192 if (fTryGracefulShutdown)
1193 {
1194 rc = shutdown(Sock, SHUT_WR);
1195 if (!rc)
1196 {
1197 uint64_t u64Start = RTTimeMilliTS();
1198 for (;;)
1199 {
1200 rc = RTTcpSelectOne(Sock, 1000);
1201 if (rc == VERR_TIMEOUT)
1202 {
1203 if (RTTimeMilliTS() - u64Start > 30000)
1204 break;
1205 }
1206 else if (rc != VINF_SUCCESS)
1207 break;
1208 {
1209 char abBitBucket[16*_1K];
1210 ssize_t cbBytesRead = recv(Sock, &abBitBucket[0], sizeof(abBitBucket), MSG_NOSIGNAL);
1211 if (cbBytesRead == 0)
1212 break; /* orderly shutdown in progress */
1213 if (cbBytesRead < 0)
1214 break; /* some kind of error, never mind which... */
1215 }
1216 } /* forever */
1217 }
1218 }
1219
1220 /*
1221 * Attempt to close it.
1222 */
1223#ifdef RT_OS_WINDOWS
1224 rc = closesocket(Sock);
1225#else
1226 rc = close(Sock);
1227#endif
1228 if (!rc)
1229 return VINF_SUCCESS;
1230 rc = rtTcpError();
1231 AssertMsgFailed(("\"%s\": close(%d) -> %Rrc\n", pszMsg, Sock, rc));
1232 return rc;
1233}
1234
Note: See TracBrowser for help on using the repository browser.

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