VirtualBox

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

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

RTTcpRead: recv returns 0 and errno = 0 when the server shuts down the socket in a normal fashion. Return VERR_NET_SHUTDOWN instead of spinning for ever.

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