VirtualBox

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

Last change on this file since 101696 was 101638, checked in by vboxsync, 15 months ago

libssh: fixing build. bugref:10539

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 69.6 KB
Line 
1/* $Id: DrvCloudTunnel.cpp 101638 2023-10-27 17:37:59Z 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*/,
422 RTREQFLAGS_VOID | RTREQFLAGS_NO_WAIT,
423 (PFNRT)drvCloudTunnelSendWorker, 2, pThis, pSgBuf);
424
425 if (RT_SUCCESS(rc))
426 {
427 drvCloudTunnelNotifyIoThread(pThis, "drvCloudTunnelUp_SendBuf");
428 return VINF_SUCCESS;
429 }
430
431 rc = VERR_NET_NO_BUFFER_SPACE;
432 }
433 else
434 rc = VERR_NET_DOWN;
435 drvCloudTunnelFreeSgBuf(pThis, pSgBuf);
436 return rc;
437}
438
439
440/**
441 * @interface_method_impl{PDMINETWORKUP,pfnEndXmit}
442 */
443static DECLCALLBACK(void) drvCloudTunnelUp_EndXmit(PPDMINETWORKUP pInterface)
444{
445 PDRVCLOUDTUNNEL pThis = PDMINETWORKUP_2_DRVCLOUDTUNNEL(pInterface);
446 RTCritSectLeave(&pThis->XmitLock);
447}
448
449
450/**
451 * @interface_method_impl{PDMINETWORKUP,pfnSetPromiscuousMode}
452 */
453static DECLCALLBACK(void) drvCloudTunnelUp_SetPromiscuousMode(PPDMINETWORKUP pInterface, bool fPromiscuous)
454{
455 RT_NOREF(pInterface, fPromiscuous);
456 LogFlowFunc(("fPromiscuous=%d\n", fPromiscuous));
457 /* nothing to do */
458}
459
460
461/**
462 * Notification on link status changes.
463 *
464 * @param pInterface Pointer to the interface structure containing the called function pointer.
465 * @param enmLinkState The new link state.
466 * @thread EMT
467 */
468static DECLCALLBACK(void) drvCloudTunnelUp_NotifyLinkChanged(PPDMINETWORKUP pInterface, PDMNETWORKLINKSTATE enmLinkState)
469{
470 LogFlowFunc(("enmLinkState=%d\n", enmLinkState));
471 PDRVCLOUDTUNNEL pThis = PDMINETWORKUP_2_DRVCLOUDTUNNEL(pInterface);
472
473 bool fLinkDown;
474 switch (enmLinkState)
475 {
476 case PDMNETWORKLINKSTATE_DOWN:
477 case PDMNETWORKLINKSTATE_DOWN_RESUME:
478 fLinkDown = true;
479 break;
480 default:
481 AssertMsgFailed(("enmLinkState=%d\n", enmLinkState));
482 RT_FALL_THRU();
483 case PDMNETWORKLINKSTATE_UP:
484 fLinkDown = false;
485 break;
486 }
487 ASMAtomicXchgSize(&pThis->fLinkDown, fLinkDown);
488}
489
490
491
492/* -=-=-=-=- PDMIBASE -=-=-=-=- */
493
494/**
495 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
496 */
497static DECLCALLBACK(void *) drvCloudTunnelQueryInterface(PPDMIBASE pInterface, const char *pszIID)
498{
499 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
500 PDRVCLOUDTUNNEL pThis = PDMINS_2_DATA(pDrvIns, PDRVCLOUDTUNNEL);
501
502 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pDrvIns->IBase);
503 PDMIBASE_RETURN_INTERFACE(pszIID, PDMINETWORKUP, &pThis->INetworkUp);
504 return NULL;
505}
506
507
508/**
509 * I/O thread handling the libssh I/O.
510 *
511 * The libssh implementation is single-threaded so we perform I/O in a
512 * dedicated thread. We take care that this thread does not become the
513 * bottleneck: If the guest wants to send, a request is enqueued into the
514 * hIoReqQueue and is handled asynchronously by this thread. TODO:If this thread
515 * wants to deliver packets to the guest, it enqueues a request into
516 * hRecvReqQueue which is later handled by the Recv thread.
517 */
518static DECLCALLBACK(int) drvCloudTunnelIoThread(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
519{
520 PDRVCLOUDTUNNEL pThis = PDMINS_2_DATA(pDrvIns, PDRVCLOUDTUNNEL);
521 // int nFDs = -1;
522
523 LogFlow(("%s: started I/O thread %p\n", pThis->pszInstance, pThread));
524
525 if (pThread->enmState == PDMTHREADSTATE_INITIALIZING)
526 return VINF_SUCCESS;
527
528 // if (pThis->enmLinkStateWant != pThis->enmLinkState)
529 // drvNATNotifyLinkChangedWorker(pThis, pThis->enmLinkStateWant);
530
531 /*
532 * Polling loop.
533 */
534 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
535 {
536 /*
537 * To prevent concurrent execution of sending/receiving threads
538 */
539//#ifndef RT_OS_WINDOWS
540 // /* process _all_ outstanding requests but don't wait */
541 // RTReqQueueProcess(pThis->hIoReqQueue, 0);
542 // RTMemFree(polls);
543//#else /* RT_OS_WINDOWS */
544
545 struct timeval timeout;
546 ssh_channel in_channels[2], out_channels[2];
547 fd_set fds;
548 int maxfd;
549
550 timeout.tv_sec = 30;
551 timeout.tv_usec = 0;
552 in_channels[0] = pThis->pSshChannel;
553 in_channels[1] = NULL;
554 FD_ZERO(&fds);
555 FD_SET(pThis->iSocketIn, &fds);
556 maxfd = pThis->iSocketIn + 1;
557
558 ssh_select(in_channels, out_channels, maxfd, &fds, &timeout);
559
560 /* Poll will call the receive callback on each packet coming from the tunnel. */
561 if (out_channels[0] != NULL)
562 ssh_channel_poll(pThis->pSshChannel, false);
563
564 /* Did we get notified by drvCloudTunnelNotifyIoThread() via connected sockets? */
565 if (FD_ISSET(pThis->iSocketIn, &fds))
566 {
567 char buf[2];
568 recv(pThis->iSocketIn, buf, 1, 0);
569 /* process all outstanding requests but don't wait */
570 RTReqQueueProcess(pThis->hIoReqQueue, 0);
571 }
572//#endif /* RT_OS_WINDOWS */
573 }
574
575 LogFlow(("%s: I/O thread %p terminated\n", pThis->pszInstance, pThread));
576
577 return VINF_SUCCESS;
578}
579
580
581/**
582 * Unblock the I/O thread so it can respond to a state change.
583 *
584 * @returns VBox status code.
585 * @param pDevIns The pcnet device instance.
586 * @param pThread The send thread.
587 */
588static DECLCALLBACK(int) drvCloudTunnelIoWakeup(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
589{
590 RT_NOREF(pThread);
591 PDRVCLOUDTUNNEL pThis = PDMINS_2_DATA(pDrvIns, PDRVCLOUDTUNNEL);
592
593 LogFlow(("%s: waking up I/O thread %p...\n", pThis->pszInstance, pThread));
594
595 drvCloudTunnelNotifyIoThread(pThis, "drvCloudTunnelIoWakeup");
596 return VINF_SUCCESS;
597}
598
599
600/*
601 * Remove the following cut&paste code after a while, when
602 * we are positive that no frames get coalesced!
603 */
604#define VBOX_CTUN_COALESCED_FRAME_DETECTION
605#ifdef VBOX_CTUN_COALESCED_FRAME_DETECTION
606struct ssh_buffer_struct {
607 bool secure;
608 size_t used;
609 size_t allocated;
610 size_t pos;
611 uint8_t *data;
612};
613
614/** @internal
615 * Describes the different possible states in a
616 * outgoing (client) channel request
617 */
618enum ssh_channel_request_state_e {
619 /** No request has been made */
620 SSH_CHANNEL_REQ_STATE_NONE = 0,
621 /** A request has been made and answer is pending */
622 SSH_CHANNEL_REQ_STATE_PENDING,
623 /** A request has been replied and accepted */
624 SSH_CHANNEL_REQ_STATE_ACCEPTED,
625 /** A request has been replied and refused */
626 SSH_CHANNEL_REQ_STATE_DENIED,
627 /** A request has been replied and an error happend */
628 SSH_CHANNEL_REQ_STATE_ERROR
629};
630
631enum ssh_channel_state_e {
632 SSH_CHANNEL_STATE_NOT_OPEN = 0,
633 SSH_CHANNEL_STATE_OPENING,
634 SSH_CHANNEL_STATE_OPEN_DENIED,
635 SSH_CHANNEL_STATE_OPEN,
636 SSH_CHANNEL_STATE_CLOSED
637};
638
639/* The channel has been closed by the remote side */
640#define SSH_CHANNEL_FLAG_CLOSED_REMOTE 0x0001
641
642/* The channel has been closed locally */
643#define SSH_CHANNEL_FLAG_CLOSED_LOCAL 0x0002
644
645/* The channel has been freed by the calling program */
646#define SSH_CHANNEL_FLAG_FREED_LOCAL 0x0004
647
648/* the channel has not yet been bound to a remote one */
649#define SSH_CHANNEL_FLAG_NOT_BOUND 0x0008
650
651struct ssh_channel_struct {
652 ssh_session session; /* SSH_SESSION pointer */
653 uint32_t local_channel;
654 uint32_t local_window;
655 int local_eof;
656 uint32_t local_maxpacket;
657
658 uint32_t remote_channel;
659 uint32_t remote_window;
660 int remote_eof; /* end of file received */
661 uint32_t remote_maxpacket;
662 enum ssh_channel_state_e state;
663 int delayed_close;
664 int flags;
665 ssh_buffer stdout_buffer;
666 ssh_buffer stderr_buffer;
667 void *userarg;
668 int exit_status;
669 enum ssh_channel_request_state_e request_state;
670 struct ssh_list *callbacks; /* list of ssh_channel_callbacks */
671
672 /* counters */
673 ssh_counter counter;
674};
675#endif /* VBOX_CTUN_COALESCED_FRAME_DETECTION */
676
677/**
678 * Worker function for delivering receive packets to the attached device.
679 *
680 * @param pThis Pointer to the cloud tunnel instance.
681 * @param pbData Packet data.
682 * @param u32Len Packet length.
683 * @thread Dev
684 */
685static DECLCALLBACK(void) drvCloudTunnelReceiveWorker(PDRVCLOUDTUNNEL pThis, uint8_t *pbData, uint32_t u32Len)
686{
687 AssertPtrReturnVoid(pbData);
688 AssertReturnVoid(u32Len!=0);
689
690 STAM_PROFILE_START(&pThis->StatDevRecv, a);
691
692 Log2(("%s: waiting until device is ready to receive...\n", pThis->pszInstance));
693 STAM_PROFILE_START(&pThis->StatDevRecvWait, b);
694 int rc = pThis->pIAboveNet->pfnWaitReceiveAvail(pThis->pIAboveNet, RT_INDEFINITE_WAIT);
695 STAM_PROFILE_STOP(&pThis->StatDevRecvWait, b);
696
697 if (RT_SUCCESS(rc))
698 {
699 Log2(("%s: delivering %u-byte packet to attached device...\n", pThis->pszInstance, u32Len));
700 rc = pThis->pIAboveNet->pfnReceive(pThis->pIAboveNet, pbData, u32Len);
701 AssertRC(rc);
702 }
703
704 RTMemFree(pbData);
705 STAM_PROFILE_STOP(&pThis->StatDevRecv, a);
706 STAM_PROFILE_ADV_STOP(&pThis->StatReceive, a);
707}
708
709static int drvCloudTunnelReceiveCallback(ssh_session session, ssh_channel channel, void* data, uint32_t len, int is_stderr, void* userdata)
710{
711 RT_NOREF(session);
712 PDRVCLOUDTUNNEL pThis = (PDRVCLOUDTUNNEL)userdata;
713
714 Log2(("drvCloudTunnelReceiveCallback: len=%d is_stderr=%s\n", len, is_stderr ? "true" : "false"));
715 if (ASMAtomicReadBool(&pThis->fLinkDown))
716 {
717 Log2(("drvCloudTunnelReceiveCallback: ignoring packet as the link is down\n"));
718 return len;
719 }
720
721#ifdef VBOX_CTUN_COALESCED_FRAME_DETECTION
722 if (channel->stdout_buffer->data != data)
723 LogRel(("drvCloudTunnelReceiveCallback: coalesced frames!\n"));
724#endif /* VBOX_CTUN_COALESCED_FRAME_DETECTION */
725
726 if (is_stderr)
727 {
728 LogRel(("%s: [REMOTE] %.*s", pThis->pszInstance, len, data));
729 return 0;
730 }
731
732 STAM_PROFILE_ADV_START(&pThis->StatReceive, a);
733
734 if (pThis->iSshVerbosity >= SSH_LOG_PACKET)
735 Log2(("%.*Rhxd\n", len, data));
736
737 /** @todo Validate len! */
738 void *pvPacket = RTMemDup(data, len);
739 if (!pvPacket)
740 {
741 LogRel(("%s: failed to allocate %d bytes\n", pThis->pszInstance, len));
742 STAM_PROFILE_ADV_STOP(&pThis->StatReceive, a);
743 return len;
744 }
745 int rc = RTReqQueueCallEx(pThis->hDevReqQueue, NULL /*ppReq*/, 0 /*cMillies*/,
746 RTREQFLAGS_VOID | RTREQFLAGS_NO_WAIT,
747 (PFNRT)drvCloudTunnelReceiveWorker, 3, pThis, pvPacket, len);
748 if (RT_FAILURE(rc))
749 {
750 LogRel(("%s: failed to enqueue device request - %Rrc\n", pThis->pszInstance, rc));
751 STAM_PROFILE_ADV_STOP(&pThis->StatReceive, a);
752 }
753
754 return len;
755}
756
757// for libssh 0.9.6
758static int channelWriteWontblockCallback(ssh_session, ssh_channel, size_t, void *)
759//static int channelWriteWontblockCallback(ssh_session, ssh_channel, unsigned int, void *)
760{
761 return 0;
762}
763
764
765
766/**
767 * This thread feeds the attached device with the packets received from the tunnel.
768 *
769 * This thread is needed because we cannot block I/O thread waiting for the attached
770 * device to become ready to receive packets coming from the tunnel.
771 */
772static DECLCALLBACK(int) drvCloudTunnelDevThread(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
773{
774 PDRVCLOUDTUNNEL pThis = PDMINS_2_DATA(pDrvIns, PDRVCLOUDTUNNEL);
775
776 LogFlow(("%s: device thread %p started\n", pThis->pszInstance, pThread));
777
778 if (pThread->enmState == PDMTHREADSTATE_INITIALIZING)
779 return VINF_SUCCESS;
780
781 /*
782 * Request processing loop.
783 */
784 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
785 {
786 int rc = RTReqQueueProcess(pThis->hDevReqQueue, RT_INDEFINITE_WAIT);
787 Log2(("drvCloudTunnelDevThread: RTReqQueueProcess returned '%Rrc'\n", rc));
788 if (RT_FAILURE(rc))
789 LogRel(("%s: failed to process device request with '%Rrc'\n", pThis->pszInstance, rc));
790 }
791
792 LogFlow(("%s: device thread %p terminated\n", pThis->pszInstance, pThread));
793 return VINF_SUCCESS;
794}
795
796
797static DECLCALLBACK(int) drvCloudTunnelReceiveWakeup(PDRVCLOUDTUNNEL pThis)
798{
799 NOREF(pThis);
800 /* Returning a VINF_* will cause RTReqQueueProcess return. */
801 return VWRN_STATE_CHANGED;
802}
803
804/**
805 * Unblock the I/O thread so it can respond to a state change.
806 *
807 * @returns VBox status code.
808 * @param pDevIns The pcnet device instance.
809 * @param pThread The send thread.
810 */
811static DECLCALLBACK(int) drvCloudTunnelDevWakeup(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
812{
813 RT_NOREF(pThread);
814 PDRVCLOUDTUNNEL pThis = PDMINS_2_DATA(pDrvIns, PDRVCLOUDTUNNEL);
815 LogFlow(("%s: waking up device thread %p...\n", pThis->pszInstance, pThread));
816
817 /* Wake up device thread. */
818 PRTREQ pReq;
819 int rc = RTReqQueueCall(pThis->hDevReqQueue, &pReq, 10000 /*cMillies*/,
820 (PFNRT)drvCloudTunnelReceiveWakeup, 1, pThis);
821 if (RT_FAILURE(rc))
822 LogRel(("%s: failed to wake up device thread - %Rrc\n", pThis->pszInstance, rc));
823 if (RT_SUCCESS(rc))
824 RTReqRelease(pReq);
825
826 return rc;
827}
828
829#define DRVCLOUDTUNNEL_COMMAND_BUFFER_SIZE 1024
830#define DRVCLOUDTUNNEL_OUTPUT_BUFFER_SIZE 65536
831
832static int drvCloudTunnelExecuteRemoteCommandNoOutput(PDRVCLOUDTUNNEL pThis, const char *pcszCommand, ...)
833{
834 va_list va;
835 va_start(va, pcszCommand);
836
837 size_t cb = RTStrPrintfV(pThis->pszCommandBuffer, DRVCLOUDTUNNEL_COMMAND_BUFFER_SIZE, pcszCommand, va);
838 if (cb == 0)
839 {
840 Log(("%s: Failed to process '%s'\n", pThis->pszInstance, pcszCommand));
841 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
842 N_("Failed to compose command line"));
843 }
844
845 LogFlow(("%s: [REMOTE] executing '%s'...\n", pThis->pszInstance, pThis->pszCommandBuffer));
846
847 ssh_channel channel = ssh_channel_new(pThis->pSshSession);
848 if (channel == NULL)
849 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
850 N_("Failed to allocate new channel"));
851
852 int rc = ssh_channel_open_session(channel);
853 if (rc != SSH_OK)
854 rc = PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
855 N_("Failed to open session channel"));
856 else
857 {
858 rc = ssh_channel_request_exec(channel, pThis->pszCommandBuffer);
859 if (rc != SSH_OK)
860 {
861 LogRel(("%s: Failed to execute '%s'\n", pThis->pszInstance, pThis->pszCommandBuffer));
862 Log(("%s: Failed to execute '%s'\n", pThis->pszInstance, pThis->pszCommandBuffer));
863 rc = PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
864 N_("Execute request failed with %d"), rc);
865 }
866 ssh_channel_close(channel);
867 }
868 ssh_channel_free(channel);
869
870 return VINF_SUCCESS;
871}
872
873
874static int drvCloudTunnelExecuteRemoteCommand(PDRVCLOUDTUNNEL pThis, const char *pcszCommand, ...)
875{
876 va_list va;
877 va_start(va, pcszCommand);
878
879 size_t cb = RTStrPrintfV(pThis->pszCommandBuffer, DRVCLOUDTUNNEL_COMMAND_BUFFER_SIZE, pcszCommand, va);
880 if (cb == 0)
881 {
882 Log(("%s: Failed to process '%s'\n", pThis->pszInstance, pcszCommand));
883 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
884 N_("Failed to compose command line"));
885 }
886
887 LogFlow(("%s: [REMOTE] executing '%s'...\n", pThis->pszInstance, pThis->pszCommandBuffer));
888
889 ssh_channel channel = ssh_channel_new(pThis->pSshSession);
890 if (channel == NULL)
891 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
892 N_("Failed to allocate new channel"));
893
894 int rc = ssh_channel_open_session(channel);
895 if (rc != SSH_OK)
896 rc = PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
897 N_("Failed to open session channel"));
898 else
899 {
900 rc = ssh_channel_request_exec(channel, pThis->pszCommandBuffer);
901 if (rc != SSH_OK)
902 {
903 LogRel(("%s: Failed to execute '%s'\n", pThis->pszInstance, pThis->pszCommandBuffer));
904 Log(("%s: Failed to execute '%s'\n", pThis->pszInstance, pThis->pszCommandBuffer));
905 rc = PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
906 N_("Execute request failed with %d"), rc);
907 }
908 else
909 {
910 int cbSpaceLeft = DRVCLOUDTUNNEL_OUTPUT_BUFFER_SIZE;
911 int cbStdOut = 0;
912 char *pszBuffer = pThis->pszOutputBuffer;
913 int cBytes = ssh_channel_read_timeout(channel, pszBuffer, cbSpaceLeft, 0, 60000 /* ms */); /* Is 60 seconds really enough? */
914 while (cBytes > 0)
915 {
916 cbStdOut += cBytes;
917 pszBuffer += cBytes;
918 cbSpaceLeft -= cBytes;
919 if (cbSpaceLeft <= 0)
920 break;
921 cBytes = ssh_channel_read_timeout(channel, pszBuffer, cbSpaceLeft, 0, 60000 /* ms */); /* Is 60 seconds really enough? */
922 }
923 if (cBytes < 0)
924 {
925 LogRel(("%s: while executing '%s' ssh_channel_read_timeout returned error\n", pThis->pszInstance, pThis->pszCommandBuffer));
926 Log(("%s: while executing '%s' ssh_channel_read_timeout returned error\n", pThis->pszInstance, pThis->pszCommandBuffer));
927 rc = VERR_INTERNAL_ERROR;
928 }
929 else
930 {
931 /* Make sure the buffer is terminated. */
932 if (cbStdOut < DRVCLOUDTUNNEL_OUTPUT_BUFFER_SIZE)
933 if (cbStdOut > 1 && pThis->pszOutputBuffer[cbStdOut - 1] == '\n')
934 pThis->pszOutputBuffer[cbStdOut - 1] = 0; /* Trim newline */
935 else
936 pThis->pszOutputBuffer[cbStdOut] = 0;
937 else
938 pThis->pszOutputBuffer[DRVCLOUDTUNNEL_OUTPUT_BUFFER_SIZE - 1] = 0; /* No choice but to eat up last character. Could have returned warning though. */
939 if (cbStdOut == 0)
940 Log(("%s: received no output from remote console\n", pThis->pszInstance));
941 else
942 Log(("%s: received output from remote console:\n%s\n", pThis->pszInstance, pThis->pszOutputBuffer));
943 rc = VINF_SUCCESS;
944
945 char *pszErrorBuffer = (char *)RTMemAlloc(DRVCLOUDTUNNEL_OUTPUT_BUFFER_SIZE);
946 if (pszErrorBuffer == NULL)
947 {
948 LogRel(("%s: Failed to allocate error buffer\n", pThis->pszInstance));
949 rc = VERR_INTERNAL_ERROR;
950 }
951 else
952 {
953 /* Report errors if there were any */
954 cBytes = ssh_channel_read_timeout(channel, pszErrorBuffer, DRVCLOUDTUNNEL_OUTPUT_BUFFER_SIZE, 1, 0); /* Peek at stderr */
955 if (cBytes > 0)
956 {
957 LogRel(("%s: WARNING! While executing '%s' remote console reported errors:\n", pThis->pszInstance, pThis->pszCommandBuffer));
958 Log(("%s: WARNING! While executing '%s' remote console reported errors:\n", pThis->pszInstance, pThis->pszCommandBuffer));
959 }
960 while (cBytes > 0)
961 {
962 LogRel(("%.*s", cBytes, pszErrorBuffer));
963 Log(("%.*s", cBytes, pszErrorBuffer));
964 cBytes = ssh_channel_read_timeout(channel, pszErrorBuffer, DRVCLOUDTUNNEL_OUTPUT_BUFFER_SIZE, 1, 1000); /* Wait for a second for more error output */
965 }
966 RTMemFree(pszErrorBuffer);
967 }
968 }
969 ssh_channel_send_eof(channel);
970 }
971 ssh_channel_close(channel);
972 }
973 ssh_channel_free(channel);
974
975 return VINF_SUCCESS;
976}
977
978
979static int drvCloudTunnelCloudInstanceInitialConfig(PDRVCLOUDTUNNEL pThis)
980{
981 LogFlow(("%s: configuring cloud instance...\n", pThis->pszInstance));
982
983 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])\"");
984 if (RT_FAILURE(rc))
985 rc = PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
986 N_("Failed to get network config via console channel"));
987 else
988 {
989 char *pszConfig = RTStrStr(pThis->pszOutputBuffer, "CONFIG: ");
990 if (!pszConfig)
991 rc = PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
992 N_("Failed to parse network config"));
993 else
994 {
995 char **ppapszTokens;
996 size_t cTokens;
997 rc = RTStrSplit(pszConfig + 8, DRVCLOUDTUNNEL_OUTPUT_BUFFER_SIZE - (pszConfig - pThis->pszOutputBuffer) - 8,
998 " ", &ppapszTokens, &cTokens);
999 if (RT_SUCCESS(rc))
1000 {
1001 /*
1002 * There should be exactly three tokens:
1003 * 1) Primary network interface name;
1004 * 2) Secondary network interface name;
1005 * 3) Secondary network gateway address.
1006 */
1007 if (cTokens != 3)
1008 Log(("%s: Got %u tokes instead of three while parsing '%s'\n", pThis->pszInstance, cTokens, pThis->pszOutputBuffer));
1009 else
1010 {
1011 char *pszSecondaryInterface = NULL;
1012 char *pszSecondaryGateway = NULL;
1013
1014 if (pThis->pszCloudPrimaryInterface)
1015 RTStrFree(pThis->pszCloudPrimaryInterface);
1016 pThis->pszCloudPrimaryInterface = RTStrDup(ppapszTokens[0]);
1017 pszSecondaryInterface = ppapszTokens[1];
1018 pszSecondaryGateway = ppapszTokens[2];
1019 Log(("%s: primary=%s secondary=%s gateway=%s\n", pThis->pszInstance, pThis->pszCloudPrimaryInterface, pszSecondaryInterface, pszSecondaryGateway));
1020
1021 rc = drvCloudTunnelExecuteRemoteCommand(pThis, "sudo oci-network-config -c");
1022 if (RT_SUCCESS(rc))
1023 rc = drvCloudTunnelExecuteRemoteCommand(pThis, "sudo ip tuntap add dev tap0 mod tap user opc");
1024 if (RT_SUCCESS(rc))
1025 rc = drvCloudTunnelExecuteRemoteCommand(pThis, "sudo sh -c 'echo \"PermitTunnel yes\" >> /etc/ssh/sshd_config'");
1026 if (RT_SUCCESS(rc))
1027 rc = drvCloudTunnelExecuteRemoteCommand(pThis, "sudo kill -SIGHUP $(pgrep -f \"sshd -D\")");
1028 if (RT_SUCCESS(rc))
1029 rc = drvCloudTunnelExecuteRemoteCommand(pThis, "sudo ip link add name br0 type bridge");
1030 if (RT_SUCCESS(rc))
1031 rc = drvCloudTunnelExecuteRemoteCommand(pThis, "sudo ip link set dev tap0 master br0");
1032 if (RT_SUCCESS(rc))
1033 rc = drvCloudTunnelExecuteRemoteCommandNoOutput(pThis, "sudo ip route change default via %s dev %s", pszSecondaryGateway, pszSecondaryInterface);
1034 if (RT_FAILURE(rc))
1035 rc = PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1036 N_("Failed to execute network config command via console channel"));
1037 }
1038
1039 for (size_t i = 0; i < cTokens; i++)
1040 RTStrFree(ppapszTokens[i]);
1041 RTMemFree(ppapszTokens);
1042 }
1043 }
1044 }
1045
1046 return rc;
1047}
1048
1049
1050static int drvCloudTunnelCloudInstanceFinalConfig(PDRVCLOUDTUNNEL pThis)
1051{
1052 if (pThis->pszCloudPrimaryInterface == NULL)
1053 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1054 N_("Failed to finalize cloud instance config because of unknown primary interface name!"));
1055
1056 LogFlow(("%s: finalizing cloud instance configuration...\n", pThis->pszInstance));
1057
1058 int rc = drvCloudTunnelExecuteRemoteCommand(pThis, "sudo ip link set dev %s down", pThis->pszCloudPrimaryInterface);
1059 if (RT_SUCCESS(rc))
1060 rc = drvCloudTunnelExecuteRemoteCommand(pThis, "sudo ip link set dev %s address %RTmac", pThis->pszCloudPrimaryInterface, pThis->targetMac.au8);
1061 if (RT_SUCCESS(rc))
1062 rc = drvCloudTunnelExecuteRemoteCommand(pThis, "sudo ifconfig %s 0.0.0.0", pThis->pszCloudPrimaryInterface); /* Make sure no IP is configured on primary */
1063 if (RT_SUCCESS(rc))
1064 rc = drvCloudTunnelExecuteRemoteCommand(pThis, "sudo ip link set dev %s master br0", pThis->pszCloudPrimaryInterface);
1065 if (RT_SUCCESS(rc))
1066 rc = drvCloudTunnelExecuteRemoteCommand(pThis, "sudo ip link set dev %s up", pThis->pszCloudPrimaryInterface);
1067 if (RT_SUCCESS(rc))
1068 rc = drvCloudTunnelExecuteRemoteCommand(pThis, "sudo ip link set dev tap0 up");
1069 if (RT_SUCCESS(rc))
1070 rc = drvCloudTunnelExecuteRemoteCommand(pThis, "sudo ip link set dev br0 up");
1071 if (RT_FAILURE(rc))
1072 rc = PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1073 N_("Failed to execute network config command via console channel"));
1074
1075 return rc;
1076}
1077
1078
1079static int drvCloudTunnelOpenTunnelChannel(PDRVCLOUDTUNNEL pThis)
1080{
1081 LogFlow(("%s: opening tunnel channel...\n", pThis->pszInstance));
1082 pThis->pSshChannel = ssh_channel_new(pThis->pSshSession);
1083 if (pThis->pSshChannel == NULL)
1084 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1085 N_("Failed to allocate new channel"));
1086 int rc = ssh_channel_open_tunnel(pThis->pSshChannel, 0);
1087 if (rc < 0)
1088 rc = PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1089 N_("Failed to open tunnel channel"));
1090 else
1091 {
1092 /* Set packet receive callback. */
1093 rc = ssh_set_channel_callbacks(pThis->pSshChannel, &pThis->Callbacks);
1094 if (rc != SSH_OK)
1095 rc = PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1096 N_("Failed to set packet receive callback"));
1097 }
1098
1099 return rc;
1100}
1101
1102
1103static void closeTunnelChannel(PDRVCLOUDTUNNEL pThis)
1104{
1105 if (pThis->pSshChannel)
1106 {
1107 LogFlow(("%s: closing tunnel channel %p\n", pThis->pszInstance, pThis->pSshChannel));
1108 ssh_channel_close(pThis->pSshChannel);
1109 ssh_channel_free(pThis->pSshChannel);
1110 pThis->pSshChannel = NULL;
1111 }
1112}
1113
1114
1115static int drvCloudTunnelStartIoThread(PDRVCLOUDTUNNEL pThis)
1116{
1117 LogFlow(("%s: starting I/O thread...\n", pThis->pszInstance));
1118 int rc = createConnectedSockets(pThis);
1119 if (RT_FAILURE(rc))
1120 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1121 N_("CloudTunnel: Failed to create a pair of connected sockets"));
1122
1123 /*
1124 * Start the cloud I/O thread.
1125 */
1126 rc = PDMDrvHlpThreadCreate(pThis->pDrvIns, &pThis->pIoThread,
1127 pThis, drvCloudTunnelIoThread, drvCloudTunnelIoWakeup,
1128 64 * _1K, RTTHREADTYPE_IO, pThis->pszInstanceIo);
1129 if (RT_FAILURE(rc))
1130 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1131 N_("CloudTunnel: Failed to start I/O thread"));
1132
1133 return rc;
1134}
1135
1136static void drvCloudTunnelStopIoThread(PDRVCLOUDTUNNEL pThis)
1137{
1138 if (pThis->pIoThread)
1139 {
1140 LogFlow(("%s: stopping I/O thread...\n", pThis->pszInstance));
1141 int rc = PDMDrvHlpThreadDestroy(pThis->pDrvIns, pThis->pIoThread, NULL);
1142 AssertRC(rc);
1143 pThis->pIoThread = NULL;
1144 }
1145 destroyConnectedSockets(pThis);
1146
1147}
1148
1149static int destroyTunnel(PDRVCLOUDTUNNEL pThis)
1150{
1151 if (pThis->pSshChannel)
1152 {
1153 int rc = ssh_remove_channel_callbacks(pThis->pSshChannel, &pThis->Callbacks);
1154 if (rc != SSH_OK)
1155 LogRel(("%s: WARNING! Failed to remove tunnel channel callbacks.\n", pThis->pszInstance));
1156 }
1157 drvCloudTunnelStopIoThread(pThis);
1158 closeTunnelChannel(pThis);
1159 ssh_disconnect(pThis->pSshSession);
1160 ssh_free(pThis->pSshSession);
1161 pThis->pSshSession = NULL;
1162 return VINF_SUCCESS;
1163}
1164
1165
1166static int drvCloudTunnelNewSession(PDRVCLOUDTUNNEL pThis, bool fPrimary)
1167{
1168 pThis->pSshSession = ssh_new();
1169 if (pThis->pSshSession == NULL)
1170 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1171 N_("CloudTunnel: Failed to allocate new SSH session"));
1172 if (ssh_options_set(pThis->pSshSession, SSH_OPTIONS_LOG_VERBOSITY, &pThis->iSshVerbosity) < 0)
1173 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1174 N_("Failed to set SSH_OPTIONS_LOG_VERBOSITY"));
1175 if (ssh_options_set(pThis->pSshSession, SSH_OPTIONS_USER, pThis->pszUser) < 0)
1176 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1177 N_("Failed to set SSH_OPTIONS_USER"));
1178 if (ssh_options_set(pThis->pSshSession, SSH_OPTIONS_HOST, fPrimary ? pThis->pszPrimaryIP : pThis->pszSecondaryIP) < 0)
1179 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1180 N_("Failed to set SSH_OPTIONS_HOST"));
1181
1182 if (ssh_options_set(pThis->pSshSession, SSH_OPTIONS_TIMEOUT, &pThis->ulTimeoutInSecounds) < 0)
1183 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1184 N_("Failed to set SSH_OPTIONS_TIMEOUT"));
1185
1186 const char *pcszProxyType = fPrimary ? pThis->pszPrimaryProxyType : pThis->pszSecondaryProxyType;
1187 if (pcszProxyType)
1188 {
1189 char szProxyCmd[1024];
1190
1191 const char *pcszProxyUser = fPrimary ? pThis->pszPrimaryProxyUser : pThis->pszSecondaryProxyUser;
1192 if (pcszProxyUser)
1193 RTStrPrintf(szProxyCmd, sizeof(szProxyCmd), "#VBoxProxy%s %s %u %s %s",
1194 fPrimary ? pThis->pszPrimaryProxyType : pThis->pszSecondaryProxyType,
1195 fPrimary ? pThis->pszPrimaryProxyHost : pThis->pszSecondaryProxyHost,
1196 fPrimary ? pThis->u16PrimaryProxyPort : pThis->u16SecondaryProxyPort,
1197 fPrimary ? pThis->pszPrimaryProxyUser : pThis->pszSecondaryProxyUser,
1198 fPrimary ? pThis->pszPrimaryProxyPassword : pThis->pszSecondaryProxyPassword);
1199 else
1200 RTStrPrintf(szProxyCmd, sizeof(szProxyCmd), "#VBoxProxy%s %s %u",
1201 fPrimary ? pThis->pszPrimaryProxyType : pThis->pszSecondaryProxyType,
1202 fPrimary ? pThis->pszPrimaryProxyHost : pThis->pszSecondaryProxyHost,
1203 fPrimary ? pThis->u16PrimaryProxyPort : pThis->u16SecondaryProxyPort);
1204 LogRel(("%s: using proxy command '%s'\n", pThis->pszInstance, szProxyCmd));
1205 if (ssh_options_set(pThis->pSshSession, SSH_OPTIONS_PROXYCOMMAND, szProxyCmd) < 0)
1206 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1207 N_("Failed to set SSH_OPTIONS_PROXYCOMMAND"));
1208 }
1209
1210 int rc = ssh_connect(pThis->pSshSession);
1211 for (int cAttempt = 1; rc != SSH_OK && cAttempt <= 5; cAttempt++)
1212 {
1213 ssh_disconnect(pThis->pSshSession);
1214 /* One more time, just to be sure. */
1215 LogRel(("%s: failed to connect to %s, retrying(#%d)...\n", pThis->pszInstance,
1216 fPrimary ? pThis->pszPrimaryIP : pThis->pszSecondaryIP, cAttempt));
1217 RTThreadSleep(10000); /* Sleep 10 seconds, then retry */
1218 rc = ssh_connect(pThis->pSshSession);
1219 }
1220 if (rc != SSH_OK)
1221 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1222 N_("CloudTunnel: Failed to connect to %s interface"), fPrimary ? "primary" : "secondary");
1223
1224 rc = ssh_userauth_publickey(pThis->pSshSession, NULL, pThis->SshKey);
1225 if (rc != SSH_AUTH_SUCCESS)
1226 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1227 N_("Failed to authenticate with public key"));
1228
1229 return VINF_SUCCESS;
1230}
1231
1232static int drvCloudTunnelSwitchToSecondary(PDRVCLOUDTUNNEL pThis)
1233{
1234 int rc = drvCloudTunnelNewSession(pThis, true /* fPrimary */);
1235 /*
1236 * Establish temporary console channel and configure the cloud instance
1237 * to bridge the tunnel channel to instance's primary interface.
1238 */
1239 if (RT_SUCCESS(rc))
1240 rc = drvCloudTunnelCloudInstanceInitialConfig(pThis);
1241
1242 ssh_disconnect(pThis->pSshSession);
1243 ssh_free(pThis->pSshSession);
1244 pThis->pSshSession = NULL;
1245
1246 return rc;
1247}
1248
1249
1250static int establishTunnel(PDRVCLOUDTUNNEL pThis)
1251{
1252 int rc = drvCloudTunnelNewSession(pThis, false /* fPrimary */);
1253 if (RT_SUCCESS(rc))
1254 rc = drvCloudTunnelCloudInstanceFinalConfig(pThis);
1255 if (RT_SUCCESS(rc))
1256 rc = drvCloudTunnelOpenTunnelChannel(pThis);
1257 if (RT_SUCCESS(rc))
1258 rc = drvCloudTunnelStartIoThread(pThis);
1259 if (RT_FAILURE(rc))
1260 {
1261 destroyTunnel(pThis);
1262 return rc;
1263 }
1264
1265 return rc;
1266}
1267
1268
1269static DECL_NOTHROW(void) drvCloudTunnelSshLogCallback(int priority, const char *function, const char *buffer, void *userdata)
1270{
1271 PDRVCLOUDTUNNEL pThis = (PDRVCLOUDTUNNEL)userdata;
1272#ifdef LOG_ENABLED
1273 const char *pcszVerbosity;
1274 switch (priority)
1275 {
1276 case SSH_LOG_WARNING:
1277 pcszVerbosity = "WARNING";
1278 break;
1279 case SSH_LOG_PROTOCOL:
1280 pcszVerbosity = "PROTOCOL";
1281 break;
1282 case SSH_LOG_PACKET:
1283 pcszVerbosity = "PACKET";
1284 break;
1285 case SSH_LOG_FUNCTIONS:
1286 pcszVerbosity = "FUNCTIONS";
1287 break;
1288 default:
1289 pcszVerbosity = "UNKNOWN";
1290 break;
1291 }
1292 Log3(("%s: SSH-%s: %s: %s\n", pThis->pszInstance, pcszVerbosity, function, buffer));
1293#else
1294 RT_NOREF(priority);
1295 LogRel(("%s: SSH %s: %s\n", pThis->pszInstance, function, buffer));
1296#endif
1297}
1298
1299/* -=-=-=-=- PDMDRVREG -=-=-=-=- */
1300
1301DECLINLINE(void) drvCloudTunnelStrFree(char **ppszString)
1302{
1303 if (*ppszString)
1304 {
1305 RTStrFree(*ppszString);
1306 *ppszString = NULL;
1307 }
1308}
1309
1310DECLINLINE(void) drvCloudTunnelHeapFree(PPDMDRVINS pDrvIns, char **ppszString)
1311{
1312 if (*ppszString)
1313 {
1314 PDMDrvHlpMMHeapFree(pDrvIns, *ppszString);
1315 *ppszString = NULL;
1316 }
1317}
1318
1319/**
1320 * Destruct a driver instance.
1321 *
1322 * Most VM resources are freed by the VM. This callback is provided so that any non-VM
1323 * resources can be freed correctly.
1324 *
1325 * @param pDrvIns The driver instance data.
1326 */
1327static DECLCALLBACK(void) drvCloudTunnelDestruct(PPDMDRVINS pDrvIns)
1328{
1329 LogFlowFunc(("\n"));
1330 PDRVCLOUDTUNNEL pThis = PDMINS_2_DATA(pDrvIns, PDRVCLOUDTUNNEL);
1331 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
1332
1333 ASMAtomicXchgSize(&pThis->fLinkDown, true);
1334
1335 destroyTunnel(pThis);
1336
1337 if (pThis->hIoReqQueue != NIL_RTREQQUEUE)
1338 {
1339 RTReqQueueDestroy(pThis->hIoReqQueue);
1340 pThis->hIoReqQueue = NIL_RTREQQUEUE;
1341 }
1342
1343 drvCloudTunnelStrFree(&pThis->pszCloudPrimaryInterface);
1344
1345 drvCloudTunnelHeapFree(pDrvIns, &pThis->pszPrimaryProxyType);
1346 drvCloudTunnelStrFree(&pThis->pszPrimaryProxyHost);
1347 drvCloudTunnelHeapFree(pDrvIns, &pThis->pszPrimaryProxyUser);
1348 drvCloudTunnelStrFree(&pThis->pszPrimaryProxyPassword);
1349
1350 drvCloudTunnelHeapFree(pDrvIns, &pThis->pszSecondaryProxyType);
1351 drvCloudTunnelStrFree(&pThis->pszSecondaryProxyHost);
1352 drvCloudTunnelHeapFree(pDrvIns, &pThis->pszSecondaryProxyUser);
1353 drvCloudTunnelStrFree(&pThis->pszSecondaryProxyPassword);
1354
1355 drvCloudTunnelStrFree(&pThis->pszSecondaryIP);
1356 drvCloudTunnelStrFree(&pThis->pszPrimaryIP);
1357 drvCloudTunnelStrFree(&pThis->pszUser);
1358
1359 drvCloudTunnelStrFree(&pThis->pszInstanceDev);
1360 drvCloudTunnelStrFree(&pThis->pszInstanceIo);
1361 drvCloudTunnelStrFree(&pThis->pszInstance);
1362
1363 drvCloudTunnelStrFree(&pThis->pszOutputBuffer);
1364 drvCloudTunnelStrFree(&pThis->pszCommandBuffer);
1365
1366 ssh_key_free(pThis->SshKey);
1367
1368 ssh_finalize();
1369 //OPENSSL_cleanup();
1370
1371 // if (pThis->pServer)
1372 // {
1373 // RTUdpServerDestroy(pThis->pServer);
1374 // pThis->pServer = NULL;
1375 // }
1376
1377 /*
1378 * Kill the xmit lock.
1379 */
1380 if (RTCritSectIsInitialized(&pThis->XmitLock))
1381 RTCritSectDelete(&pThis->XmitLock);
1382
1383#ifdef VBOX_WITH_STATISTICS
1384 /*
1385 * Deregister statistics.
1386 */
1387 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatPktSent);
1388 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatPktSentBytes);
1389 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatPktRecv);
1390 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatPktRecvBytes);
1391 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatTransmit);
1392 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatReceive);
1393 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatDevRecv);
1394 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatDevRecvWait);
1395#endif /* VBOX_WITH_STATISTICS */
1396}
1397
1398
1399/**
1400 * Construct a Cloud tunnel network transport driver instance.
1401 *
1402 * @copydoc FNPDMDRVCONSTRUCT
1403 */
1404static DECLCALLBACK(int) drvCloudTunnelConstruct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t fFlags)
1405{
1406 RT_NOREF(fFlags);
1407 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
1408 PDRVCLOUDTUNNEL pThis = PDMINS_2_DATA(pDrvIns, PDRVCLOUDTUNNEL);
1409 PCPDMDRVHLPR3 pHlp = pDrvIns->pHlpR3;
1410
1411 /*
1412 * Init the static parts.
1413 */
1414 pThis->pDrvIns = pDrvIns;
1415 pThis->pszCommandBuffer = NULL;
1416 pThis->pszOutputBuffer = NULL;
1417 pThis->pszInstance = NULL;
1418 pThis->pszPrimaryIP = NULL;
1419 pThis->pszSecondaryIP = NULL;
1420 pThis->pszUser = NULL;
1421 pThis->SshKey = 0;
1422
1423 /* IBase */
1424 pDrvIns->IBase.pfnQueryInterface = drvCloudTunnelQueryInterface;
1425 /* INetwork */
1426 pThis->INetworkUp.pfnBeginXmit = drvCloudTunnelUp_BeginXmit;
1427 pThis->INetworkUp.pfnAllocBuf = drvCloudTunnelUp_AllocBuf;
1428 pThis->INetworkUp.pfnFreeBuf = drvCloudTunnelUp_FreeBuf;
1429 pThis->INetworkUp.pfnSendBuf = drvCloudTunnelUp_SendBuf;
1430 pThis->INetworkUp.pfnEndXmit = drvCloudTunnelUp_EndXmit;
1431 pThis->INetworkUp.pfnSetPromiscuousMode = drvCloudTunnelUp_SetPromiscuousMode;
1432 pThis->INetworkUp.pfnNotifyLinkChanged = drvCloudTunnelUp_NotifyLinkChanged;
1433
1434 /* ??? */
1435 pThis->iSocketIn = INVALID_SOCKET;
1436 pThis->iSocketOut = INVALID_SOCKET;
1437 pThis->pSshSession = 0;
1438 pThis->pSshChannel = 0;
1439
1440 pThis->pDevThread = 0;
1441 pThis->pIoThread = 0;
1442 pThis->hIoReqQueue = NIL_RTREQQUEUE;
1443
1444 pThis->fLinkDown = false;
1445
1446 pThis->pszCloudPrimaryInterface = NULL;
1447
1448#ifdef VBOX_WITH_STATISTICS
1449 /*
1450 * Statistics.
1451 */
1452 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatPktSent, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of sent packets.", "/Drivers/CloudTunnel%d/Packets/Sent", pDrvIns->iInstance);
1453 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatPktSentBytes, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_BYTES, "Number of sent bytes.", "/Drivers/CloudTunnel%d/Bytes/Sent", pDrvIns->iInstance);
1454 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatPktRecv, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of received packets.", "/Drivers/CloudTunnel%d/Packets/Received", pDrvIns->iInstance);
1455 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatPktRecvBytes, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_BYTES, "Number of received bytes.", "/Drivers/CloudTunnel%d/Bytes/Received", pDrvIns->iInstance);
1456 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatTransmit, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS, STAMUNIT_TICKS_PER_CALL, "Profiling packet transmit runs.", "/Drivers/CloudTunnel%d/Transmit", pDrvIns->iInstance);
1457 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatReceive, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS, STAMUNIT_TICKS_PER_CALL, "Profiling packet receive runs.", "/Drivers/CloudTunnel%d/Receive", pDrvIns->iInstance);
1458 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatDevRecv, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS, STAMUNIT_TICKS_PER_CALL, "Profiling device receive runs.", "/Drivers/CloudTunnel%d/DeviceReceive", pDrvIns->iInstance);
1459 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatDevRecvWait, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS, STAMUNIT_TICKS_PER_CALL, "Profiling device receive waits.", "/Drivers/CloudTunnel%d/DeviceReceiveWait", pDrvIns->iInstance);
1460#endif /* VBOX_WITH_STATISTICS */
1461
1462 /*
1463 * Validate the config.
1464 */
1465 PDMDRV_VALIDATE_CONFIG_RETURN(pDrvIns, "SshKey"
1466 "|PrimaryIP"
1467 "|SecondaryIP"
1468 "|TargetMAC"
1469
1470 "|PrimaryProxyType"
1471 "|PrimaryProxyHost"
1472 "|PrimaryProxyPort"
1473 "|PrimaryProxyUser"
1474 "|PrimaryProxyPassword"
1475 "|SecondaryProxyType"
1476 "|SecondaryProxyHost"
1477 "|SecondaryProxyPort"
1478 "|SecondaryProxyUser"
1479 "|SecondaryProxyPassword"
1480
1481 ,"");
1482
1483 /*
1484 * Check that no-one is attached to us.
1485 */
1486 AssertMsgReturn(PDMDrvHlpNoAttach(pDrvIns) == VERR_PDM_NO_ATTACHED_DRIVER,
1487 ("Configuration error: Not possible to attach anything to this driver!\n"),
1488 VERR_PDM_DRVINS_NO_ATTACH);
1489
1490 /*
1491 * Query the network port interface.
1492 */
1493 pThis->pIAboveNet = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMINETWORKDOWN);
1494 if (!pThis->pIAboveNet)
1495 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_MISSING_INTERFACE_ABOVE,
1496 N_("Configuration error: The above device/driver didn't export the network port interface"));
1497
1498 /*
1499 * Read the configuration.
1500 */
1501 int rc;
1502
1503 char szVal[2048];
1504 RTNETADDRIPV4 tmpAddr;
1505 rc = pHlp->pfnCFGMQueryString(pCfg, "PrimaryIP", szVal, sizeof(szVal));
1506 if (RT_FAILURE(rc))
1507 return PDMDRV_SET_ERROR(pDrvIns, rc,
1508 N_("DrvCloudTunnel: Configuration error: Querying \"PrimaryIP\" as string failed"));
1509 rc = RTNetStrToIPv4Addr(szVal, &tmpAddr);
1510 if (RT_FAILURE(rc))
1511 return PDMDRV_SET_ERROR(pDrvIns, rc,
1512 N_("DrvCloudTunnel: Configuration error: \"PrimaryIP\" is not valid"));
1513 else
1514 pThis->pszPrimaryIP = RTStrDup(szVal);
1515
1516 rc = pHlp->pfnCFGMQueryString(pCfg, "SecondaryIP", szVal, sizeof(szVal));
1517 if (RT_FAILURE(rc))
1518 return PDMDRV_SET_ERROR(pDrvIns, rc,
1519 N_("DrvCloudTunnel: Configuration error: Querying \"SecondaryIP\" as string failed"));
1520 rc = RTNetStrToIPv4Addr(szVal, &tmpAddr);
1521 if (RT_FAILURE(rc))
1522 return PDMDRV_SET_ERROR(pDrvIns, rc,
1523 N_("DrvCloudTunnel: Configuration error: \"SecondaryIP\" is not valid"));
1524 else
1525 pThis->pszSecondaryIP = RTStrDup(szVal);
1526 rc = pHlp->pfnCFGMQueryBytes(pCfg, "TargetMAC", pThis->targetMac.au8, sizeof(pThis->targetMac.au8));
1527 if (RT_FAILURE(rc))
1528 return PDMDRV_SET_ERROR(pDrvIns, rc,
1529 N_("DrvCloudTunnel: Configuration error: Failed to get target MAC address"));
1530 /** @todo In the near future we will want to include proxy settings here! */
1531 // Do we want to pass the user name via CFGM?
1532 pThis->pszUser = RTStrDup("opc");
1533 // Is it safe to expose verbosity via CFGM?
1534#ifdef LOG_ENABLED
1535 pThis->iSshVerbosity = SSH_LOG_PACKET; //SSH_LOG_FUNCTIONS;
1536#else
1537 pThis->iSshVerbosity = SSH_LOG_WARNING;
1538#endif
1539
1540 pThis->ulTimeoutInSecounds = 30; /* The default 10-second timeout is too short? */
1541
1542 rc = pHlp->pfnCFGMQueryPassword(pCfg, "SshKey", szVal, sizeof(szVal));
1543 if (RT_FAILURE(rc))
1544 return PDMDRV_SET_ERROR(pDrvIns, rc,
1545 N_("DrvCloudTunnel: Configuration error: Querying \"SshKey\" as password failed"));
1546 rc = ssh_pki_import_privkey_base64(szVal, NULL, NULL, NULL, &pThis->SshKey);
1547 RTMemWipeThoroughly(szVal, sizeof(szVal), 10);
1548 if (rc != SSH_OK)
1549 return PDMDRV_SET_ERROR(pDrvIns, VERR_INVALID_BASE64_ENCODING,
1550 N_("DrvCloudTunnel: Configuration error: Converting \"SshKey\" from base64 failed"));
1551
1552 /* PrimaryProxyType is optional */
1553 rc = pHlp->pfnCFGMQueryStringAllocDef(pCfg, "PrimaryProxyType", &pThis->pszPrimaryProxyType, NULL);
1554 if (RT_FAILURE(rc))
1555 return PDMDRV_SET_ERROR(pDrvIns, rc,
1556 N_("DrvCloudTunnel: Configuration error: Querying \"PrimaryProxyType\" as string failed"));
1557 if (pThis->pszPrimaryProxyType)
1558 {
1559 rc = pHlp->pfnCFGMQueryString(pCfg, "PrimaryProxyHost", szVal, sizeof(szVal));
1560 if (RT_FAILURE(rc))
1561 return PDMDRV_SET_ERROR(pDrvIns, rc,
1562 N_("DrvCloudTunnel: Configuration error: Querying \"PrimaryProxyHost\" as string failed"));
1563 rc = RTNetStrToIPv4Addr(szVal, &tmpAddr);
1564 if (RT_FAILURE(rc))
1565 return PDMDRV_SET_ERROR(pDrvIns, rc,
1566 N_("DrvCloudTunnel: Configuration error: \"PrimaryProxyHost\" is not valid"));
1567 else
1568 pThis->pszPrimaryProxyHost = RTStrDup(szVal);
1569
1570 uint64_t u64Val;
1571 rc = pHlp->pfnCFGMQueryInteger(pCfg, "PrimaryProxyPort", &u64Val);
1572 if (RT_FAILURE(rc))
1573 return PDMDRV_SET_ERROR(pDrvIns, rc,
1574 N_("DrvCloudTunnel: Configuration error: Querying \"PrimaryProxyPort\" as integer failed"));
1575 if (u64Val > 0xFFFF)
1576 return PDMDRV_SET_ERROR(pDrvIns, rc,
1577 N_("DrvCloudTunnel: Configuration error: \"PrimaryProxyPort\" is not valid"));
1578 pThis->u16PrimaryProxyPort = (uint16_t)u64Val;
1579
1580 /* PrimaryProxyUser is optional */
1581 rc = pHlp->pfnCFGMQueryStringAllocDef(pCfg, "PrimaryProxyUser", &pThis->pszPrimaryProxyUser, NULL);
1582 if (RT_FAILURE(rc))
1583 return PDMDRV_SET_ERROR(pDrvIns, rc,
1584 N_("DrvCloudTunnel: Configuration error: Querying \"PrimaryProxyUser\" as string failed"));
1585 /* PrimaryProxyPassword must be present if PrimaryProxyUser is present */
1586 if (pThis->pszPrimaryProxyUser)
1587 {
1588 rc = pHlp->pfnCFGMQueryPassword(pCfg, "PrimaryProxyPassword", szVal, sizeof(szVal));
1589 if (RT_FAILURE(rc))
1590 return PDMDRV_SET_ERROR(pDrvIns, rc,
1591 N_("DrvCloudTunnel: Configuration error: Querying \"PrimaryProxyPassword\" as string failed"));
1592 pThis->pszPrimaryProxyPassword = RTStrDup(szVal);
1593 }
1594 }
1595
1596 /* SecondaryProxyType is optional */
1597 rc = pHlp->pfnCFGMQueryStringAllocDef(pCfg, "SecondaryProxyType", &pThis->pszSecondaryProxyType, NULL);
1598 if (RT_FAILURE(rc))
1599 return PDMDRV_SET_ERROR(pDrvIns, rc,
1600 N_("DrvCloudTunnel: Configuration error: Querying \"SecondaryProxyType\" as string failed"));
1601 if (pThis->pszSecondaryProxyType)
1602 {
1603 if (RT_FAILURE(rc))
1604 return PDMDRV_SET_ERROR(pDrvIns, rc,
1605 N_("DrvCloudTunnel: Configuration error: Querying \"SecondaryProxyType\" as string failed"));
1606
1607 rc = pHlp->pfnCFGMQueryString(pCfg, "SecondaryProxyHost", szVal, sizeof(szVal));
1608 if (RT_FAILURE(rc))
1609 return PDMDRV_SET_ERROR(pDrvIns, rc,
1610 N_("DrvCloudTunnel: Configuration error: Querying \"SecondaryProxyHost\" as string failed"));
1611 rc = RTNetStrToIPv4Addr(szVal, &tmpAddr);
1612 if (RT_FAILURE(rc))
1613 return PDMDRV_SET_ERROR(pDrvIns, rc,
1614 N_("DrvCloudTunnel: Configuration error: \"SecondaryProxyHost\" is not valid"));
1615 else
1616 pThis->pszSecondaryProxyHost = RTStrDup(szVal);
1617
1618 uint64_t u64Val;
1619 rc = pHlp->pfnCFGMQueryInteger(pCfg, "SecondaryProxyPort", &u64Val);
1620 if (RT_FAILURE(rc))
1621 return PDMDRV_SET_ERROR(pDrvIns, rc,
1622 N_("DrvCloudTunnel: Configuration error: Querying \"SecondaryProxyPort\" as integer failed"));
1623 if (u64Val > 0xFFFF)
1624 return PDMDRV_SET_ERROR(pDrvIns, rc,
1625 N_("DrvCloudTunnel: Configuration error: \"SecondaryProxyPort\" is not valid"));
1626 pThis->u16SecondaryProxyPort = (uint16_t)u64Val;
1627
1628 /* SecondaryProxyUser is optional */
1629 rc = pHlp->pfnCFGMQueryStringAllocDef(pCfg, "SecondaryProxyUser", &pThis->pszSecondaryProxyUser, NULL);
1630 if (RT_FAILURE(rc))
1631 return PDMDRV_SET_ERROR(pDrvIns, rc,
1632 N_("DrvCloudTunnel: Configuration error: Querying \"SecondaryProxyUser\" as string failed"));
1633 /* SecondaryProxyPassword must be present if SecondaryProxyUser is present */
1634 if (pThis->pszSecondaryProxyUser)
1635 {
1636 rc = pHlp->pfnCFGMQueryPassword(pCfg, "SecondaryProxyPassword", szVal, sizeof(szVal));
1637 if (RT_FAILURE(rc))
1638 return PDMDRV_SET_ERROR(pDrvIns, rc,
1639 N_("DrvCloudTunnel: Configuration error: Querying \"SecondaryProxyPassword\" as string failed"));
1640 pThis->pszSecondaryProxyPassword = RTStrDup(szVal);
1641 }
1642 }
1643
1644 pThis->pszCommandBuffer = (char *)RTMemAlloc(DRVCLOUDTUNNEL_COMMAND_BUFFER_SIZE);
1645 if (pThis->pszCommandBuffer == NULL)
1646 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_HIF_OPEN_FAILED,
1647 N_("DrvCloudTunnel: Failed to allocate command buffer"));
1648 pThis->pszOutputBuffer = (char *)RTMemAlloc(DRVCLOUDTUNNEL_OUTPUT_BUFFER_SIZE);
1649 if (pThis->pszOutputBuffer == NULL)
1650 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_HIF_OPEN_FAILED,
1651 N_("DrvCloudTunnel: Failed to allocate output buffer"));
1652 /*
1653 * Create unique instance name for logging.
1654 */
1655 rc = RTStrAPrintf(&pThis->pszInstance, "CT#%d", pDrvIns->iInstance);
1656 AssertRC(rc);
1657
1658 LogRel(("%s: primary=%s secondary=%s target-mac=%RTmac\n", pThis->pszInstance, pThis->pszPrimaryIP, pThis->pszSecondaryIP, pThis->targetMac.au8));
1659
1660 /*
1661 * Create unique thread name for cloud I/O.
1662 */
1663 rc = RTStrAPrintf(&pThis->pszInstanceIo, "CTunIO%d", pDrvIns->iInstance);
1664 AssertRC(rc);
1665
1666 /*
1667 * Create unique thread name for device receive function.
1668 */
1669 rc = RTStrAPrintf(&pThis->pszInstanceDev, "CTunDev%d", pDrvIns->iInstance);
1670 AssertRC(rc);
1671
1672 /*
1673 * Create the transmit lock.
1674 */
1675 rc = RTCritSectInit(&pThis->XmitLock);
1676 AssertRCReturn(rc, rc);
1677
1678 /*
1679 * Create the request queue for I/O requests.
1680 */
1681 rc = RTReqQueueCreate(&pThis->hIoReqQueue);
1682 AssertLogRelRCReturn(rc, rc);
1683
1684 /*
1685 * Create the request queue for attached device requests.
1686 */
1687 rc = RTReqQueueCreate(&pThis->hDevReqQueue);
1688 AssertLogRelRCReturn(rc, rc);
1689
1690 /*
1691 * Start the device output thread.
1692 */
1693 rc = PDMDrvHlpThreadCreate(pThis->pDrvIns, &pThis->pDevThread,
1694 pThis, drvCloudTunnelDevThread, drvCloudTunnelDevWakeup,
1695 64 * _1K, RTTHREADTYPE_IO, pThis->pszInstanceDev);
1696 if (RT_FAILURE(rc))
1697 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1698 N_("CloudTunnel: Failed to start device thread"));
1699
1700 rc = ssh_init();
1701 if (rc != SSH_OK)
1702 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1703 N_("CloudTunnel: Failed to initialize libssh"));
1704
1705 memset(&pThis->Callbacks, 0, sizeof(pThis->Callbacks));
1706#ifdef PACKET_CAPTURE_ENABLED
1707 pThis->Callbacks.channel_data_function = drvCloudTunnelReceiveCallbackWithPacketCapture;
1708#else
1709 pThis->Callbacks.channel_data_function = drvCloudTunnelReceiveCallback;
1710#endif
1711 pThis->Callbacks.userdata = pThis;
1712 pThis->Callbacks.channel_write_wontblock_function = channelWriteWontblockCallback;
1713 ssh_callbacks_init(&pThis->Callbacks);
1714
1715 rc = ssh_set_log_callback(drvCloudTunnelSshLogCallback);
1716 if (rc != SSH_OK)
1717 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1718 N_("CloudTunnel: Failed to set libssh log callback"));
1719 rc = ssh_set_log_userdata(pThis);
1720 if (rc != SSH_OK)
1721 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1722 N_("CloudTunnel: Failed to set libssh log userdata"));
1723
1724 rc = drvCloudTunnelSwitchToSecondary(pThis);
1725 if (RT_SUCCESS(rc))
1726 rc = establishTunnel(pThis);
1727
1728 return rc;
1729}
1730
1731
1732#if 0
1733/**
1734 * Suspend notification.
1735 *
1736 * @param pDrvIns The driver instance.
1737 */
1738static DECLCALLBACK(void) drvCloudTunnelSuspend(PPDMDRVINS pDrvIns)
1739{
1740 LogFlowFunc(("\n"));
1741 PDRVCLOUDTUNNEL pThis = PDMINS_2_DATA(pDrvIns, PDRVCLOUDTUNNEL);
1742
1743 RT_NOREF(pThis);
1744 // if (pThis->pServer)
1745 // {
1746 // RTUdpServerDestroy(pThis->pServer);
1747 // pThis->pServer = NULL;
1748 // }
1749}
1750
1751
1752/**
1753 * Resume notification.
1754 *
1755 * @param pDrvIns The driver instance.
1756 */
1757static DECLCALLBACK(void) drvCloudTunnelResume(PPDMDRVINS pDrvIns)
1758{
1759 LogFlowFunc(("\n"));
1760 PDRVCLOUDTUNNEL pThis = PDMINS_2_DATA(pDrvIns, PDRVCLOUDTUNNEL);
1761
1762 int rc = RTUdpServerCreate("", pThis->uSrcPort, RTTHREADTYPE_IO, pThis->pszInstance,
1763 drvCloudTunnelReceive, pDrvIns, &pThis->pServer);
1764 if (RT_FAILURE(rc))
1765 PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1766 N_("CloudTunnel: Failed to start the Cloud tunnel server"));
1767
1768}
1769#endif
1770
1771/**
1772 * Cloud tunnel network transport driver registration record.
1773 */
1774const PDMDRVREG g_DrvCloudTunnel =
1775{
1776 /* u32Version */
1777 PDM_DRVREG_VERSION,
1778 /* szName */
1779 "CloudTunnel",
1780 /* szRCMod */
1781 "",
1782 /* szR0Mod */
1783 "",
1784 /* pszDescription */
1785 "Cloud Tunnel Network Transport Driver",
1786 /* fFlags */
1787 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
1788 /* fClass. */
1789 PDM_DRVREG_CLASS_NETWORK,
1790 /* cMaxInstances */
1791 ~0U,
1792 /* cbInstance */
1793 sizeof(DRVCLOUDTUNNEL),
1794 /* pfnConstruct */
1795 drvCloudTunnelConstruct,
1796 /* pfnDestruct */
1797 drvCloudTunnelDestruct,
1798 /* pfnRelocate */
1799 NULL,
1800 /* pfnIOCtl */
1801 NULL,
1802 /* pfnPowerOn */
1803 NULL,
1804 /* pfnReset */
1805 NULL,
1806 /* pfnSuspend */
1807 NULL, // drvCloudTunnelSuspend,
1808 /* pfnResume */
1809 NULL, // drvCloudTunnelResume,
1810 /* pfnAttach */
1811 NULL,
1812 /* pfnDetach */
1813 NULL,
1814 /* pfnPowerOff */
1815 NULL,
1816 /* pfnSoftReset */
1817 NULL,
1818 /* u32EndVersion */
1819 PDM_DRVREG_VERSION
1820};
1821
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