VirtualBox

source: vbox/trunk/src/VBox/Devices/Audio/AudioTestServiceTcp.cpp@ 90855

Last change on this file since 90855 was 90830, checked in by vboxsync, 3 years ago

Audio/ValKit: More work on ATS client destruction handling. bugref:10008

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 28.6 KB
Line 
1/* $Id: AudioTestServiceTcp.cpp 90830 2021-08-24 10:47:52Z vboxsync $ */
2/** @file
3 * AudioTestServiceTcp - Audio test execution server, TCP/IP Transport Layer.
4 */
5
6/*
7 * Copyright (C) 2021 Oracle Corporation
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
18
19/*********************************************************************************************************************************
20* Header Files *
21*********************************************************************************************************************************/
22#define LOG_GROUP LOG_GROUP_AUDIO_TEST
23#include <iprt/asm.h>
24#include <iprt/assert.h>
25#include <iprt/critsect.h>
26#include <iprt/err.h>
27#include <iprt/log.h>
28#include <iprt/mem.h>
29#include <iprt/message.h>
30#include <iprt/poll.h>
31#include <iprt/string.h>
32#include <iprt/tcp.h>
33#include <iprt/thread.h>
34#include <iprt/time.h>
35
36#include <VBox/log.h>
37
38#include "AudioTestService.h"
39#include "AudioTestServiceInternal.h"
40
41
42/*********************************************************************************************************************************
43* Defined Constants And Macros *
44*********************************************************************************************************************************/
45
46
47/*********************************************************************************************************************************
48* Structures and Typedefs *
49*********************************************************************************************************************************/
50/**
51 * TCP specific client data.
52 */
53typedef struct ATSTRANSPORTCLIENT
54{
55 /** Socket of the current client. */
56 RTSOCKET hTcpClient;
57 /** Indicates whether \a hTcpClient comes from the server or from a client
58 * connect (relevant when closing it). */
59 bool fFromServer;
60 /** The size of the stashed data. */
61 size_t cbTcpStashed;
62 /** The size of the stashed data allocation. */
63 size_t cbTcpStashedAlloced;
64 /** The stashed data. */
65 uint8_t *pbTcpStashed;
66} ATSTRANSPORTCLIENT;
67
68/**
69 * Enumeration for the TCP/IP connection mode.
70 */
71typedef enum ATSTCPMODE
72{
73 /** Both: Uses parallel client and server connection methods (via threads). */
74 ATSTCPMODE_BOTH = 0,
75 /** Client only: Connects to a server. */
76 ATSTCPMODE_CLIENT,
77 /** Server only: Listens for new incoming client connections. */
78 ATSTCPMODE_SERVER
79} ATSTCPMODE;
80
81/**
82 * Structure for keeping Audio Test Service (ATS) transport instance-specific data.
83 */
84typedef struct ATSTRANSPORTINST
85{
86 /** Critical section for serializing access. */
87 RTCRITSECT CritSect;
88 /** Connection mode to use. */
89 ATSTCPMODE enmMode;
90 /** The addresses to bind to. Empty string means any. */
91 char szBindAddr[256];
92 /** The TCP port to listen to. */
93 uint32_t uBindPort;
94 /** The addresses to connect to if running in reversed (VM NATed) mode. */
95 char szConnectAddr[256];
96 /** The TCP port to connect to if running in reversed (VM NATed) mode. */
97 uint32_t uConnectPort;
98 /** Pointer to the TCP server instance. */
99 PRTTCPSERVER pTcpServer;
100 /** Thread calling RTTcpServerListen2. */
101 RTTHREAD hThreadServer;
102 /** Thread calling RTTcpClientConnect. */
103 RTTHREAD hThreadConnect;
104 /** The main thread handle (for signalling). */
105 RTTHREAD hThreadMain;
106 /** Stop connecting attempts when set. */
107 bool fStopConnecting;
108 /** Connect cancel cookie. */
109 PRTTCPCLIENTCONNECTCANCEL volatile pConnectCancelCookie;
110} ATSTRANSPORTINST;
111/** Pointer to an Audio Test Service (ATS) TCP/IP transport instance. */
112typedef ATSTRANSPORTINST *PATSTRANSPORTINST;
113
114/**
115 * Structure holding an ATS connection context, which is
116 * required when connecting a client via server (listening) or client (connecting).
117 */
118typedef struct ATSCONNCTX
119{
120 /** Pointer to transport instance to use. */
121 PATSTRANSPORTINST pInst;
122 /** Pointer to transport client to connect. */
123 PATSTRANSPORTCLIENT pClient;
124} ATSCONNCTX;
125/** Pointer to an Audio Test Service (ATS) TCP/IP connection context. */
126typedef ATSCONNCTX *PATSCONNCTX;
127
128
129/*********************************************************************************************************************************
130* Global Variables *
131*********************************************************************************************************************************/
132
133/**
134 * Disconnects the current client and frees all stashed data.
135 */
136static void atsTcpDisconnectClient(PATSTRANSPORTINST pThis, PATSTRANSPORTCLIENT pClient)
137{
138 RT_NOREF(pThis);
139
140 if (pClient->hTcpClient != NIL_RTSOCKET)
141 {
142 int rc;
143 if (pClient->fFromServer)
144 rc = RTTcpServerDisconnectClient2(pClient->hTcpClient);
145 else
146 rc = RTTcpClientClose(pClient->hTcpClient);
147 pClient->hTcpClient = NIL_RTSOCKET;
148 AssertRCSuccess(rc);
149 }
150
151 if (pClient->pbTcpStashed)
152 {
153 RTMemFree(pClient->pbTcpStashed);
154 pClient->pbTcpStashed = NULL;
155 }
156}
157
158/**
159 * Sets the current client socket in a safe manner.
160 *
161 * @returns NIL_RTSOCKET if consumed, other wise hTcpClient.
162 * @param pThis Transport instance.
163 * @param pClient Client to set the socket for.
164 * @param fFromServer Whether the socket is from a server (listening) or client (connecting) call.
165 * Important when closing / disconnecting.
166 * @param hTcpClient The client socket.
167 */
168static RTSOCKET atsTcpSetClient(PATSTRANSPORTINST pThis, PATSTRANSPORTCLIENT pClient, bool fFromServer, RTSOCKET hTcpClient)
169{
170 RTCritSectEnter(&pThis->CritSect);
171 if ( pClient->hTcpClient == NIL_RTSOCKET
172 && !pThis->fStopConnecting)
173 {
174 LogFunc(("New client connected\n"));
175
176 pClient->fFromServer = fFromServer;
177 pClient->hTcpClient = hTcpClient;
178 hTcpClient = NIL_RTSOCKET; /* Invalidate, as pClient has now ownership. */
179 }
180 RTCritSectLeave(&pThis->CritSect);
181 return hTcpClient;
182}
183
184/**
185 * Checks if it's a fatal RTTcpClientConnect return code.
186 *
187 * @returns true / false.
188 * @param rc The IPRT status code.
189 */
190static bool atsTcpIsFatalClientConnectStatus(int rc)
191{
192 return rc != VERR_NET_UNREACHABLE
193 && rc != VERR_NET_HOST_DOWN
194 && rc != VERR_NET_HOST_UNREACHABLE
195 && rc != VERR_NET_CONNECTION_REFUSED
196 && rc != VERR_TIMEOUT
197 && rc != VERR_NET_CONNECTION_TIMED_OUT;
198}
199
200/**
201 * Server mode connection thread.
202 *
203 * @returns iprt status code.
204 * @param hSelf Thread handle. Ignored.
205 * @param pvUser Pointer to ATSTRANSPORTINST the thread is bound to.
206 */
207static DECLCALLBACK(int) atsTcpServerConnectThread(RTTHREAD hSelf, void *pvUser)
208{
209 RT_NOREF(hSelf);
210
211 PATSCONNCTX pConnCtx = (PATSCONNCTX)pvUser;
212 PATSTRANSPORTINST pThis = pConnCtx->pInst;
213 PATSTRANSPORTCLIENT pClient = pConnCtx->pClient;
214
215 RTSOCKET hTcpClient;
216 int rc = RTTcpServerListen2(pThis->pTcpServer, &hTcpClient);
217 if (RT_SUCCESS(rc))
218 {
219 hTcpClient = atsTcpSetClient(pThis, pClient, true /* fFromServer */, hTcpClient);
220 RTTcpServerDisconnectClient2(hTcpClient);
221 }
222
223 return rc;
224}
225
226/**
227 * Client mode connection thread.
228 *
229 * @returns iprt status code.
230 * @param hSelf Thread handle. Use to sleep on. The main thread will
231 * signal it to speed up thread shutdown.
232 * @param pvUser Pointer to a connection context (PATSCONNCTX) the thread is bound to.
233 */
234static DECLCALLBACK(int) atsTcpClientConnectThread(RTTHREAD hSelf, void *pvUser)
235{
236 PATSCONNCTX pConnCtx = (PATSCONNCTX)pvUser;
237 PATSTRANSPORTINST pThis = pConnCtx->pInst;
238 PATSTRANSPORTCLIENT pClient = pConnCtx->pClient;
239
240 for (;;)
241 {
242 /* Stop? */
243 RTCritSectEnter(&pThis->CritSect);
244 bool fStop = pThis->fStopConnecting;
245 RTCritSectLeave(&pThis->CritSect);
246 if (fStop)
247 return VINF_SUCCESS;
248
249 /* Try connect. */ /** @todo make cancelable! */
250 RTSOCKET hTcpClient;
251 int rc = RTTcpClientConnectEx(pThis->szConnectAddr, pThis->uConnectPort, &hTcpClient,
252 RT_SOCKETCONNECT_DEFAULT_WAIT, &pThis->pConnectCancelCookie);
253 if (RT_SUCCESS(rc))
254 {
255 hTcpClient = atsTcpSetClient(pThis, pClient, false /* fFromServer */, hTcpClient);
256 RTTcpClientCloseEx(hTcpClient, true /* fGracefulShutdown*/);
257 break;
258 }
259
260 if (atsTcpIsFatalClientConnectStatus(rc))
261 return rc;
262
263 /* Delay a wee bit before retrying. */
264 RTThreadUserWait(hSelf, 1536);
265 }
266 return VINF_SUCCESS;
267}
268
269/**
270 * Wait on the threads to complete.
271 *
272 * @returns Thread status (if collected), otherwise VINF_SUCCESS.
273 * @param pThis Transport instance.
274 * @param cMillies The period to wait on each thread.
275 */
276static int atsTcpConnectWaitOnThreads(PATSTRANSPORTINST pThis, RTMSINTERVAL cMillies)
277{
278 int rcRet = VINF_SUCCESS;
279
280 if (pThis->hThreadConnect != NIL_RTTHREAD)
281 {
282 int rcThread;
283 int rc2 = RTThreadWait(pThis->hThreadConnect, cMillies, &rcThread);
284 if (RT_SUCCESS(rc2))
285 {
286 pThis->hThreadConnect = NIL_RTTHREAD;
287 rcRet = rcThread;
288 }
289 }
290
291 if (pThis->hThreadServer != NIL_RTTHREAD)
292 {
293 int rcThread;
294 int rc2 = RTThreadWait(pThis->hThreadServer, cMillies, &rcThread);
295 if (RT_SUCCESS(rc2))
296 {
297 pThis->hThreadServer = NIL_RTTHREAD;
298 if (RT_SUCCESS(rc2))
299 rcRet = rcThread;
300 }
301 }
302 return rcRet;
303}
304
305/**
306 * @interface_method_impl{ATSTRANSPORT,pfnWaitForConnect}
307 */
308static DECLCALLBACK(int) atsTcpWaitForConnect(PATSTRANSPORTINST pThis, PPATSTRANSPORTCLIENT ppClientNew)
309{
310 PATSTRANSPORTCLIENT pClient = (PATSTRANSPORTCLIENT)RTMemAllocZ(sizeof(ATSTRANSPORTCLIENT));
311 AssertPtrReturn(pClient, VERR_NO_MEMORY);
312
313 int rc;
314
315 if (pThis->enmMode == ATSTCPMODE_SERVER)
316 {
317 pClient->fFromServer = true;
318 rc = RTTcpServerListen2(pThis->pTcpServer, &pClient->hTcpClient);
319 LogFunc(("RTTcpServerListen2 -> %Rrc\n", rc));
320 }
321 else if (pThis->enmMode == ATSTCPMODE_CLIENT)
322 {
323 pClient->fFromServer = false;
324 for (;;)
325 {
326 Log2Func(("Calling RTTcpClientConnect(%s, %u,)...\n", pThis->szConnectAddr, pThis->uConnectPort));
327 rc = RTTcpClientConnect(pThis->szConnectAddr, pThis->uConnectPort, &pClient->hTcpClient);
328 LogFunc(("RTTcpClientConnect -> %Rrc\n", rc));
329 if (RT_SUCCESS(rc) || atsTcpIsFatalClientConnectStatus(rc))
330 break;
331
332 /* Delay a wee bit before retrying. */
333 RTThreadSleep(1536);
334 }
335 }
336 else
337 {
338 Assert(pThis->enmMode == ATSTCPMODE_BOTH);
339
340 /*
341 * Create client threads.
342 */
343 RTCritSectEnter(&pThis->CritSect);
344
345 pThis->fStopConnecting = false;
346 RTCritSectLeave(&pThis->CritSect);
347
348 atsTcpConnectWaitOnThreads(pThis, 32 /* cMillies */);
349
350 ATSCONNCTX ConnCtx;
351 RT_ZERO(ConnCtx);
352 ConnCtx.pInst = pThis;
353 ConnCtx.pClient = pClient;
354
355 rc = VINF_SUCCESS;
356 if (pThis->hThreadConnect == NIL_RTTHREAD)
357 {
358 pThis->pConnectCancelCookie = NULL;
359 rc = RTThreadCreate(&pThis->hThreadConnect, atsTcpClientConnectThread, &ConnCtx, 0, RTTHREADTYPE_DEFAULT,
360 RTTHREADFLAGS_WAITABLE, "tcpconn");
361 }
362 if (pThis->hThreadServer == NIL_RTTHREAD && RT_SUCCESS(rc))
363 rc = RTThreadCreate(&pThis->hThreadServer, atsTcpServerConnectThread, &ConnCtx, 0, RTTHREADTYPE_DEFAULT,
364 RTTHREADFLAGS_WAITABLE, "tcpserv");
365
366 RTCritSectEnter(&pThis->CritSect);
367
368 /*
369 * Wait for connection to be established.
370 */
371 while ( RT_SUCCESS(rc)
372 && pClient->hTcpClient == NIL_RTSOCKET)
373 {
374 RTCritSectLeave(&pThis->CritSect);
375 rc = atsTcpConnectWaitOnThreads(pThis, 10 /* cMillies */);
376 RTCritSectEnter(&pThis->CritSect);
377 }
378
379 /*
380 * Cancel the threads.
381 */
382 pThis->fStopConnecting = true;
383
384 RTCritSectLeave(&pThis->CritSect);
385 RTTcpClientCancelConnect(&pThis->pConnectCancelCookie);
386 }
387
388 if (RT_SUCCESS(rc))
389 {
390 *ppClientNew = pClient;
391 }
392 else
393 {
394 if (pClient)
395 {
396 RTTcpServerDisconnectClient2(pClient->hTcpClient);
397
398 RTMemFree(pClient);
399 pClient = NULL;
400 }
401 }
402
403 return rc;
404}
405
406/**
407 * @interface_method_impl{ATSTRANSPORT,pfnNotifyReboot}
408 */
409static DECLCALLBACK(void) atsTcpNotifyReboot(PATSTRANSPORTINST pThis)
410{
411 LogFunc(("RTTcpServerDestroy(%p)\n", pThis->pTcpServer));
412 if (pThis->pTcpServer)
413 {
414 int rc = RTTcpServerDestroy(pThis->pTcpServer);
415 if (RT_FAILURE(rc))
416 RTMsgInfo("RTTcpServerDestroy failed in atsTcpNotifyReboot: %Rrc", rc);
417 pThis->pTcpServer = NULL;
418 }
419}
420
421/**
422 * @interface_method_impl{ATSTRANSPORT,pfnNotifyBye}
423 */
424static DECLCALLBACK(void) atsTcpNotifyBye(PATSTRANSPORTINST pThis, PATSTRANSPORTCLIENT pClient)
425{
426 LogFunc(("atsTcpDisconnectClient %RTsock\n", pClient->hTcpClient));
427 atsTcpDisconnectClient(pThis, pClient);
428}
429
430/**
431 * @interface_method_impl{ATSTRANSPORT,pfnNotifyHowdy}
432 */
433static DECLCALLBACK(void) atsTcpNotifyHowdy(PATSTRANSPORTINST pThis, PATSTRANSPORTCLIENT pClient)
434{
435 /* nothing to do here */
436 RT_NOREF(pThis, pClient);
437}
438
439/**
440 * @interface_method_impl{ATSTRANSPORT,pfnBabble}
441 */
442static DECLCALLBACK(void) atsTcpBabble(PATSTRANSPORTINST pThis, PATSTRANSPORTCLIENT pClient, PCATSPKTHDR pPktHdr, RTMSINTERVAL cMsSendTimeout)
443{
444 /*
445 * Try send the babble reply.
446 */
447 RT_NOREF(cMsSendTimeout); /** @todo implement the timeout here; non-blocking write + select-on-write. */
448 int rc;
449 size_t cbToSend = RT_ALIGN_Z(pPktHdr->cb, ATSPKT_ALIGNMENT);
450 do rc = RTTcpWrite(pClient->hTcpClient, pPktHdr, cbToSend);
451 while (rc == VERR_INTERRUPTED);
452
453 /*
454 * Disconnect the client.
455 */
456 LogFunc(("atsTcpDisconnectClient(%RTsock) (RTTcpWrite rc=%Rrc)\n", pClient->hTcpClient, rc));
457 atsTcpDisconnectClient(pThis, pClient);
458}
459
460/**
461 * @interface_method_impl{ATSTRANSPORT,pfnSendPkt}
462 */
463static DECLCALLBACK(int) atsTcpSendPkt(PATSTRANSPORTINST pThis, PATSTRANSPORTCLIENT pClient, PCATSPKTHDR pPktHdr)
464{
465 AssertReturn(pPktHdr->cb >= sizeof(ATSPKTHDR), VERR_INVALID_PARAMETER);
466
467 /*
468 * Write it.
469 */
470 size_t cbToSend = RT_ALIGN_Z(pPktHdr->cb, ATSPKT_ALIGNMENT);
471
472 Log3Func(("%RU32 -> %zu\n", pPktHdr->cb, cbToSend));
473
474 Log3Func(("Header:\n"
475 "%.*Rhxd\n", RT_MIN(sizeof(ATSPKTHDR), cbToSend), pPktHdr));
476
477 if (cbToSend > sizeof(ATSPKTHDR))
478 Log3Func(("Payload:\n"
479 "%.*Rhxd\n",
480 RT_MIN(64, cbToSend - sizeof(ATSPKTHDR)), (uint8_t *)pPktHdr + sizeof(ATSPKTHDR)));
481
482 int rc = RTTcpWrite(pClient->hTcpClient, pPktHdr, cbToSend);
483 if ( RT_FAILURE(rc)
484 && rc != VERR_INTERRUPTED)
485 {
486 /* assume fatal connection error. */
487 LogFunc(("RTTcpWrite -> %Rrc -> atsTcpDisconnectClient(%RTsock)\n", rc, pClient->hTcpClient));
488 atsTcpDisconnectClient(pThis, pClient);
489 }
490
491 return rc;
492}
493
494/**
495 * @interface_method_impl{ATSTRANSPORT,pfnRecvPkt}
496 */
497static DECLCALLBACK(int) atsTcpRecvPkt(PATSTRANSPORTINST pThis, PATSTRANSPORTCLIENT pClient, PPATSPKTHDR ppPktHdr)
498{
499 int rc = VINF_SUCCESS;
500 *ppPktHdr = NULL;
501
502 /*
503 * Read state.
504 */
505 size_t offData = 0;
506 size_t cbData = 0;
507 size_t cbDataAlloced;
508 uint8_t *pbData = NULL;
509
510 /*
511 * Any stashed data?
512 */
513 if (pClient->cbTcpStashedAlloced)
514 {
515 offData = pClient->cbTcpStashed;
516 cbDataAlloced = pClient->cbTcpStashedAlloced;
517 pbData = pClient->pbTcpStashed;
518
519 pClient->cbTcpStashed = 0;
520 pClient->cbTcpStashedAlloced = 0;
521 pClient->pbTcpStashed = NULL;
522 }
523 else
524 {
525 cbDataAlloced = RT_ALIGN_Z(64, ATSPKT_ALIGNMENT);
526 pbData = (uint8_t *)RTMemAlloc(cbDataAlloced);
527 if (!pbData)
528 return VERR_NO_MEMORY;
529 }
530
531 /*
532 * Read and validate the length.
533 */
534 while (offData < sizeof(uint32_t))
535 {
536 size_t cbRead;
537 rc = RTTcpRead(pClient->hTcpClient, pbData + offData, sizeof(uint32_t) - offData, &cbRead);
538 if (RT_FAILURE(rc))
539 break;
540 if (cbRead == 0)
541 {
542 LogFunc(("RTTcpRead -> %Rrc / cbRead=0 -> VERR_NET_NOT_CONNECTED (#1)\n", rc));
543 rc = VERR_NET_NOT_CONNECTED;
544 break;
545 }
546 offData += cbRead;
547 }
548 if (RT_SUCCESS(rc))
549 {
550 ASMCompilerBarrier(); /* paranoia^3 */
551 cbData = *(uint32_t volatile *)pbData;
552 if (cbData >= sizeof(ATSPKTHDR) && cbData <= ATSPKT_MAX_SIZE)
553 {
554 /*
555 * Align the length and reallocate the return packet it necessary.
556 */
557 cbData = RT_ALIGN_Z(cbData, ATSPKT_ALIGNMENT);
558 if (cbData > cbDataAlloced)
559 {
560 void *pvNew = RTMemRealloc(pbData, cbData);
561 if (pvNew)
562 {
563 pbData = (uint8_t *)pvNew;
564 cbDataAlloced = cbData;
565 }
566 else
567 rc = VERR_NO_MEMORY;
568 }
569 if (RT_SUCCESS(rc))
570 {
571 /*
572 * Read the remainder of the data.
573 */
574 while (offData < cbData)
575 {
576 size_t cbRead;
577 rc = RTTcpRead(pClient->hTcpClient, pbData + offData, cbData - offData, &cbRead);
578 if (RT_FAILURE(rc))
579 break;
580 if (cbRead == 0)
581 {
582 LogFunc(("RTTcpRead -> %Rrc / cbRead=0 -> VERR_NET_NOT_CONNECTED (#2)\n", rc));
583 rc = VERR_NET_NOT_CONNECTED;
584 break;
585 }
586
587 offData += cbRead;
588 }
589
590 Log3Func(("Header:\n"
591 "%.*Rhxd\n", sizeof(ATSPKTHDR), pbData));
592
593 if ( RT_SUCCESS(rc)
594 && cbData > sizeof(ATSPKTHDR))
595 Log3Func(("Payload:\n"
596 "%.*Rhxd\n", RT_MIN(64, cbData - sizeof(ATSPKTHDR)), (uint8_t *)pbData + sizeof(ATSPKTHDR)));
597 }
598 }
599 else
600 rc = VERR_NET_PROTOCOL_ERROR;
601 }
602 if (RT_SUCCESS(rc))
603 *ppPktHdr = (PATSPKTHDR)pbData;
604 else
605 {
606 /*
607 * Deal with errors.
608 */
609 if (rc == VERR_INTERRUPTED)
610 {
611 /* stash it away for the next call. */
612 pClient->cbTcpStashed = cbData;
613 pClient->cbTcpStashedAlloced = cbDataAlloced;
614 pClient->pbTcpStashed = pbData;
615 }
616 else
617 {
618 RTMemFree(pbData);
619
620 /* assume fatal connection error. */
621 LogFunc(("RTTcpRead -> %Rrc -> atsTcpDisconnectClient(%RTsock)\n", rc, pClient->hTcpClient));
622 atsTcpDisconnectClient(pThis, pClient);
623 }
624 }
625
626 return rc;
627}
628
629/**
630 * @interface_method_impl{ATSTRANSPORT,pfnPollSetAdd}
631 */
632static DECLCALLBACK(int) atsTcpPollSetAdd(PATSTRANSPORTINST pThis, RTPOLLSET hPollSet, PATSTRANSPORTCLIENT pClient, uint32_t idStart)
633{
634 RT_NOREF(pThis);
635 return RTPollSetAddSocket(hPollSet, pClient->hTcpClient, RTPOLL_EVT_READ | RTPOLL_EVT_ERROR, idStart);
636}
637
638/**
639 * @interface_method_impl{ATSTRANSPORT,pfnPollSetRemove}
640 */
641static DECLCALLBACK(int) atsTcpPollSetRemove(PATSTRANSPORTINST pThis, RTPOLLSET hPollSet, PATSTRANSPORTCLIENT pClient, uint32_t idStart)
642{
643 RT_NOREF(pThis, pClient);
644 return RTPollSetRemove(hPollSet, idStart);
645}
646
647/**
648 * @interface_method_impl{ATSTRANSPORT,pfnPollIn}
649 */
650static DECLCALLBACK(bool) atsTcpPollIn(PATSTRANSPORTINST pThis, PATSTRANSPORTCLIENT pClient)
651{
652 RT_NOREF(pThis);
653 int rc = RTTcpSelectOne(pClient->hTcpClient, 0/*cMillies*/);
654 return RT_SUCCESS(rc);
655}
656
657/**
658 * @interface_method_impl{ATSTRANSPORT,pfnTerm}
659 */
660static DECLCALLBACK(void) atsTcpTerm(PATSTRANSPORTINST pThis)
661{
662 /* Signal thread */
663 if (RTCritSectIsInitialized(&pThis->CritSect))
664 {
665 RTCritSectEnter(&pThis->CritSect);
666 pThis->fStopConnecting = true;
667 RTCritSectLeave(&pThis->CritSect);
668 }
669
670 if (pThis->hThreadConnect != NIL_RTTHREAD)
671 {
672 RTThreadUserSignal(pThis->hThreadConnect);
673 RTTcpClientCancelConnect(&pThis->pConnectCancelCookie);
674 }
675
676 /* Shut down the server (will wake up thread). */
677 if (pThis->pTcpServer)
678 {
679 LogFunc(("Destroying server...\n"));
680 int rc = RTTcpServerDestroy(pThis->pTcpServer);
681 if (RT_FAILURE(rc))
682 RTMsgInfo("RTTcpServerDestroy failed in atsTcpTerm: %Rrc", rc);
683 pThis->pTcpServer = NULL;
684 }
685
686 /* Wait for the thread (they should've had some time to quit by now). */
687 atsTcpConnectWaitOnThreads(pThis, 15000);
688
689 LogFunc(("Done\n"));
690}
691
692/**
693 * @interface_method_impl{ATSTRANSPORT,pfnCreate}
694 */
695static DECLCALLBACK(int) atsTcpCreate(PATSTRANSPORTINST *ppThis)
696{
697 PATSTRANSPORTINST pThis = (PATSTRANSPORTINST)RTMemAllocZ(sizeof(ATSTRANSPORTINST));
698 AssertPtrReturn(pThis, VERR_NO_MEMORY);
699
700 int rc = RTCritSectInit(&pThis->CritSect);
701 if (RT_SUCCESS(rc))
702 {
703 *ppThis = pThis;
704 }
705
706 return rc;
707}
708
709/**
710 * @interface_method_impl{ATSTRANSPORT,pfnDestroy}
711 */
712static DECLCALLBACK(int) atsTcpDestroy(PATSTRANSPORTINST pThis)
713{
714 /* Finally, clean up the critical section. */
715 if (RTCritSectIsInitialized(&pThis->CritSect))
716 RTCritSectDelete(&pThis->CritSect);
717
718 RTMemFree(pThis);
719
720 return VINF_SUCCESS;
721}
722
723/**
724 * @interface_method_impl{ATSTRANSPORT,pfnStart}
725 */
726static DECLCALLBACK(int) atsTcpStart(PATSTRANSPORTINST pThis)
727{
728 int rc = VINF_SUCCESS;
729
730 if (pThis->enmMode != ATSTCPMODE_CLIENT)
731 {
732 rc = RTTcpServerCreateEx(pThis->szBindAddr[0] ? pThis->szBindAddr : NULL, pThis->uBindPort, &pThis->pTcpServer);
733 if (RT_FAILURE(rc))
734 {
735 if (rc == VERR_NET_DOWN)
736 {
737 RTMsgInfo("RTTcpServerCreateEx(%s, %u,) failed: %Rrc, retrying for 20 seconds...\n",
738 pThis->szBindAddr[0] ? pThis->szBindAddr : NULL, pThis->uBindPort, rc);
739 uint64_t StartMs = RTTimeMilliTS();
740 do
741 {
742 RTThreadSleep(1000);
743 rc = RTTcpServerCreateEx(pThis->szBindAddr[0] ? pThis->szBindAddr : NULL, pThis->uBindPort, &pThis->pTcpServer);
744 } while ( rc == VERR_NET_DOWN
745 && RTTimeMilliTS() - StartMs < 20000);
746 if (RT_SUCCESS(rc))
747 RTMsgInfo("RTTcpServerCreateEx succceeded.\n");
748 }
749
750 if (RT_FAILURE(rc))
751 {
752 RTMsgError("RTTcpServerCreateEx(%s, %u,) failed: %Rrc\n",
753 pThis->szBindAddr[0] ? pThis->szBindAddr : NULL, pThis->uBindPort, rc);
754 }
755 }
756 }
757
758 return rc;
759}
760
761/**
762 * @interface_method_impl{ATSTRANSPORT,pfnOption}
763 */
764static DECLCALLBACK(int) atsTcpOption(PATSTRANSPORTINST pThis, int ch, PCRTGETOPTUNION pVal)
765{
766 int rc;
767
768 switch (ch)
769 {
770 case ATSTCPOPT_MODE:
771 if (!strcmp(pVal->psz, "both"))
772 pThis->enmMode = ATSTCPMODE_BOTH;
773 else if (!strcmp(pVal->psz, "client"))
774 pThis->enmMode = ATSTCPMODE_CLIENT;
775 else if (!strcmp(pVal->psz, "server"))
776 pThis->enmMode = ATSTCPMODE_SERVER;
777 else
778 return RTMsgErrorRc(VERR_INVALID_PARAMETER, "Invalid TCP mode: '%s'\n", pVal->psz);
779 return VINF_SUCCESS;
780
781 case ATSTCPOPT_BIND_ADDRESS:
782 rc = RTStrCopy(pThis->szBindAddr, sizeof(pThis->szBindAddr), pVal->psz);
783 if (RT_FAILURE(rc))
784 return RTMsgErrorRc(VERR_INVALID_PARAMETER, "TCP bind address is too long (%Rrc)", rc);
785 return VINF_SUCCESS;
786
787 case ATSTCPOPT_BIND_PORT:
788 pThis->uBindPort = pVal->u16 == 0 ? ATS_TCP_DEF_BIND_PORT_GUEST : pVal->u16;
789 return VINF_SUCCESS;
790
791 case ATSTCPOPT_CONNECT_ADDRESS:
792 rc = RTStrCopy(pThis->szConnectAddr, sizeof(pThis->szConnectAddr), pVal->psz);
793 if (RT_FAILURE(rc))
794 return RTMsgErrorRc(VERR_INVALID_PARAMETER, "TCP connect address is too long (%Rrc)", rc);
795 if (!pThis->szConnectAddr[0])
796 strcpy(pThis->szConnectAddr, ATS_TCP_DEF_CONNECT_GUEST_STR);
797 return VINF_SUCCESS;
798
799 case ATSTCPOPT_CONNECT_PORT:
800 pThis->uConnectPort = pVal->u16 == 0 ? ATS_TCP_DEF_BIND_PORT_GUEST : pVal->u16;
801 return VINF_SUCCESS;
802
803 default:
804 break;
805 }
806 return VERR_TRY_AGAIN;
807}
808
809/**
810 * @interface_method_impl{ATSTRANSPORT,pfnUsage}
811 */
812DECLCALLBACK(void) atsTcpUsage(PRTSTREAM pStream)
813{
814 RTStrmPrintf(pStream,
815 " --tcp-mode <both|client|server>\n"
816 " Selects the mode of operation.\n"
817 " Default: both\n"
818 " --tcp-bind-address <address>\n"
819 " The address(es) to listen to TCP connection on. Empty string\n"
820 " means any address, this is the default.\n"
821 " --tcp-bind-port <port>\n"
822 " The port to listen to TCP connections on.\n"
823 " Default: %u\n"
824 " --tcp-connect-address <address>\n"
825 " The address of the server to try connect to in client mode.\n"
826 " Default: " ATS_TCP_DEF_CONNECT_GUEST_STR "\n"
827 " --tcp-connect-port <port>\n"
828 " The port on the server to connect to in client mode.\n"
829 " Default: %u\n"
830 , ATS_TCP_DEF_BIND_PORT_GUEST, ATS_TCP_DEF_CONNECT_PORT_GUEST);
831}
832
833/** Command line options for the TCP/IP transport layer. */
834static const RTGETOPTDEF g_TcpOpts[] =
835{
836 { "--tcp-mode", ATSTCPOPT_MODE, RTGETOPT_REQ_STRING },
837 { "--tcp-bind-address", ATSTCPOPT_BIND_ADDRESS, RTGETOPT_REQ_STRING },
838 { "--tcp-bind-port", ATSTCPOPT_BIND_PORT, RTGETOPT_REQ_UINT16 },
839 { "--tcp-connect-address", ATSTCPOPT_CONNECT_ADDRESS, RTGETOPT_REQ_STRING },
840 { "--tcp-connect-port", ATSTCPOPT_CONNECT_PORT, RTGETOPT_REQ_UINT16 }
841};
842
843/** TCP/IP transport layer. */
844const ATSTRANSPORT g_TcpTransport =
845{
846 /* .szName = */ "tcp",
847 /* .pszDesc = */ "TCP/IP",
848 /* .cOpts = */ &g_TcpOpts[0],
849 /* .paOpts = */ RT_ELEMENTS(g_TcpOpts),
850 /* .pfnUsage = */ atsTcpUsage,
851 /* .pfnCreate = */ atsTcpCreate,
852 /* .pfnDestroy = */ atsTcpDestroy,
853 /* .pfnOption = */ atsTcpOption,
854 /* .pfnStart = */ atsTcpStart,
855 /* .pfnTerm = */ atsTcpTerm,
856 /* .pfnWaitForConnect = */ atsTcpWaitForConnect,
857 /* .pfnPollIn = */ atsTcpPollIn,
858 /* .pfnPollSetAdd = */ atsTcpPollSetAdd,
859 /* .pfnPollSetRemove = */ atsTcpPollSetRemove,
860 /* .pfnRecvPkt = */ atsTcpRecvPkt,
861 /* .pfnSendPkt = */ atsTcpSendPkt,
862 /* .pfnBabble = */ atsTcpBabble,
863 /* .pfnNotifyHowdy = */ atsTcpNotifyHowdy,
864 /* .pfnNotifyBye = */ atsTcpNotifyBye,
865 /* .pfnNotifyReboot = */ atsTcpNotifyReboot,
866 /* .u32EndMarker = */ UINT32_C(0x12345678)
867};
868
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