VirtualBox

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

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

IPRT/r3/tcp.cpp: Windows build fix. Killed some warnings as well.

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