VirtualBox

source: vbox/trunk/src/VBox/Devices/Network/DrvCloudTunnel.cpp@ 105381

Last change on this file since 105381 was 105353, checked in by vboxsync, 4 months ago

iprt/req.h,*: Adjustments of the RTReqQueue API to fit darwin/arm64 restrictions. bugref:10725

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 69.7 KB
Line 
1/* $Id: DrvCloudTunnel.cpp 105353 2024-07-16 11:47:19Z vboxsync $ */
2/** @file
3 * DrvCloudTunnel - Cloud tunnel network transport driver
4 *
5 * Based on code contributed by Christophe Devriese
6 */
7
8/*
9 * Copyright (C) 2022-2023 Oracle and/or its affiliates.
10 *
11 * This file is part of VirtualBox base platform packages, as
12 * available from https://www.virtualbox.org.
13 *
14 * This program is free software; you can redistribute it and/or
15 * modify it under the terms of the GNU General Public License
16 * as published by the Free Software Foundation, in version 3 of the
17 * License.
18 *
19 * This program is distributed in the hope that it will be useful, but
20 * WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
22 * General Public License for more details.
23 *
24 * You should have received a copy of the GNU General Public License
25 * along with this program; if not, see <https://www.gnu.org/licenses>.
26 *
27 * SPDX-License-Identifier: GPL-3.0-only
28 */
29
30
31/*********************************************************************************************************************************
32* Header Files *
33*********************************************************************************************************************************/
34#define LOG_GROUP LOG_GROUP_DRV_CTUN
35#include <VBox/log.h>
36#include <VBox/vmm/pdmdrv.h>
37#include <VBox/vmm/pdmnetifs.h>
38#include <VBox/vmm/pdmnetinline.h>
39
40#include <iprt/asm.h>
41#include <iprt/assert.h>
42#include <iprt/ctype.h>
43#include <iprt/mem.h>
44#include <iprt/path.h>
45#include <iprt/uuid.h>
46#include <iprt/req.h>
47#include <iprt/stream.h>
48#include <iprt/string.h>
49#include <iprt/critsect.h>
50
51#include "VBoxDD.h"
52
53#ifdef RT_OS_WINDOWS
54# include <iprt/win/windows.h>
55typedef int socklen_t;
56#else
57# include <errno.h>
58 typedef int SOCKET;
59# define closesocket close
60# define INVALID_SOCKET -1
61# define SOCKET_ERROR -1
62DECLINLINE(int) WSAGetLastError() { return errno; }
63#endif
64
65/* Prevent inclusion of Winsock2.h */
66#define _WINSOCK2API_
67#include <libssh/libssh.h>
68#include <libssh/callbacks.h>
69
70
71/*********************************************************************************************************************************
72* Structures and Typedefs *
73*********************************************************************************************************************************/
74/**
75 * Cloud tunnel driver instance data.
76 *
77 * @implements PDMINETWORKUP
78 */
79typedef struct DRVCLOUDTUNNEL
80{
81 /** The network interface. */
82 PDMINETWORKUP INetworkUp;
83 /** The network interface. */
84 PPDMINETWORKDOWN pIAboveNet;
85 /** Pointer to the driver instance. */
86 PPDMDRVINS pDrvIns;
87 /** Cloud instance private key. */
88 ssh_key SshKey;
89 /** Cloud instance user. */
90 char *pszUser;
91 /** Cloud instance primary IP address. */
92 char *pszPrimaryIP;
93 /** Cloud instance primary IP address. */
94 char *pszSecondaryIP;
95 /** MAC address to set on cloud primary interface. */
96 RTMAC targetMac;
97 /** SSH connection timeout in seconds. */
98 long ulTimeoutInSecounds;
99
100 /** Primary proxy type. */
101 char *pszPrimaryProxyType;
102 /** Primary proxy server IP address. */
103 char *pszPrimaryProxyHost;
104 /** Primary proxy server port. */
105 uint16_t u16PrimaryProxyPort;
106 /** Primary proxy user. */
107 char *pszPrimaryProxyUser;
108 /** Primary proxy password. */
109 char *pszPrimaryProxyPassword;
110
111 /** Secondary proxy type. */
112 char *pszSecondaryProxyType;
113 /** Secondary proxy server IP address. */
114 char *pszSecondaryProxyHost;
115 /** Secondary proxy server port. */
116 uint16_t u16SecondaryProxyPort;
117 /** Secondary proxy user. */
118 char *pszSecondaryProxyUser;
119 /** Secondary proxy password. */
120 char *pszSecondaryProxyPassword;
121
122 /** Cloud tunnel instance string. */
123 char *pszInstance;
124 /** Cloud tunnel I/O thread unique name. */
125 char *pszInstanceIo;
126 /** Cloud tunnel device thread unique name. */
127 char *pszInstanceDev;
128
129 /** Command assembly buffer. */
130 char *pszCommandBuffer;
131 /** Command output buffer. */
132 char *pszOutputBuffer;
133 /** Name of primary interface of cloud instance. */
134 char *pszCloudPrimaryInterface;
135
136 /** Cloud destination address. */
137 RTNETADDR DestAddress;
138 /** Transmit lock used by drvCloudTunnelUp_BeginXmit. */
139 RTCRITSECT XmitLock;
140 /** Server data structure for Cloud communication. */
141// PRTCLOUDSERVER pServer;
142
143 /** RX thread for delivering packets to attached device. */
144 PPDMTHREAD pDevThread;
145 /** Queue for device-thread requests. */
146 RTREQQUEUE hDevReqQueue;
147 /** I/O thread for tunnel channel. */
148 PPDMTHREAD pIoThread;
149 /** Queue for I/O-thread requests. */
150 RTREQQUEUE hIoReqQueue;
151 /** I/O thread notification socket pair (in). */
152 SOCKET iSocketIn;
153 /** I/O thread notification socket pair (out). */
154 SOCKET iSocketOut;
155
156 /** SSH private key. */
157
158 /** SSH Log Verbosity: 0 - No log, 1 - warnings, 2 - protocol, 3 - packet, 4 - functions */
159 int iSshVerbosity;
160 /** SSH Session. */
161 ssh_session pSshSession;
162 /** SSH Tunnel Channel. */
163 ssh_channel pSshChannel;
164 /** SSH Packet Receive Callback Structure. */
165 struct ssh_channel_callbacks_struct Callbacks;
166
167 /** Flag whether the link is down. */
168 bool volatile fLinkDown;
169
170#ifdef VBOX_WITH_STATISTICS
171 /** Number of sent packets. */
172 STAMCOUNTER StatPktSent;
173 /** Number of sent bytes. */
174 STAMCOUNTER StatPktSentBytes;
175 /** Number of received packets. */
176 STAMCOUNTER StatPktRecv;
177 /** Number of received bytes. */
178 STAMCOUNTER StatPktRecvBytes;
179 /** Profiling packet transmit runs. */
180 STAMPROFILEADV StatTransmit;
181 /** Profiling packet receive runs. */
182 STAMPROFILEADV StatReceive;
183 /** Profiling packet receive device (both actual receive and waiting). */
184 STAMPROFILE StatDevRecv;
185 /** Profiling packet receive device waiting. */
186 STAMPROFILE StatDevRecvWait;
187#endif /* VBOX_WITH_STATISTICS */
188
189#ifdef LOG_ENABLED
190 /** The nano ts of the last transfer. */
191 uint64_t u64LastTransferTS;
192 /** The nano ts of the last receive. */
193 uint64_t u64LastReceiveTS;
194#endif
195} DRVCLOUDTUNNEL, *PDRVCLOUDTUNNEL;
196
197
198/** Converts a pointer to CLOUDTUNNEL::INetworkUp to a PRDVCLOUDTUNNEL. */
199#define PDMINETWORKUP_2_DRVCLOUDTUNNEL(pInterface) ( (PDRVCLOUDTUNNEL)((uintptr_t)pInterface - RT_UOFFSETOF(DRVCLOUDTUNNEL, INetworkUp)) )
200
201
202/*********************************************************************************************************************************
203* Internal Functions *
204*********************************************************************************************************************************/
205
206/**
207 * @interface_method_impl{PDMINETWORKUP,pfnBeginXmit}
208 */
209static DECLCALLBACK(int) drvCloudTunnelUp_BeginXmit(PPDMINETWORKUP pInterface, bool fOnWorkerThread)
210{
211 RT_NOREF(fOnWorkerThread);
212 PDRVCLOUDTUNNEL pThis = PDMINETWORKUP_2_DRVCLOUDTUNNEL(pInterface);
213 int rc = RTCritSectTryEnter(&pThis->XmitLock);
214 if (RT_FAILURE(rc))
215 {
216 /** @todo XMIT thread */
217 rc = VERR_TRY_AGAIN;
218 }
219 return rc;
220}
221
222/**
223 * @interface_method_impl{PDMINETWORKUP,pfnAllocBuf}
224 */
225static DECLCALLBACK(int) drvCloudTunnelUp_AllocBuf(PPDMINETWORKUP pInterface, size_t cbMin,
226 PCPDMNETWORKGSO pGso, PPPDMSCATTERGATHER ppSgBuf)
227{
228 PDRVCLOUDTUNNEL pThis = PDMINETWORKUP_2_DRVCLOUDTUNNEL(pInterface);
229 Assert(RTCritSectIsOwner(&pThis->XmitLock)); NOREF(pThis);
230
231 /*
232 * Allocate a scatter / gather buffer descriptor that is immediately
233 * followed by the buffer space of its single segment. The GSO context
234 * comes after that again.
235 */
236 PPDMSCATTERGATHER pSgBuf = (PPDMSCATTERGATHER)RTMemAlloc( RT_ALIGN_Z(sizeof(*pSgBuf), 16)
237 + RT_ALIGN_Z(cbMin, 16)
238 + (pGso ? RT_ALIGN_Z(sizeof(*pGso), 16) : 0));
239 if (!pSgBuf)
240 return VERR_NO_MEMORY;
241
242 /*
243 * Initialize the S/G buffer and return.
244 */
245 pSgBuf->fFlags = PDMSCATTERGATHER_FLAGS_MAGIC | PDMSCATTERGATHER_FLAGS_OWNER_1;
246 pSgBuf->cbUsed = 0;
247 pSgBuf->cbAvailable = RT_ALIGN_Z(cbMin, 16);
248 pSgBuf->pvAllocator = NULL;
249 if (!pGso)
250 pSgBuf->pvUser = NULL;
251 else
252 {
253 pSgBuf->pvUser = (uint8_t *)(pSgBuf + 1) + pSgBuf->cbAvailable;
254 *(PPDMNETWORKGSO)pSgBuf->pvUser = *pGso;
255 }
256 pSgBuf->cSegs = 1;
257 pSgBuf->aSegs[0].cbSeg = pSgBuf->cbAvailable;
258 pSgBuf->aSegs[0].pvSeg = pSgBuf + 1;
259
260#if 0 /* poison */
261 memset(pSgBuf->aSegs[0].pvSeg, 'F', pSgBuf->aSegs[0].cbSeg);
262#endif
263 *ppSgBuf = pSgBuf;
264 return VINF_SUCCESS;
265}
266
267
268/**
269 * @interface_method_impl{PDMINETWORKUP,pfnFreeBuf}
270 */
271static DECLCALLBACK(int) drvCloudTunnelUp_FreeBuf(PPDMINETWORKUP pInterface, PPDMSCATTERGATHER pSgBuf)
272{
273 PDRVCLOUDTUNNEL pThis = PDMINETWORKUP_2_DRVCLOUDTUNNEL(pInterface);
274 Assert(RTCritSectIsOwner(&pThis->XmitLock)); NOREF(pThis);
275 if (pSgBuf)
276 {
277 Assert((pSgBuf->fFlags & PDMSCATTERGATHER_FLAGS_MAGIC_MASK) == PDMSCATTERGATHER_FLAGS_MAGIC);
278 pSgBuf->fFlags = 0;
279 RTMemFree(pSgBuf);
280 }
281 return VINF_SUCCESS;
282}
283
284static int createConnectedSockets(PDRVCLOUDTUNNEL pThis)
285{
286 LogFlow(("%s: creating a pair of connected sockets...\n", pThis->pszInstance));
287 struct sockaddr_in inaddr;
288 struct sockaddr addr;
289 SOCKET lst = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
290 memset(&inaddr, 0, sizeof(inaddr));
291 memset(&addr, 0, sizeof(addr));
292 inaddr.sin_family = AF_INET;
293 inaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
294 inaddr.sin_port = 0;
295 int yes = 1;
296 setsockopt(lst, SOL_SOCKET, SO_REUSEADDR, (char*)&yes, sizeof(yes));
297 bind(lst, (struct sockaddr *)&inaddr, sizeof(inaddr));
298 listen(lst, 1);
299 socklen_t len=sizeof(inaddr);
300 getsockname(lst, &addr, &len);
301 pThis->iSocketOut = socket(AF_INET, SOCK_STREAM, 0);
302 connect(pThis->iSocketOut, &addr, len);
303 pThis->iSocketIn = accept(lst, 0, 0);
304 closesocket(lst);
305 Log2(("%s: socket(%d) <= socket(%d) created successfully.\n", pThis->pszInstance, pThis->iSocketIn, pThis->iSocketOut));
306 return VINF_SUCCESS;
307}
308
309
310static void destroyConnectedSockets(PDRVCLOUDTUNNEL pThis)
311{
312 if (pThis->iSocketOut != INVALID_SOCKET)
313 {
314 LogFlow(("%s: destroying output socket (%d)...\n", pThis->pszInstance, pThis->iSocketOut));
315 closesocket(pThis->iSocketOut);
316 }
317 if (pThis->iSocketIn != INVALID_SOCKET)
318 {
319 LogFlow(("%s: destroying input socket (%d)...\n", pThis->pszInstance, pThis->iSocketIn));
320 closesocket(pThis->iSocketIn);
321 }
322}
323
324
325DECLINLINE(void) drvCloudTunnelFreeSgBuf(PDRVCLOUDTUNNEL pThis, PPDMSCATTERGATHER pSgBuf)
326{
327 RT_NOREF(pThis);
328 RTMemFree(pSgBuf);
329}
330
331DECLINLINE(void) drvCloudTunnelNotifyIoThread(PDRVCLOUDTUNNEL pThis, const char *pszWho)
332{
333 RT_NOREF(pszWho);
334 int cBytes = send(pThis->iSocketOut, " ", 1, 0);
335 if (cBytes == SOCKET_ERROR)
336 LogRel(("Failed to send a signalling packet, error code %d", WSAGetLastError())); // @todo!
337
338}
339
340
341/**
342 * Worker function for sending packets on I/O thread.
343 *
344 * @param pThis Pointer to the cloud tunnel instance.
345 * @param pSgBuf The scatter/gather buffer.
346 * @thread I/O
347 */
348static DECLCALLBACK(void) drvCloudTunnelSendWorker(PDRVCLOUDTUNNEL pThis, PPDMSCATTERGATHER pSgBuf)
349{
350 // int rc = VINF_SUCCESS;
351 if (!pSgBuf->pvUser)
352 {
353#ifdef LOG_ENABLED
354 uint64_t u64Now = RTTimeProgramNanoTS();
355 LogFunc(("%-4d bytes at %llu ns deltas: r=%llu t=%llu\n",
356 pSgBuf->cbUsed, u64Now, u64Now - pThis->u64LastReceiveTS, u64Now - pThis->u64LastTransferTS));
357 pThis->u64LastTransferTS = u64Now;
358#endif
359 Log2(("writing to tunnel channel: pSgBuf->aSegs[0].pvSeg=%p pSgBuf->cbUsed=%#x\n%.*Rhxd\n",
360 pSgBuf->aSegs[0].pvSeg, pSgBuf->cbUsed, pSgBuf->cbUsed, pSgBuf->aSegs[0].pvSeg));
361
362 int cBytes = ssh_channel_write(pThis->pSshChannel, pSgBuf->aSegs[0].pvSeg, (uint32_t)pSgBuf->cbUsed);
363 if (cBytes == SSH_ERROR)
364 LogRel(("%s: ssh_channel_write failed\n", pThis->pszInstance));
365 }
366 else
367 {
368 uint8_t abHdrScratch[256];
369 uint8_t const *pbFrame = (uint8_t const *)pSgBuf->aSegs[0].pvSeg;
370 PCPDMNETWORKGSO pGso = (PCPDMNETWORKGSO)pSgBuf->pvUser;
371 uint32_t const cSegs = PDMNetGsoCalcSegmentCount(pGso, pSgBuf->cbUsed); Assert(cSegs > 1);
372 for (uint32_t iSeg = 0; iSeg < cSegs; iSeg++)
373 {
374 uint32_t cbSegFrame;
375 void *pvSegFrame = PDMNetGsoCarveSegmentQD(pGso, (uint8_t *)pbFrame, pSgBuf->cbUsed, abHdrScratch,
376 iSeg, cSegs, &cbSegFrame);
377 Log2(("writing to tunnel channel: pvSegFrame=%p cbSegFrame=%#x\n%.*Rhxd\n",
378 pvSegFrame, cbSegFrame, cbSegFrame, pvSegFrame));
379 int cBytes = ssh_channel_write(pThis->pSshChannel, pvSegFrame, cbSegFrame);
380 if (cBytes == SSH_ERROR)
381 LogRel(("%s: ssh_channel_write failed\n", pThis->pszInstance));
382 }
383 }
384
385 pSgBuf->fFlags = 0;
386 RTMemFree(pSgBuf);
387
388 STAM_PROFILE_ADV_STOP(&pThis->StatTransmit, a);
389 // AssertRC(rc);
390 // if (RT_FAILURE(rc))
391 // {
392 // if (rc == VERR_NO_MEMORY)
393 // rc = VERR_NET_NO_BUFFER_SPACE;
394 // else
395 // rc = VERR_NET_DOWN;
396 // }
397 // return rc;
398}
399
400
401/**
402 * @interface_method_impl{PDMINETWORKUP,pfnSendBuf}
403 */
404static DECLCALLBACK(int) drvCloudTunnelUp_SendBuf(PPDMINETWORKUP pInterface, PPDMSCATTERGATHER pSgBuf, bool fOnWorkerThread)
405{
406 RT_NOREF(fOnWorkerThread);
407 PDRVCLOUDTUNNEL pThis = PDMINETWORKUP_2_DRVCLOUDTUNNEL(pInterface);
408 STAM_COUNTER_INC(&pThis->StatPktSent);
409 STAM_COUNTER_ADD(&pThis->StatPktSentBytes, pSgBuf->cbUsed);
410 STAM_PROFILE_ADV_START(&pThis->StatTransmit, a);
411
412 AssertPtr(pSgBuf);
413 Assert((pSgBuf->fFlags & PDMSCATTERGATHER_FLAGS_MAGIC_MASK) == PDMSCATTERGATHER_FLAGS_MAGIC);
414 Assert(RTCritSectIsOwner(&pThis->XmitLock));
415
416 int rc = VINF_SUCCESS;
417 if (pThis->pIoThread && pThis->pIoThread->enmState == PDMTHREADSTATE_RUNNING)
418 {
419 Log2(("%s: submitting TX request (pvSeg=%p, %u bytes) to I/O queue...\n",
420 pThis->pszInstance, pSgBuf->aSegs[0].pvSeg, pSgBuf->cbUsed));
421 rc = RTReqQueueCallEx(pThis->hIoReqQueue, NULL /*ppReq*/, 0 /*cMillies*/, RTREQFLAGS_VOID | RTREQFLAGS_NO_WAIT,
422 (PFNRT)drvCloudTunnelSendWorker, 2, pThis, pSgBuf);
423
424 if (RT_SUCCESS(rc))
425 {
426 drvCloudTunnelNotifyIoThread(pThis, "drvCloudTunnelUp_SendBuf");
427 return VINF_SUCCESS;
428 }
429
430 rc = VERR_NET_NO_BUFFER_SPACE;
431 }
432 else
433 rc = VERR_NET_DOWN;
434 drvCloudTunnelFreeSgBuf(pThis, pSgBuf);
435 return rc;
436}
437
438
439/**
440 * @interface_method_impl{PDMINETWORKUP,pfnEndXmit}
441 */
442static DECLCALLBACK(void) drvCloudTunnelUp_EndXmit(PPDMINETWORKUP pInterface)
443{
444 PDRVCLOUDTUNNEL pThis = PDMINETWORKUP_2_DRVCLOUDTUNNEL(pInterface);
445 RTCritSectLeave(&pThis->XmitLock);
446}
447
448
449/**
450 * @interface_method_impl{PDMINETWORKUP,pfnSetPromiscuousMode}
451 */
452static DECLCALLBACK(void) drvCloudTunnelUp_SetPromiscuousMode(PPDMINETWORKUP pInterface, bool fPromiscuous)
453{
454 RT_NOREF(pInterface, fPromiscuous);
455 LogFlowFunc(("fPromiscuous=%d\n", fPromiscuous));
456 /* nothing to do */
457}
458
459
460/**
461 * Notification on link status changes.
462 *
463 * @param pInterface Pointer to the interface structure containing the called function pointer.
464 * @param enmLinkState The new link state.
465 * @thread EMT
466 */
467static DECLCALLBACK(void) drvCloudTunnelUp_NotifyLinkChanged(PPDMINETWORKUP pInterface, PDMNETWORKLINKSTATE enmLinkState)
468{
469 LogFlowFunc(("enmLinkState=%d\n", enmLinkState));
470 PDRVCLOUDTUNNEL pThis = PDMINETWORKUP_2_DRVCLOUDTUNNEL(pInterface);
471
472 bool fLinkDown;
473 switch (enmLinkState)
474 {
475 case PDMNETWORKLINKSTATE_DOWN:
476 case PDMNETWORKLINKSTATE_DOWN_RESUME:
477 fLinkDown = true;
478 break;
479 default:
480 AssertMsgFailed(("enmLinkState=%d\n", enmLinkState));
481 RT_FALL_THRU();
482 case PDMNETWORKLINKSTATE_UP:
483 fLinkDown = false;
484 break;
485 }
486 ASMAtomicXchgSize(&pThis->fLinkDown, fLinkDown);
487}
488
489
490
491/* -=-=-=-=- PDMIBASE -=-=-=-=- */
492
493/**
494 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
495 */
496static DECLCALLBACK(void *) drvCloudTunnelQueryInterface(PPDMIBASE pInterface, const char *pszIID)
497{
498 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
499 PDRVCLOUDTUNNEL pThis = PDMINS_2_DATA(pDrvIns, PDRVCLOUDTUNNEL);
500
501 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pDrvIns->IBase);
502 PDMIBASE_RETURN_INTERFACE(pszIID, PDMINETWORKUP, &pThis->INetworkUp);
503 return NULL;
504}
505
506
507/**
508 * I/O thread handling the libssh I/O.
509 *
510 * The libssh implementation is single-threaded so we perform I/O in a
511 * dedicated thread. We take care that this thread does not become the
512 * bottleneck: If the guest wants to send, a request is enqueued into the
513 * hIoReqQueue and is handled asynchronously by this thread. TODO:If this thread
514 * wants to deliver packets to the guest, it enqueues a request into
515 * hRecvReqQueue which is later handled by the Recv thread.
516 */
517static DECLCALLBACK(int) drvCloudTunnelIoThread(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
518{
519 PDRVCLOUDTUNNEL pThis = PDMINS_2_DATA(pDrvIns, PDRVCLOUDTUNNEL);
520 // int nFDs = -1;
521
522 LogFlow(("%s: started I/O thread %p\n", pThis->pszInstance, pThread));
523
524 if (pThread->enmState == PDMTHREADSTATE_INITIALIZING)
525 return VINF_SUCCESS;
526
527 // if (pThis->enmLinkStateWant != pThis->enmLinkState)
528 // drvNATNotifyLinkChangedWorker(pThis, pThis->enmLinkStateWant);
529
530 /*
531 * Polling loop.
532 */
533 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
534 {
535 /*
536 * To prevent concurrent execution of sending/receiving threads
537 */
538//#ifndef RT_OS_WINDOWS
539 // /* process _all_ outstanding requests but don't wait */
540 // RTReqQueueProcess(pThis->hIoReqQueue, 0);
541 // RTMemFree(polls);
542//#else /* RT_OS_WINDOWS */
543
544 struct timeval timeout;
545 ssh_channel in_channels[2], out_channels[2];
546 fd_set fds;
547 int maxfd;
548
549 timeout.tv_sec = 30;
550 timeout.tv_usec = 0;
551 in_channels[0] = pThis->pSshChannel;
552 in_channels[1] = NULL;
553 FD_ZERO(&fds);
554 FD_SET(pThis->iSocketIn, &fds);
555 maxfd = pThis->iSocketIn + 1;
556
557 ssh_select(in_channels, out_channels, maxfd, &fds, &timeout);
558
559 /* Poll will call the receive callback on each packet coming from the tunnel. */
560 if (out_channels[0] != NULL)
561 ssh_channel_poll(pThis->pSshChannel, false);
562
563 /* Did we get notified by drvCloudTunnelNotifyIoThread() via connected sockets? */
564 if (FD_ISSET(pThis->iSocketIn, &fds))
565 {
566 char buf[2];
567 recv(pThis->iSocketIn, buf, 1, 0);
568 /* process all outstanding requests but don't wait */
569 RTReqQueueProcess(pThis->hIoReqQueue, 0);
570 }
571//#endif /* RT_OS_WINDOWS */
572 }
573
574 LogFlow(("%s: I/O thread %p terminated\n", pThis->pszInstance, pThread));
575
576 return VINF_SUCCESS;
577}
578
579
580/**
581 * Unblock the I/O thread so it can respond to a state change.
582 *
583 * @returns VBox status code.
584 * @param pDevIns The pcnet device instance.
585 * @param pThread The send thread.
586 */
587static DECLCALLBACK(int) drvCloudTunnelIoWakeup(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
588{
589 RT_NOREF(pThread);
590 PDRVCLOUDTUNNEL pThis = PDMINS_2_DATA(pDrvIns, PDRVCLOUDTUNNEL);
591
592 LogFlow(("%s: waking up I/O thread %p...\n", pThis->pszInstance, pThread));
593
594 drvCloudTunnelNotifyIoThread(pThis, "drvCloudTunnelIoWakeup");
595 return VINF_SUCCESS;
596}
597
598
599/*
600 * Remove the following cut&paste code after a while, when
601 * we are positive that no frames get coalesced!
602 */
603#define VBOX_CTUN_COALESCED_FRAME_DETECTION
604#ifdef VBOX_CTUN_COALESCED_FRAME_DETECTION
605struct ssh_buffer_struct {
606 bool secure;
607 size_t used;
608 size_t allocated;
609 size_t pos;
610 uint8_t *data;
611};
612
613/** @internal
614 * Describes the different possible states in a
615 * outgoing (client) channel request
616 */
617enum ssh_channel_request_state_e {
618 /** No request has been made */
619 SSH_CHANNEL_REQ_STATE_NONE = 0,
620 /** A request has been made and answer is pending */
621 SSH_CHANNEL_REQ_STATE_PENDING,
622 /** A request has been replied and accepted */
623 SSH_CHANNEL_REQ_STATE_ACCEPTED,
624 /** A request has been replied and refused */
625 SSH_CHANNEL_REQ_STATE_DENIED,
626 /** A request has been replied and an error happend */
627 SSH_CHANNEL_REQ_STATE_ERROR
628};
629
630enum ssh_channel_state_e {
631 SSH_CHANNEL_STATE_NOT_OPEN = 0,
632 SSH_CHANNEL_STATE_OPENING,
633 SSH_CHANNEL_STATE_OPEN_DENIED,
634 SSH_CHANNEL_STATE_OPEN,
635 SSH_CHANNEL_STATE_CLOSED
636};
637
638/* The channel has been closed by the remote side */
639#define SSH_CHANNEL_FLAG_CLOSED_REMOTE 0x0001
640
641/* The channel has been closed locally */
642#define SSH_CHANNEL_FLAG_CLOSED_LOCAL 0x0002
643
644/* The channel has been freed by the calling program */
645#define SSH_CHANNEL_FLAG_FREED_LOCAL 0x0004
646
647/* the channel has not yet been bound to a remote one */
648#define SSH_CHANNEL_FLAG_NOT_BOUND 0x0008
649
650struct ssh_channel_struct {
651 ssh_session session; /* SSH_SESSION pointer */
652 uint32_t local_channel;
653 uint32_t local_window;
654 int local_eof;
655 uint32_t local_maxpacket;
656
657 uint32_t remote_channel;
658 uint32_t remote_window;
659 int remote_eof; /* end of file received */
660 uint32_t remote_maxpacket;
661 enum ssh_channel_state_e state;
662 int delayed_close;
663 int flags;
664 ssh_buffer stdout_buffer;
665 ssh_buffer stderr_buffer;
666 void *userarg;
667 int exit_status;
668 enum ssh_channel_request_state_e request_state;
669 struct ssh_list *callbacks; /* list of ssh_channel_callbacks */
670
671 /* counters */
672 ssh_counter counter;
673};
674#endif /* VBOX_CTUN_COALESCED_FRAME_DETECTION */
675
676/**
677 * Worker function for delivering receive packets to the attached device.
678 *
679 * @param pThis Pointer to the cloud tunnel instance.
680 * @param pbData Packet data.
681 * @param u32Len Packet length.
682 * @thread Dev
683 */
684static DECLCALLBACK(void) drvCloudTunnelReceiveWorker(PDRVCLOUDTUNNEL pThis, uint8_t *pbData, uint32_t u32Len)
685{
686 AssertPtrReturnVoid(pbData);
687 AssertReturnVoid(u32Len!=0);
688
689 STAM_PROFILE_START(&pThis->StatDevRecv, a);
690
691 Log2(("%s: waiting until device is ready to receive...\n", pThis->pszInstance));
692 STAM_PROFILE_START(&pThis->StatDevRecvWait, b);
693 int rc = pThis->pIAboveNet->pfnWaitReceiveAvail(pThis->pIAboveNet, RT_INDEFINITE_WAIT);
694 STAM_PROFILE_STOP(&pThis->StatDevRecvWait, b);
695
696 if (RT_SUCCESS(rc))
697 {
698 Log2(("%s: delivering %u-byte packet to attached device...\n", pThis->pszInstance, u32Len));
699 rc = pThis->pIAboveNet->pfnReceive(pThis->pIAboveNet, pbData, u32Len);
700 AssertRC(rc);
701 }
702
703 RTMemFree(pbData);
704 STAM_PROFILE_STOP(&pThis->StatDevRecv, a);
705 STAM_PROFILE_ADV_STOP(&pThis->StatReceive, a);
706}
707
708static int drvCloudTunnelReceiveCallback(ssh_session session, ssh_channel channel, void* data, uint32_t len, int is_stderr, void* userdata)
709{
710 RT_NOREF(session);
711 PDRVCLOUDTUNNEL pThis = (PDRVCLOUDTUNNEL)userdata;
712
713 Log2(("drvCloudTunnelReceiveCallback: len=%d is_stderr=%s\n", len, is_stderr ? "true" : "false"));
714 if (ASMAtomicReadBool(&pThis->fLinkDown))
715 {
716 Log2(("drvCloudTunnelReceiveCallback: ignoring packet as the link is down\n"));
717 return len;
718 }
719
720#ifdef VBOX_CTUN_COALESCED_FRAME_DETECTION
721 if (channel->stdout_buffer->data != data)
722 LogRel(("drvCloudTunnelReceiveCallback: coalesced frames!\n"));
723#endif /* VBOX_CTUN_COALESCED_FRAME_DETECTION */
724
725 if (is_stderr)
726 {
727 LogRel(("%s: [REMOTE] %.*s", pThis->pszInstance, len, data));
728 return 0;
729 }
730
731 STAM_PROFILE_ADV_START(&pThis->StatReceive, a);
732
733 if (pThis->iSshVerbosity >= SSH_LOG_PACKET)
734 Log2(("%.*Rhxd\n", len, data));
735
736 /** @todo Validate len! */
737 void *pvPacket = RTMemDup(data, len);
738 if (!pvPacket)
739 {
740 LogRel(("%s: failed to allocate %d bytes\n", pThis->pszInstance, len));
741 STAM_PROFILE_ADV_STOP(&pThis->StatReceive, a);
742 return len;
743 }
744 int rc = RTReqQueueCallEx(pThis->hDevReqQueue, NULL /*ppReq*/, 0 /*cMillies*/, RTREQFLAGS_VOID | RTREQFLAGS_NO_WAIT,
745 (PFNRT)drvCloudTunnelReceiveWorker, 3, pThis, pvPacket, len);
746 if (RT_FAILURE(rc))
747 {
748 LogRel(("%s: failed to enqueue device request - %Rrc\n", pThis->pszInstance, rc));
749 STAM_PROFILE_ADV_STOP(&pThis->StatReceive, a);
750 }
751
752 return len;
753}
754
755
756/* See ssh_channel_write_wontblock_callback in libssh/callbacks.h. */
757#if LIBSSH_VERSION_INT >= SSH_VERSION_INT(0,10,0)
758static int channelWriteWontblockCallback(ssh_session, ssh_channel, uint32_t, void *)
759#else
760static int channelWriteWontblockCallback(ssh_session, ssh_channel, size_t, void *)
761#endif
762{
763 return 0;
764}
765
766
767
768/**
769 * This thread feeds the attached device with the packets received from the tunnel.
770 *
771 * This thread is needed because we cannot block I/O thread waiting for the attached
772 * device to become ready to receive packets coming from the tunnel.
773 */
774static DECLCALLBACK(int) drvCloudTunnelDevThread(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
775{
776 PDRVCLOUDTUNNEL pThis = PDMINS_2_DATA(pDrvIns, PDRVCLOUDTUNNEL);
777
778 LogFlow(("%s: device thread %p started\n", pThis->pszInstance, pThread));
779
780 if (pThread->enmState == PDMTHREADSTATE_INITIALIZING)
781 return VINF_SUCCESS;
782
783 /*
784 * Request processing loop.
785 */
786 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
787 {
788 int rc = RTReqQueueProcess(pThis->hDevReqQueue, RT_INDEFINITE_WAIT);
789 Log2(("drvCloudTunnelDevThread: RTReqQueueProcess returned '%Rrc'\n", rc));
790 if (RT_FAILURE(rc))
791 LogRel(("%s: failed to process device request with '%Rrc'\n", pThis->pszInstance, rc));
792 }
793
794 LogFlow(("%s: device thread %p terminated\n", pThis->pszInstance, pThread));
795 return VINF_SUCCESS;
796}
797
798
799static DECLCALLBACK(int) drvCloudTunnelReceiveWakeup(PDRVCLOUDTUNNEL pThis)
800{
801 NOREF(pThis);
802 /* Returning a VINF_* will cause RTReqQueueProcess return. */
803 return VWRN_STATE_CHANGED;
804}
805
806/**
807 * Unblock the I/O thread so it can respond to a state change.
808 *
809 * @returns VBox status code.
810 * @param pDevIns The pcnet device instance.
811 * @param pThread The send thread.
812 */
813static DECLCALLBACK(int) drvCloudTunnelDevWakeup(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
814{
815 RT_NOREF(pThread);
816 PDRVCLOUDTUNNEL pThis = PDMINS_2_DATA(pDrvIns, PDRVCLOUDTUNNEL);
817 LogFlow(("%s: waking up device thread %p...\n", pThis->pszInstance, pThread));
818
819 /* Wake up device thread. */
820 PRTREQ pReq;
821 int rc = RTReqQueueCall(pThis->hDevReqQueue, &pReq, 10000 /*cMillies*/, (PFNRT)drvCloudTunnelReceiveWakeup, 1, pThis);
822 if (RT_FAILURE(rc))
823 LogRel(("%s: failed to wake up device thread - %Rrc\n", pThis->pszInstance, rc));
824 if (RT_SUCCESS(rc))
825 RTReqRelease(pReq);
826
827 return rc;
828}
829
830#define DRVCLOUDTUNNEL_COMMAND_BUFFER_SIZE 1024
831#define DRVCLOUDTUNNEL_OUTPUT_BUFFER_SIZE 65536
832
833static int drvCloudTunnelExecuteRemoteCommandNoOutput(PDRVCLOUDTUNNEL pThis, const char *pcszCommand, ...)
834{
835 va_list va;
836 va_start(va, pcszCommand);
837 ssize_t const cch = RTStrPrintf2V(pThis->pszCommandBuffer, DRVCLOUDTUNNEL_COMMAND_BUFFER_SIZE, pcszCommand, va);
838 va_end(va);
839 if (cch <= 0)
840 {
841 Log(("%s: Failed to process '%s'\n", pThis->pszInstance, pcszCommand));
842 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
843 N_("Failed to compose command line"));
844 }
845
846 LogFlow(("%s: [REMOTE] executing '%s'...\n", pThis->pszInstance, pThis->pszCommandBuffer));
847
848 ssh_channel channel = ssh_channel_new(pThis->pSshSession);
849 if (channel == NULL)
850 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
851 N_("Failed to allocate new channel"));
852
853 int rc = ssh_channel_open_session(channel);
854 if (rc != SSH_OK)
855 rc = PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
856 N_("Failed to open session channel"));
857 else
858 {
859 rc = ssh_channel_request_exec(channel, pThis->pszCommandBuffer);
860 if (rc != SSH_OK)
861 {
862 LogRel(("%s: Failed to execute '%s'\n", pThis->pszInstance, pThis->pszCommandBuffer));
863 Log(("%s: Failed to execute '%s'\n", pThis->pszInstance, pThis->pszCommandBuffer));
864 rc = PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
865 N_("Execute request failed with %d"), rc);
866 }
867 ssh_channel_close(channel);
868 }
869 ssh_channel_free(channel);
870
871 return rc;
872}
873
874
875static int drvCloudTunnelExecuteRemoteCommand(PDRVCLOUDTUNNEL pThis, const char *pcszCommand, ...)
876{
877 va_list va;
878 va_start(va, pcszCommand);
879 ssize_t const cch = RTStrPrintf2V(pThis->pszCommandBuffer, DRVCLOUDTUNNEL_COMMAND_BUFFER_SIZE, pcszCommand, va);
880 va_end(va);
881 if (cch <= 0)
882 {
883 Log(("%s: Failed to process '%s'\n", pThis->pszInstance, pcszCommand));
884 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
885 N_("Failed to compose command line"));
886 }
887
888 LogFlow(("%s: [REMOTE] executing '%s'...\n", pThis->pszInstance, pThis->pszCommandBuffer));
889
890 ssh_channel channel = ssh_channel_new(pThis->pSshSession);
891 if (channel == NULL)
892 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
893 N_("Failed to allocate new channel"));
894
895 int rc = ssh_channel_open_session(channel);
896 if (rc != SSH_OK)
897 rc = PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
898 N_("Failed to open session channel"));
899 else
900 {
901 rc = ssh_channel_request_exec(channel, pThis->pszCommandBuffer);
902 if (rc != SSH_OK)
903 {
904 LogRel(("%s: Failed to execute '%s'\n", pThis->pszInstance, pThis->pszCommandBuffer));
905 Log(("%s: Failed to execute '%s'\n", pThis->pszInstance, pThis->pszCommandBuffer));
906 rc = PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
907 N_("Execute request failed with %d"), rc);
908 }
909 else
910 {
911 int cbSpaceLeft = DRVCLOUDTUNNEL_OUTPUT_BUFFER_SIZE;
912 int cbStdOut = 0;
913 char *pszBuffer = pThis->pszOutputBuffer;
914 int cBytes = ssh_channel_read_timeout(channel, pszBuffer, cbSpaceLeft, 0, 60000 /* ms */); /* Is 60 seconds really enough? */
915 while (cBytes > 0)
916 {
917 cbStdOut += cBytes;
918 pszBuffer += cBytes;
919 cbSpaceLeft -= cBytes;
920 if (cbSpaceLeft <= 0)
921 break;
922 cBytes = ssh_channel_read_timeout(channel, pszBuffer, cbSpaceLeft, 0, 60000 /* ms */); /* Is 60 seconds really enough? */
923 }
924 if (cBytes < 0)
925 {
926 LogRel(("%s: while executing '%s' ssh_channel_read_timeout returned error\n", pThis->pszInstance, pThis->pszCommandBuffer));
927 Log(("%s: while executing '%s' ssh_channel_read_timeout returned error\n", pThis->pszInstance, pThis->pszCommandBuffer));
928 rc = VERR_INTERNAL_ERROR;
929 }
930 else
931 {
932 /* Make sure the buffer is terminated. */
933 if (cbStdOut < DRVCLOUDTUNNEL_OUTPUT_BUFFER_SIZE)
934 if (cbStdOut > 1 && pThis->pszOutputBuffer[cbStdOut - 1] == '\n')
935 pThis->pszOutputBuffer[cbStdOut - 1] = 0; /* Trim newline */
936 else
937 pThis->pszOutputBuffer[cbStdOut] = 0;
938 else
939 pThis->pszOutputBuffer[DRVCLOUDTUNNEL_OUTPUT_BUFFER_SIZE - 1] = 0; /* No choice but to eat up last character. Could have returned warning though. */
940 if (cbStdOut == 0)
941 Log(("%s: received no output from remote console\n", pThis->pszInstance));
942 else
943 Log(("%s: received output from remote console:\n%s\n", pThis->pszInstance, pThis->pszOutputBuffer));
944 rc = VINF_SUCCESS;
945
946 char *pszErrorBuffer = (char *)RTMemAlloc(DRVCLOUDTUNNEL_OUTPUT_BUFFER_SIZE);
947 if (pszErrorBuffer == NULL)
948 {
949 LogRel(("%s: Failed to allocate error buffer\n", pThis->pszInstance));
950 rc = VERR_INTERNAL_ERROR;
951 }
952 else
953 {
954 /* Report errors if there were any */
955 cBytes = ssh_channel_read_timeout(channel, pszErrorBuffer, DRVCLOUDTUNNEL_OUTPUT_BUFFER_SIZE, 1, 0); /* Peek at stderr */
956 if (cBytes > 0)
957 {
958 LogRel(("%s: WARNING! While executing '%s' remote console reported errors:\n", pThis->pszInstance, pThis->pszCommandBuffer));
959 Log(("%s: WARNING! While executing '%s' remote console reported errors:\n", pThis->pszInstance, pThis->pszCommandBuffer));
960 }
961 while (cBytes > 0)
962 {
963 LogRel(("%.*s", cBytes, pszErrorBuffer));
964 Log(("%.*s", cBytes, pszErrorBuffer));
965 cBytes = ssh_channel_read_timeout(channel, pszErrorBuffer, DRVCLOUDTUNNEL_OUTPUT_BUFFER_SIZE, 1, 1000); /* Wait for a second for more error output */
966 }
967 RTMemFree(pszErrorBuffer);
968 }
969 }
970 ssh_channel_send_eof(channel);
971 }
972 ssh_channel_close(channel);
973 }
974 ssh_channel_free(channel);
975
976 return rc;
977}
978
979
980static int drvCloudTunnelCloudInstanceInitialConfig(PDRVCLOUDTUNNEL pThis)
981{
982 LogFlow(("%s: configuring cloud instance...\n", pThis->pszInstance));
983
984 int rc = drvCloudTunnelExecuteRemoteCommand(pThis, "python3 -c \"from oci_utils.vnicutils import VNICUtils; cfg = VNICUtils().get_network_config(); print('CONFIG:', [i['IFACE'] for i in cfg if 'IS_PRIMARY' in i][0], [i['IFACE']+' '+i['VIRTRT'] for i in cfg if not 'IS_PRIMARY' in i][0])\"");
985 if (RT_FAILURE(rc))
986 rc = PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
987 N_("Failed to get network config via console channel"));
988 else
989 {
990 char *pszConfig = RTStrStr(pThis->pszOutputBuffer, "CONFIG: ");
991 if (!pszConfig)
992 rc = PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
993 N_("Failed to parse network config"));
994 else
995 {
996 char **ppapszTokens;
997 size_t cTokens;
998 rc = RTStrSplit(pszConfig + 8, DRVCLOUDTUNNEL_OUTPUT_BUFFER_SIZE - (pszConfig - pThis->pszOutputBuffer) - 8,
999 " ", &ppapszTokens, &cTokens);
1000 if (RT_SUCCESS(rc))
1001 {
1002 /*
1003 * There should be exactly three tokens:
1004 * 1) Primary network interface name;
1005 * 2) Secondary network interface name;
1006 * 3) Secondary network gateway address.
1007 */
1008 if (cTokens != 3)
1009 Log(("%s: Got %u tokes instead of three while parsing '%s'\n", pThis->pszInstance, cTokens, pThis->pszOutputBuffer));
1010 else
1011 {
1012 char *pszSecondaryInterface = NULL;
1013 char *pszSecondaryGateway = NULL;
1014
1015 if (pThis->pszCloudPrimaryInterface)
1016 RTStrFree(pThis->pszCloudPrimaryInterface);
1017 pThis->pszCloudPrimaryInterface = RTStrDup(ppapszTokens[0]);
1018 pszSecondaryInterface = ppapszTokens[1];
1019 pszSecondaryGateway = ppapszTokens[2];
1020 Log(("%s: primary=%s secondary=%s gateway=%s\n", pThis->pszInstance, pThis->pszCloudPrimaryInterface, pszSecondaryInterface, pszSecondaryGateway));
1021
1022 rc = drvCloudTunnelExecuteRemoteCommand(pThis, "sudo oci-network-config -c");
1023 if (RT_SUCCESS(rc))
1024 rc = drvCloudTunnelExecuteRemoteCommand(pThis, "sudo ip tuntap add dev tap0 mod tap user opc");
1025 if (RT_SUCCESS(rc))
1026 rc = drvCloudTunnelExecuteRemoteCommand(pThis, "sudo sh -c 'echo \"PermitTunnel yes\" >> /etc/ssh/sshd_config'");
1027 if (RT_SUCCESS(rc))
1028 rc = drvCloudTunnelExecuteRemoteCommand(pThis, "sudo kill -SIGHUP $(pgrep -f \"sshd -D\")");
1029 if (RT_SUCCESS(rc))
1030 rc = drvCloudTunnelExecuteRemoteCommand(pThis, "sudo ip link add name br0 type bridge");
1031 if (RT_SUCCESS(rc))
1032 rc = drvCloudTunnelExecuteRemoteCommand(pThis, "sudo ip link set dev tap0 master br0");
1033 if (RT_SUCCESS(rc))
1034 rc = drvCloudTunnelExecuteRemoteCommandNoOutput(pThis, "sudo ip route change default via %s dev %s", pszSecondaryGateway, pszSecondaryInterface);
1035 if (RT_FAILURE(rc))
1036 rc = PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1037 N_("Failed to execute network config command via console channel"));
1038 }
1039
1040 for (size_t i = 0; i < cTokens; i++)
1041 RTStrFree(ppapszTokens[i]);
1042 RTMemFree(ppapszTokens);
1043 }
1044 }
1045 }
1046
1047 return rc;
1048}
1049
1050
1051static int drvCloudTunnelCloudInstanceFinalConfig(PDRVCLOUDTUNNEL pThis)
1052{
1053 if (pThis->pszCloudPrimaryInterface == NULL)
1054 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1055 N_("Failed to finalize cloud instance config because of unknown primary interface name!"));
1056
1057 LogFlow(("%s: finalizing cloud instance configuration...\n", pThis->pszInstance));
1058
1059 int rc = drvCloudTunnelExecuteRemoteCommand(pThis, "sudo ip link set dev %s down", pThis->pszCloudPrimaryInterface);
1060 if (RT_SUCCESS(rc))
1061 rc = drvCloudTunnelExecuteRemoteCommand(pThis, "sudo ip link set dev %s address %RTmac", pThis->pszCloudPrimaryInterface, pThis->targetMac.au8);
1062 if (RT_SUCCESS(rc))
1063 rc = drvCloudTunnelExecuteRemoteCommand(pThis, "sudo ifconfig %s 0.0.0.0", pThis->pszCloudPrimaryInterface); /* Make sure no IP is configured on primary */
1064 if (RT_SUCCESS(rc))
1065 rc = drvCloudTunnelExecuteRemoteCommand(pThis, "sudo ip link set dev %s master br0", pThis->pszCloudPrimaryInterface);
1066 if (RT_SUCCESS(rc))
1067 rc = drvCloudTunnelExecuteRemoteCommand(pThis, "sudo ip link set dev %s up", pThis->pszCloudPrimaryInterface);
1068 if (RT_SUCCESS(rc))
1069 rc = drvCloudTunnelExecuteRemoteCommand(pThis, "sudo ip link set dev tap0 up");
1070 if (RT_SUCCESS(rc))
1071 rc = drvCloudTunnelExecuteRemoteCommand(pThis, "sudo ip link set dev br0 up");
1072 if (RT_FAILURE(rc))
1073 rc = PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1074 N_("Failed to execute network config command via console channel"));
1075
1076 return rc;
1077}
1078
1079
1080static int drvCloudTunnelOpenTunnelChannel(PDRVCLOUDTUNNEL pThis)
1081{
1082 LogFlow(("%s: opening tunnel channel...\n", pThis->pszInstance));
1083 pThis->pSshChannel = ssh_channel_new(pThis->pSshSession);
1084 if (pThis->pSshChannel == NULL)
1085 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1086 N_("Failed to allocate new channel"));
1087 int rc = ssh_channel_open_tunnel(pThis->pSshChannel, 0);
1088 if (rc < 0)
1089 rc = PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1090 N_("Failed to open tunnel channel"));
1091 else
1092 {
1093 /* Set packet receive callback. */
1094 rc = ssh_set_channel_callbacks(pThis->pSshChannel, &pThis->Callbacks);
1095 if (rc != SSH_OK)
1096 rc = PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1097 N_("Failed to set packet receive callback"));
1098 }
1099
1100 return rc;
1101}
1102
1103
1104static void closeTunnelChannel(PDRVCLOUDTUNNEL pThis)
1105{
1106 if (pThis->pSshChannel)
1107 {
1108 LogFlow(("%s: closing tunnel channel %p\n", pThis->pszInstance, pThis->pSshChannel));
1109 ssh_channel_close(pThis->pSshChannel);
1110 ssh_channel_free(pThis->pSshChannel);
1111 pThis->pSshChannel = NULL;
1112 }
1113}
1114
1115
1116static int drvCloudTunnelStartIoThread(PDRVCLOUDTUNNEL pThis)
1117{
1118 LogFlow(("%s: starting I/O thread...\n", pThis->pszInstance));
1119 int rc = createConnectedSockets(pThis);
1120 if (RT_FAILURE(rc))
1121 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1122 N_("CloudTunnel: Failed to create a pair of connected sockets"));
1123
1124 /*
1125 * Start the cloud I/O thread.
1126 */
1127 rc = PDMDrvHlpThreadCreate(pThis->pDrvIns, &pThis->pIoThread,
1128 pThis, drvCloudTunnelIoThread, drvCloudTunnelIoWakeup,
1129 64 * _1K, RTTHREADTYPE_IO, pThis->pszInstanceIo);
1130 if (RT_FAILURE(rc))
1131 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1132 N_("CloudTunnel: Failed to start I/O thread"));
1133
1134 return rc;
1135}
1136
1137static void drvCloudTunnelStopIoThread(PDRVCLOUDTUNNEL pThis)
1138{
1139 if (pThis->pIoThread)
1140 {
1141 LogFlow(("%s: stopping I/O thread...\n", pThis->pszInstance));
1142 int rc = PDMDrvHlpThreadDestroy(pThis->pDrvIns, pThis->pIoThread, NULL);
1143 AssertRC(rc);
1144 pThis->pIoThread = NULL;
1145 }
1146 destroyConnectedSockets(pThis);
1147
1148}
1149
1150static int destroyTunnel(PDRVCLOUDTUNNEL pThis)
1151{
1152 if (pThis->pSshChannel)
1153 {
1154 int rc = ssh_remove_channel_callbacks(pThis->pSshChannel, &pThis->Callbacks);
1155 if (rc != SSH_OK)
1156 LogRel(("%s: WARNING! Failed to remove tunnel channel callbacks.\n", pThis->pszInstance));
1157 }
1158 drvCloudTunnelStopIoThread(pThis);
1159 closeTunnelChannel(pThis);
1160 ssh_disconnect(pThis->pSshSession);
1161 ssh_free(pThis->pSshSession);
1162 pThis->pSshSession = NULL;
1163 return VINF_SUCCESS;
1164}
1165
1166
1167static int drvCloudTunnelNewSession(PDRVCLOUDTUNNEL pThis, bool fPrimary)
1168{
1169 pThis->pSshSession = ssh_new();
1170 if (pThis->pSshSession == NULL)
1171 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1172 N_("CloudTunnel: Failed to allocate new SSH session"));
1173 if (ssh_options_set(pThis->pSshSession, SSH_OPTIONS_LOG_VERBOSITY, &pThis->iSshVerbosity) < 0)
1174 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1175 N_("Failed to set SSH_OPTIONS_LOG_VERBOSITY"));
1176 if (ssh_options_set(pThis->pSshSession, SSH_OPTIONS_USER, pThis->pszUser) < 0)
1177 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1178 N_("Failed to set SSH_OPTIONS_USER"));
1179 if (ssh_options_set(pThis->pSshSession, SSH_OPTIONS_HOST, fPrimary ? pThis->pszPrimaryIP : pThis->pszSecondaryIP) < 0)
1180 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1181 N_("Failed to set SSH_OPTIONS_HOST"));
1182
1183 if (ssh_options_set(pThis->pSshSession, SSH_OPTIONS_TIMEOUT, &pThis->ulTimeoutInSecounds) < 0)
1184 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1185 N_("Failed to set SSH_OPTIONS_TIMEOUT"));
1186
1187 const char *pcszProxyType = fPrimary ? pThis->pszPrimaryProxyType : pThis->pszSecondaryProxyType;
1188 if (pcszProxyType)
1189 {
1190 char szProxyCmd[1024];
1191
1192 const char *pcszProxyUser = fPrimary ? pThis->pszPrimaryProxyUser : pThis->pszSecondaryProxyUser;
1193 if (pcszProxyUser)
1194 RTStrPrintf(szProxyCmd, sizeof(szProxyCmd), "#VBoxProxy%s %s %u %s %s",
1195 fPrimary ? pThis->pszPrimaryProxyType : pThis->pszSecondaryProxyType,
1196 fPrimary ? pThis->pszPrimaryProxyHost : pThis->pszSecondaryProxyHost,
1197 fPrimary ? pThis->u16PrimaryProxyPort : pThis->u16SecondaryProxyPort,
1198 fPrimary ? pThis->pszPrimaryProxyUser : pThis->pszSecondaryProxyUser,
1199 fPrimary ? pThis->pszPrimaryProxyPassword : pThis->pszSecondaryProxyPassword);
1200 else
1201 RTStrPrintf(szProxyCmd, sizeof(szProxyCmd), "#VBoxProxy%s %s %u",
1202 fPrimary ? pThis->pszPrimaryProxyType : pThis->pszSecondaryProxyType,
1203 fPrimary ? pThis->pszPrimaryProxyHost : pThis->pszSecondaryProxyHost,
1204 fPrimary ? pThis->u16PrimaryProxyPort : pThis->u16SecondaryProxyPort);
1205 LogRel(("%s: using proxy command '%s'\n", pThis->pszInstance, szProxyCmd));
1206 if (ssh_options_set(pThis->pSshSession, SSH_OPTIONS_PROXYCOMMAND, szProxyCmd) < 0)
1207 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1208 N_("Failed to set SSH_OPTIONS_PROXYCOMMAND"));
1209 }
1210
1211 int rc = ssh_connect(pThis->pSshSession);
1212 for (int cAttempt = 1; rc != SSH_OK && cAttempt <= 5; cAttempt++)
1213 {
1214 ssh_disconnect(pThis->pSshSession);
1215 /* One more time, just to be sure. */
1216 LogRel(("%s: failed to connect to %s, retrying(#%d)...\n", pThis->pszInstance,
1217 fPrimary ? pThis->pszPrimaryIP : pThis->pszSecondaryIP, cAttempt));
1218 RTThreadSleep(10000); /* Sleep 10 seconds, then retry */
1219 rc = ssh_connect(pThis->pSshSession);
1220 }
1221 if (rc != SSH_OK)
1222 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1223 N_("CloudTunnel: Failed to connect to %s interface"), fPrimary ? "primary" : "secondary");
1224
1225 rc = ssh_userauth_publickey(pThis->pSshSession, NULL, pThis->SshKey);
1226 if (rc != SSH_AUTH_SUCCESS)
1227 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1228 N_("Failed to authenticate with public key"));
1229
1230 return VINF_SUCCESS;
1231}
1232
1233static int drvCloudTunnelSwitchToSecondary(PDRVCLOUDTUNNEL pThis)
1234{
1235 int rc = drvCloudTunnelNewSession(pThis, true /* fPrimary */);
1236 /*
1237 * Establish temporary console channel and configure the cloud instance
1238 * to bridge the tunnel channel to instance's primary interface.
1239 */
1240 if (RT_SUCCESS(rc))
1241 rc = drvCloudTunnelCloudInstanceInitialConfig(pThis);
1242
1243 ssh_disconnect(pThis->pSshSession);
1244 ssh_free(pThis->pSshSession);
1245 pThis->pSshSession = NULL;
1246
1247 return rc;
1248}
1249
1250
1251static int establishTunnel(PDRVCLOUDTUNNEL pThis)
1252{
1253 int rc = drvCloudTunnelNewSession(pThis, false /* fPrimary */);
1254 if (RT_SUCCESS(rc))
1255 rc = drvCloudTunnelCloudInstanceFinalConfig(pThis);
1256 if (RT_SUCCESS(rc))
1257 rc = drvCloudTunnelOpenTunnelChannel(pThis);
1258 if (RT_SUCCESS(rc))
1259 rc = drvCloudTunnelStartIoThread(pThis);
1260 if (RT_FAILURE(rc))
1261 {
1262 destroyTunnel(pThis);
1263 return rc;
1264 }
1265
1266 return rc;
1267}
1268
1269
1270static DECL_NOTHROW(void) drvCloudTunnelSshLogCallback(int priority, const char *function, const char *buffer, void *userdata)
1271{
1272 PDRVCLOUDTUNNEL pThis = (PDRVCLOUDTUNNEL)userdata;
1273#ifdef LOG_ENABLED
1274 const char *pcszVerbosity;
1275 switch (priority)
1276 {
1277 case SSH_LOG_WARNING:
1278 pcszVerbosity = "WARNING";
1279 break;
1280 case SSH_LOG_PROTOCOL:
1281 pcszVerbosity = "PROTOCOL";
1282 break;
1283 case SSH_LOG_PACKET:
1284 pcszVerbosity = "PACKET";
1285 break;
1286 case SSH_LOG_FUNCTIONS:
1287 pcszVerbosity = "FUNCTIONS";
1288 break;
1289 default:
1290 pcszVerbosity = "UNKNOWN";
1291 break;
1292 }
1293 Log3(("%s: SSH-%s: %s: %s\n", pThis->pszInstance, pcszVerbosity, function, buffer));
1294#else
1295 RT_NOREF(priority);
1296 LogRel(("%s: SSH %s: %s\n", pThis->pszInstance, function, buffer));
1297#endif
1298}
1299
1300/* -=-=-=-=- PDMDRVREG -=-=-=-=- */
1301
1302DECLINLINE(void) drvCloudTunnelStrFree(char **ppszString)
1303{
1304 if (*ppszString)
1305 {
1306 RTStrFree(*ppszString);
1307 *ppszString = NULL;
1308 }
1309}
1310
1311DECLINLINE(void) drvCloudTunnelHeapFree(PPDMDRVINS pDrvIns, char **ppszString)
1312{
1313 if (*ppszString)
1314 {
1315 PDMDrvHlpMMHeapFree(pDrvIns, *ppszString);
1316 *ppszString = NULL;
1317 }
1318}
1319
1320/**
1321 * Destruct a driver instance.
1322 *
1323 * Most VM resources are freed by the VM. This callback is provided so that any non-VM
1324 * resources can be freed correctly.
1325 *
1326 * @param pDrvIns The driver instance data.
1327 */
1328static DECLCALLBACK(void) drvCloudTunnelDestruct(PPDMDRVINS pDrvIns)
1329{
1330 LogFlowFunc(("\n"));
1331 PDRVCLOUDTUNNEL pThis = PDMINS_2_DATA(pDrvIns, PDRVCLOUDTUNNEL);
1332 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
1333
1334 ASMAtomicXchgSize(&pThis->fLinkDown, true);
1335
1336 destroyTunnel(pThis);
1337
1338 if (pThis->hIoReqQueue != NIL_RTREQQUEUE)
1339 {
1340 RTReqQueueDestroy(pThis->hIoReqQueue);
1341 pThis->hIoReqQueue = NIL_RTREQQUEUE;
1342 }
1343
1344 drvCloudTunnelStrFree(&pThis->pszCloudPrimaryInterface);
1345
1346 drvCloudTunnelHeapFree(pDrvIns, &pThis->pszPrimaryProxyType);
1347 drvCloudTunnelStrFree(&pThis->pszPrimaryProxyHost);
1348 drvCloudTunnelHeapFree(pDrvIns, &pThis->pszPrimaryProxyUser);
1349 drvCloudTunnelStrFree(&pThis->pszPrimaryProxyPassword);
1350
1351 drvCloudTunnelHeapFree(pDrvIns, &pThis->pszSecondaryProxyType);
1352 drvCloudTunnelStrFree(&pThis->pszSecondaryProxyHost);
1353 drvCloudTunnelHeapFree(pDrvIns, &pThis->pszSecondaryProxyUser);
1354 drvCloudTunnelStrFree(&pThis->pszSecondaryProxyPassword);
1355
1356 drvCloudTunnelStrFree(&pThis->pszSecondaryIP);
1357 drvCloudTunnelStrFree(&pThis->pszPrimaryIP);
1358 drvCloudTunnelStrFree(&pThis->pszUser);
1359
1360 drvCloudTunnelStrFree(&pThis->pszInstanceDev);
1361 drvCloudTunnelStrFree(&pThis->pszInstanceIo);
1362 drvCloudTunnelStrFree(&pThis->pszInstance);
1363
1364 drvCloudTunnelStrFree(&pThis->pszOutputBuffer);
1365 drvCloudTunnelStrFree(&pThis->pszCommandBuffer);
1366
1367 ssh_key_free(pThis->SshKey);
1368
1369 ssh_finalize();
1370 //OPENSSL_cleanup();
1371
1372 // if (pThis->pServer)
1373 // {
1374 // RTUdpServerDestroy(pThis->pServer);
1375 // pThis->pServer = NULL;
1376 // }
1377
1378 /*
1379 * Kill the xmit lock.
1380 */
1381 if (RTCritSectIsInitialized(&pThis->XmitLock))
1382 RTCritSectDelete(&pThis->XmitLock);
1383
1384#ifdef VBOX_WITH_STATISTICS
1385 /*
1386 * Deregister statistics.
1387 */
1388 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatPktSent);
1389 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatPktSentBytes);
1390 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatPktRecv);
1391 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatPktRecvBytes);
1392 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatTransmit);
1393 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatReceive);
1394 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatDevRecv);
1395 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatDevRecvWait);
1396#endif /* VBOX_WITH_STATISTICS */
1397}
1398
1399
1400/**
1401 * Construct a Cloud tunnel network transport driver instance.
1402 *
1403 * @copydoc FNPDMDRVCONSTRUCT
1404 */
1405static DECLCALLBACK(int) drvCloudTunnelConstruct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t fFlags)
1406{
1407 RT_NOREF(fFlags);
1408 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
1409 PDRVCLOUDTUNNEL pThis = PDMINS_2_DATA(pDrvIns, PDRVCLOUDTUNNEL);
1410 PCPDMDRVHLPR3 pHlp = pDrvIns->pHlpR3;
1411
1412 /*
1413 * Init the static parts.
1414 */
1415 pThis->pDrvIns = pDrvIns;
1416 pThis->pszCommandBuffer = NULL;
1417 pThis->pszOutputBuffer = NULL;
1418 pThis->pszInstance = NULL;
1419 pThis->pszPrimaryIP = NULL;
1420 pThis->pszSecondaryIP = NULL;
1421 pThis->pszUser = NULL;
1422 pThis->SshKey = 0;
1423
1424 /* IBase */
1425 pDrvIns->IBase.pfnQueryInterface = drvCloudTunnelQueryInterface;
1426 /* INetwork */
1427 pThis->INetworkUp.pfnBeginXmit = drvCloudTunnelUp_BeginXmit;
1428 pThis->INetworkUp.pfnAllocBuf = drvCloudTunnelUp_AllocBuf;
1429 pThis->INetworkUp.pfnFreeBuf = drvCloudTunnelUp_FreeBuf;
1430 pThis->INetworkUp.pfnSendBuf = drvCloudTunnelUp_SendBuf;
1431 pThis->INetworkUp.pfnEndXmit = drvCloudTunnelUp_EndXmit;
1432 pThis->INetworkUp.pfnSetPromiscuousMode = drvCloudTunnelUp_SetPromiscuousMode;
1433 pThis->INetworkUp.pfnNotifyLinkChanged = drvCloudTunnelUp_NotifyLinkChanged;
1434
1435 /* ??? */
1436 pThis->iSocketIn = INVALID_SOCKET;
1437 pThis->iSocketOut = INVALID_SOCKET;
1438 pThis->pSshSession = 0;
1439 pThis->pSshChannel = 0;
1440
1441 pThis->pDevThread = 0;
1442 pThis->pIoThread = 0;
1443 pThis->hIoReqQueue = NIL_RTREQQUEUE;
1444
1445 pThis->fLinkDown = false;
1446
1447 pThis->pszCloudPrimaryInterface = NULL;
1448
1449#ifdef VBOX_WITH_STATISTICS
1450 /*
1451 * Statistics.
1452 */
1453 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatPktSent, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of sent packets.", "/Drivers/CloudTunnel%d/Packets/Sent", pDrvIns->iInstance);
1454 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatPktSentBytes, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_BYTES, "Number of sent bytes.", "/Drivers/CloudTunnel%d/Bytes/Sent", pDrvIns->iInstance);
1455 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatPktRecv, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of received packets.", "/Drivers/CloudTunnel%d/Packets/Received", pDrvIns->iInstance);
1456 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatPktRecvBytes, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_BYTES, "Number of received bytes.", "/Drivers/CloudTunnel%d/Bytes/Received", pDrvIns->iInstance);
1457 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatTransmit, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS, STAMUNIT_TICKS_PER_CALL, "Profiling packet transmit runs.", "/Drivers/CloudTunnel%d/Transmit", pDrvIns->iInstance);
1458 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatReceive, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS, STAMUNIT_TICKS_PER_CALL, "Profiling packet receive runs.", "/Drivers/CloudTunnel%d/Receive", pDrvIns->iInstance);
1459 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatDevRecv, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS, STAMUNIT_TICKS_PER_CALL, "Profiling device receive runs.", "/Drivers/CloudTunnel%d/DeviceReceive", pDrvIns->iInstance);
1460 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatDevRecvWait, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS, STAMUNIT_TICKS_PER_CALL, "Profiling device receive waits.", "/Drivers/CloudTunnel%d/DeviceReceiveWait", pDrvIns->iInstance);
1461#endif /* VBOX_WITH_STATISTICS */
1462
1463 /*
1464 * Validate the config.
1465 */
1466 PDMDRV_VALIDATE_CONFIG_RETURN(pDrvIns, "SshKey"
1467 "|PrimaryIP"
1468 "|SecondaryIP"
1469 "|TargetMAC"
1470
1471 "|PrimaryProxyType"
1472 "|PrimaryProxyHost"
1473 "|PrimaryProxyPort"
1474 "|PrimaryProxyUser"
1475 "|PrimaryProxyPassword"
1476 "|SecondaryProxyType"
1477 "|SecondaryProxyHost"
1478 "|SecondaryProxyPort"
1479 "|SecondaryProxyUser"
1480 "|SecondaryProxyPassword"
1481
1482 ,"");
1483
1484 /*
1485 * Check that no-one is attached to us.
1486 */
1487 AssertMsgReturn(PDMDrvHlpNoAttach(pDrvIns) == VERR_PDM_NO_ATTACHED_DRIVER,
1488 ("Configuration error: Not possible to attach anything to this driver!\n"),
1489 VERR_PDM_DRVINS_NO_ATTACH);
1490
1491 /*
1492 * Query the network port interface.
1493 */
1494 pThis->pIAboveNet = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMINETWORKDOWN);
1495 if (!pThis->pIAboveNet)
1496 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_MISSING_INTERFACE_ABOVE,
1497 N_("Configuration error: The above device/driver didn't export the network port interface"));
1498
1499 /*
1500 * Read the configuration.
1501 */
1502 int rc;
1503
1504 char szVal[2048];
1505 RTNETADDRIPV4 tmpAddr;
1506 rc = pHlp->pfnCFGMQueryString(pCfg, "PrimaryIP", szVal, sizeof(szVal));
1507 if (RT_FAILURE(rc))
1508 return PDMDRV_SET_ERROR(pDrvIns, rc,
1509 N_("DrvCloudTunnel: Configuration error: Querying \"PrimaryIP\" as string failed"));
1510 rc = RTNetStrToIPv4Addr(szVal, &tmpAddr);
1511 if (RT_FAILURE(rc))
1512 return PDMDRV_SET_ERROR(pDrvIns, rc,
1513 N_("DrvCloudTunnel: Configuration error: \"PrimaryIP\" is not valid"));
1514 else
1515 pThis->pszPrimaryIP = RTStrDup(szVal);
1516
1517 rc = pHlp->pfnCFGMQueryString(pCfg, "SecondaryIP", szVal, sizeof(szVal));
1518 if (RT_FAILURE(rc))
1519 return PDMDRV_SET_ERROR(pDrvIns, rc,
1520 N_("DrvCloudTunnel: Configuration error: Querying \"SecondaryIP\" as string failed"));
1521 rc = RTNetStrToIPv4Addr(szVal, &tmpAddr);
1522 if (RT_FAILURE(rc))
1523 return PDMDRV_SET_ERROR(pDrvIns, rc,
1524 N_("DrvCloudTunnel: Configuration error: \"SecondaryIP\" is not valid"));
1525 else
1526 pThis->pszSecondaryIP = RTStrDup(szVal);
1527 rc = pHlp->pfnCFGMQueryBytes(pCfg, "TargetMAC", pThis->targetMac.au8, sizeof(pThis->targetMac.au8));
1528 if (RT_FAILURE(rc))
1529 return PDMDRV_SET_ERROR(pDrvIns, rc,
1530 N_("DrvCloudTunnel: Configuration error: Failed to get target MAC address"));
1531 /** @todo In the near future we will want to include proxy settings here! */
1532 // Do we want to pass the user name via CFGM?
1533 pThis->pszUser = RTStrDup("opc");
1534 // Is it safe to expose verbosity via CFGM?
1535#ifdef LOG_ENABLED
1536 pThis->iSshVerbosity = SSH_LOG_PACKET; //SSH_LOG_FUNCTIONS;
1537#else
1538 pThis->iSshVerbosity = SSH_LOG_WARNING;
1539#endif
1540
1541 pThis->ulTimeoutInSecounds = 30; /* The default 10-second timeout is too short? */
1542
1543 rc = pHlp->pfnCFGMQueryPassword(pCfg, "SshKey", szVal, sizeof(szVal));
1544 if (RT_FAILURE(rc))
1545 return PDMDRV_SET_ERROR(pDrvIns, rc,
1546 N_("DrvCloudTunnel: Configuration error: Querying \"SshKey\" as password failed"));
1547 rc = ssh_pki_import_privkey_base64(szVal, NULL, NULL, NULL, &pThis->SshKey);
1548 RTMemWipeThoroughly(szVal, sizeof(szVal), 10);
1549 if (rc != SSH_OK)
1550 return PDMDRV_SET_ERROR(pDrvIns, VERR_INVALID_BASE64_ENCODING,
1551 N_("DrvCloudTunnel: Configuration error: Converting \"SshKey\" from base64 failed"));
1552
1553 /* PrimaryProxyType is optional */
1554 rc = pHlp->pfnCFGMQueryStringAllocDef(pCfg, "PrimaryProxyType", &pThis->pszPrimaryProxyType, NULL);
1555 if (RT_FAILURE(rc))
1556 return PDMDRV_SET_ERROR(pDrvIns, rc,
1557 N_("DrvCloudTunnel: Configuration error: Querying \"PrimaryProxyType\" as string failed"));
1558 if (pThis->pszPrimaryProxyType)
1559 {
1560 rc = pHlp->pfnCFGMQueryString(pCfg, "PrimaryProxyHost", szVal, sizeof(szVal));
1561 if (RT_FAILURE(rc))
1562 return PDMDRV_SET_ERROR(pDrvIns, rc,
1563 N_("DrvCloudTunnel: Configuration error: Querying \"PrimaryProxyHost\" as string failed"));
1564 rc = RTNetStrToIPv4Addr(szVal, &tmpAddr);
1565 if (RT_FAILURE(rc))
1566 return PDMDRV_SET_ERROR(pDrvIns, rc,
1567 N_("DrvCloudTunnel: Configuration error: \"PrimaryProxyHost\" is not valid"));
1568 else
1569 pThis->pszPrimaryProxyHost = RTStrDup(szVal);
1570
1571 uint64_t u64Val;
1572 rc = pHlp->pfnCFGMQueryInteger(pCfg, "PrimaryProxyPort", &u64Val);
1573 if (RT_FAILURE(rc))
1574 return PDMDRV_SET_ERROR(pDrvIns, rc,
1575 N_("DrvCloudTunnel: Configuration error: Querying \"PrimaryProxyPort\" as integer failed"));
1576 if (u64Val > 0xFFFF)
1577 return PDMDRV_SET_ERROR(pDrvIns, rc,
1578 N_("DrvCloudTunnel: Configuration error: \"PrimaryProxyPort\" is not valid"));
1579 pThis->u16PrimaryProxyPort = (uint16_t)u64Val;
1580
1581 /* PrimaryProxyUser is optional */
1582 rc = pHlp->pfnCFGMQueryStringAllocDef(pCfg, "PrimaryProxyUser", &pThis->pszPrimaryProxyUser, NULL);
1583 if (RT_FAILURE(rc))
1584 return PDMDRV_SET_ERROR(pDrvIns, rc,
1585 N_("DrvCloudTunnel: Configuration error: Querying \"PrimaryProxyUser\" as string failed"));
1586 /* PrimaryProxyPassword must be present if PrimaryProxyUser is present */
1587 if (pThis->pszPrimaryProxyUser)
1588 {
1589 rc = pHlp->pfnCFGMQueryPassword(pCfg, "PrimaryProxyPassword", szVal, sizeof(szVal));
1590 if (RT_FAILURE(rc))
1591 return PDMDRV_SET_ERROR(pDrvIns, rc,
1592 N_("DrvCloudTunnel: Configuration error: Querying \"PrimaryProxyPassword\" as string failed"));
1593 pThis->pszPrimaryProxyPassword = RTStrDup(szVal);
1594 }
1595 }
1596
1597 /* SecondaryProxyType is optional */
1598 rc = pHlp->pfnCFGMQueryStringAllocDef(pCfg, "SecondaryProxyType", &pThis->pszSecondaryProxyType, NULL);
1599 if (RT_FAILURE(rc))
1600 return PDMDRV_SET_ERROR(pDrvIns, rc,
1601 N_("DrvCloudTunnel: Configuration error: Querying \"SecondaryProxyType\" as string failed"));
1602 if (pThis->pszSecondaryProxyType)
1603 {
1604 if (RT_FAILURE(rc))
1605 return PDMDRV_SET_ERROR(pDrvIns, rc,
1606 N_("DrvCloudTunnel: Configuration error: Querying \"SecondaryProxyType\" as string failed"));
1607
1608 rc = pHlp->pfnCFGMQueryString(pCfg, "SecondaryProxyHost", szVal, sizeof(szVal));
1609 if (RT_FAILURE(rc))
1610 return PDMDRV_SET_ERROR(pDrvIns, rc,
1611 N_("DrvCloudTunnel: Configuration error: Querying \"SecondaryProxyHost\" as string failed"));
1612 rc = RTNetStrToIPv4Addr(szVal, &tmpAddr);
1613 if (RT_FAILURE(rc))
1614 return PDMDRV_SET_ERROR(pDrvIns, rc,
1615 N_("DrvCloudTunnel: Configuration error: \"SecondaryProxyHost\" is not valid"));
1616 else
1617 pThis->pszSecondaryProxyHost = RTStrDup(szVal);
1618
1619 uint64_t u64Val;
1620 rc = pHlp->pfnCFGMQueryInteger(pCfg, "SecondaryProxyPort", &u64Val);
1621 if (RT_FAILURE(rc))
1622 return PDMDRV_SET_ERROR(pDrvIns, rc,
1623 N_("DrvCloudTunnel: Configuration error: Querying \"SecondaryProxyPort\" as integer failed"));
1624 if (u64Val > 0xFFFF)
1625 return PDMDRV_SET_ERROR(pDrvIns, rc,
1626 N_("DrvCloudTunnel: Configuration error: \"SecondaryProxyPort\" is not valid"));
1627 pThis->u16SecondaryProxyPort = (uint16_t)u64Val;
1628
1629 /* SecondaryProxyUser is optional */
1630 rc = pHlp->pfnCFGMQueryStringAllocDef(pCfg, "SecondaryProxyUser", &pThis->pszSecondaryProxyUser, NULL);
1631 if (RT_FAILURE(rc))
1632 return PDMDRV_SET_ERROR(pDrvIns, rc,
1633 N_("DrvCloudTunnel: Configuration error: Querying \"SecondaryProxyUser\" as string failed"));
1634 /* SecondaryProxyPassword must be present if SecondaryProxyUser is present */
1635 if (pThis->pszSecondaryProxyUser)
1636 {
1637 rc = pHlp->pfnCFGMQueryPassword(pCfg, "SecondaryProxyPassword", szVal, sizeof(szVal));
1638 if (RT_FAILURE(rc))
1639 return PDMDRV_SET_ERROR(pDrvIns, rc,
1640 N_("DrvCloudTunnel: Configuration error: Querying \"SecondaryProxyPassword\" as string failed"));
1641 pThis->pszSecondaryProxyPassword = RTStrDup(szVal);
1642 }
1643 }
1644
1645 pThis->pszCommandBuffer = (char *)RTMemAlloc(DRVCLOUDTUNNEL_COMMAND_BUFFER_SIZE);
1646 if (pThis->pszCommandBuffer == NULL)
1647 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_HIF_OPEN_FAILED,
1648 N_("DrvCloudTunnel: Failed to allocate command buffer"));
1649 pThis->pszOutputBuffer = (char *)RTMemAlloc(DRVCLOUDTUNNEL_OUTPUT_BUFFER_SIZE);
1650 if (pThis->pszOutputBuffer == NULL)
1651 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_HIF_OPEN_FAILED,
1652 N_("DrvCloudTunnel: Failed to allocate output buffer"));
1653 /*
1654 * Create unique instance name for logging.
1655 */
1656 rc = RTStrAPrintf(&pThis->pszInstance, "CT#%d", pDrvIns->iInstance);
1657 AssertRC(rc);
1658
1659 LogRel(("%s: primary=%s secondary=%s target-mac=%RTmac\n", pThis->pszInstance, pThis->pszPrimaryIP, pThis->pszSecondaryIP, pThis->targetMac.au8));
1660
1661 /*
1662 * Create unique thread name for cloud I/O.
1663 */
1664 rc = RTStrAPrintf(&pThis->pszInstanceIo, "CTunIO%d", pDrvIns->iInstance);
1665 AssertRC(rc);
1666
1667 /*
1668 * Create unique thread name for device receive function.
1669 */
1670 rc = RTStrAPrintf(&pThis->pszInstanceDev, "CTunDev%d", pDrvIns->iInstance);
1671 AssertRC(rc);
1672
1673 /*
1674 * Create the transmit lock.
1675 */
1676 rc = RTCritSectInit(&pThis->XmitLock);
1677 AssertRCReturn(rc, rc);
1678
1679 /*
1680 * Create the request queue for I/O requests.
1681 */
1682 rc = RTReqQueueCreate(&pThis->hIoReqQueue);
1683 AssertLogRelRCReturn(rc, rc);
1684
1685 /*
1686 * Create the request queue for attached device requests.
1687 */
1688 rc = RTReqQueueCreate(&pThis->hDevReqQueue);
1689 AssertLogRelRCReturn(rc, rc);
1690
1691 /*
1692 * Start the device output thread.
1693 */
1694 rc = PDMDrvHlpThreadCreate(pThis->pDrvIns, &pThis->pDevThread,
1695 pThis, drvCloudTunnelDevThread, drvCloudTunnelDevWakeup,
1696 64 * _1K, RTTHREADTYPE_IO, pThis->pszInstanceDev);
1697 if (RT_FAILURE(rc))
1698 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1699 N_("CloudTunnel: Failed to start device thread"));
1700
1701 rc = ssh_init();
1702 if (rc != SSH_OK)
1703 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1704 N_("CloudTunnel: Failed to initialize libssh"));
1705
1706 memset(&pThis->Callbacks, 0, sizeof(pThis->Callbacks));
1707#ifdef PACKET_CAPTURE_ENABLED
1708 pThis->Callbacks.channel_data_function = drvCloudTunnelReceiveCallbackWithPacketCapture;
1709#else
1710 pThis->Callbacks.channel_data_function = drvCloudTunnelReceiveCallback;
1711#endif
1712 pThis->Callbacks.userdata = pThis;
1713 pThis->Callbacks.channel_write_wontblock_function = channelWriteWontblockCallback;
1714 ssh_callbacks_init(&pThis->Callbacks);
1715
1716 rc = ssh_set_log_callback(drvCloudTunnelSshLogCallback);
1717 if (rc != SSH_OK)
1718 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1719 N_("CloudTunnel: Failed to set libssh log callback"));
1720 rc = ssh_set_log_userdata(pThis);
1721 if (rc != SSH_OK)
1722 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1723 N_("CloudTunnel: Failed to set libssh log userdata"));
1724
1725 rc = drvCloudTunnelSwitchToSecondary(pThis);
1726 if (RT_SUCCESS(rc))
1727 rc = establishTunnel(pThis);
1728
1729 return rc;
1730}
1731
1732
1733#if 0
1734/**
1735 * Suspend notification.
1736 *
1737 * @param pDrvIns The driver instance.
1738 */
1739static DECLCALLBACK(void) drvCloudTunnelSuspend(PPDMDRVINS pDrvIns)
1740{
1741 LogFlowFunc(("\n"));
1742 PDRVCLOUDTUNNEL pThis = PDMINS_2_DATA(pDrvIns, PDRVCLOUDTUNNEL);
1743
1744 RT_NOREF(pThis);
1745 // if (pThis->pServer)
1746 // {
1747 // RTUdpServerDestroy(pThis->pServer);
1748 // pThis->pServer = NULL;
1749 // }
1750}
1751
1752
1753/**
1754 * Resume notification.
1755 *
1756 * @param pDrvIns The driver instance.
1757 */
1758static DECLCALLBACK(void) drvCloudTunnelResume(PPDMDRVINS pDrvIns)
1759{
1760 LogFlowFunc(("\n"));
1761 PDRVCLOUDTUNNEL pThis = PDMINS_2_DATA(pDrvIns, PDRVCLOUDTUNNEL);
1762
1763 int rc = RTUdpServerCreate("", pThis->uSrcPort, RTTHREADTYPE_IO, pThis->pszInstance,
1764 drvCloudTunnelReceive, pDrvIns, &pThis->pServer);
1765 if (RT_FAILURE(rc))
1766 PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1767 N_("CloudTunnel: Failed to start the Cloud tunnel server"));
1768
1769}
1770#endif
1771
1772/**
1773 * Cloud tunnel network transport driver registration record.
1774 */
1775const PDMDRVREG g_DrvCloudTunnel =
1776{
1777 /* u32Version */
1778 PDM_DRVREG_VERSION,
1779 /* szName */
1780 "CloudTunnel",
1781 /* szRCMod */
1782 "",
1783 /* szR0Mod */
1784 "",
1785 /* pszDescription */
1786 "Cloud Tunnel Network Transport Driver",
1787 /* fFlags */
1788 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
1789 /* fClass. */
1790 PDM_DRVREG_CLASS_NETWORK,
1791 /* cMaxInstances */
1792 ~0U,
1793 /* cbInstance */
1794 sizeof(DRVCLOUDTUNNEL),
1795 /* pfnConstruct */
1796 drvCloudTunnelConstruct,
1797 /* pfnDestruct */
1798 drvCloudTunnelDestruct,
1799 /* pfnRelocate */
1800 NULL,
1801 /* pfnIOCtl */
1802 NULL,
1803 /* pfnPowerOn */
1804 NULL,
1805 /* pfnReset */
1806 NULL,
1807 /* pfnSuspend */
1808 NULL, // drvCloudTunnelSuspend,
1809 /* pfnResume */
1810 NULL, // drvCloudTunnelResume,
1811 /* pfnAttach */
1812 NULL,
1813 /* pfnDetach */
1814 NULL,
1815 /* pfnPowerOff */
1816 NULL,
1817 /* pfnSoftReset */
1818 NULL,
1819 /* u32EndVersion */
1820 PDM_DRVREG_VERSION
1821};
1822
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