VirtualBox

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

Last change on this file since 101634 was 101634, checked in by vboxsync, 16 months ago

libssh: removing 0.9.6 mention from Config.kmk and build fix. 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 101634 2023-10-27 15:27:36Z 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#ifdef WIN32
758static int channelWriteWontblockCallback(ssh_session, ssh_channel, unsigned int, 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*/,
822 (PFNRT)drvCloudTunnelReceiveWakeup, 1, pThis);
823 if (RT_FAILURE(rc))
824 LogRel(("%s: failed to wake up device thread - %Rrc\n", pThis->pszInstance, rc));
825 if (RT_SUCCESS(rc))
826 RTReqRelease(pReq);
827
828 return rc;
829}
830
831#define DRVCLOUDTUNNEL_COMMAND_BUFFER_SIZE 1024
832#define DRVCLOUDTUNNEL_OUTPUT_BUFFER_SIZE 65536
833
834static int drvCloudTunnelExecuteRemoteCommandNoOutput(PDRVCLOUDTUNNEL pThis, const char *pcszCommand, ...)
835{
836 va_list va;
837 va_start(va, pcszCommand);
838
839 size_t cb = RTStrPrintfV(pThis->pszCommandBuffer, DRVCLOUDTUNNEL_COMMAND_BUFFER_SIZE, pcszCommand, va);
840 if (cb == 0)
841 {
842 Log(("%s: Failed to process '%s'\n", pThis->pszInstance, pcszCommand));
843 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
844 N_("Failed to compose command line"));
845 }
846
847 LogFlow(("%s: [REMOTE] executing '%s'...\n", pThis->pszInstance, pThis->pszCommandBuffer));
848
849 ssh_channel channel = ssh_channel_new(pThis->pSshSession);
850 if (channel == NULL)
851 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
852 N_("Failed to allocate new channel"));
853
854 int rc = ssh_channel_open_session(channel);
855 if (rc != SSH_OK)
856 rc = PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
857 N_("Failed to open session channel"));
858 else
859 {
860 rc = ssh_channel_request_exec(channel, pThis->pszCommandBuffer);
861 if (rc != SSH_OK)
862 {
863 LogRel(("%s: Failed to execute '%s'\n", pThis->pszInstance, pThis->pszCommandBuffer));
864 Log(("%s: Failed to execute '%s'\n", pThis->pszInstance, pThis->pszCommandBuffer));
865 rc = PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
866 N_("Execute request failed with %d"), rc);
867 }
868 ssh_channel_close(channel);
869 }
870 ssh_channel_free(channel);
871
872 return VINF_SUCCESS;
873}
874
875
876static int drvCloudTunnelExecuteRemoteCommand(PDRVCLOUDTUNNEL pThis, const char *pcszCommand, ...)
877{
878 va_list va;
879 va_start(va, pcszCommand);
880
881 size_t cb = RTStrPrintfV(pThis->pszCommandBuffer, DRVCLOUDTUNNEL_COMMAND_BUFFER_SIZE, pcszCommand, va);
882 if (cb == 0)
883 {
884 Log(("%s: Failed to process '%s'\n", pThis->pszInstance, pcszCommand));
885 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
886 N_("Failed to compose command line"));
887 }
888
889 LogFlow(("%s: [REMOTE] executing '%s'...\n", pThis->pszInstance, pThis->pszCommandBuffer));
890
891 ssh_channel channel = ssh_channel_new(pThis->pSshSession);
892 if (channel == NULL)
893 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
894 N_("Failed to allocate new channel"));
895
896 int rc = ssh_channel_open_session(channel);
897 if (rc != SSH_OK)
898 rc = PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
899 N_("Failed to open session channel"));
900 else
901 {
902 rc = ssh_channel_request_exec(channel, pThis->pszCommandBuffer);
903 if (rc != SSH_OK)
904 {
905 LogRel(("%s: Failed to execute '%s'\n", pThis->pszInstance, pThis->pszCommandBuffer));
906 Log(("%s: Failed to execute '%s'\n", pThis->pszInstance, pThis->pszCommandBuffer));
907 rc = PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
908 N_("Execute request failed with %d"), rc);
909 }
910 else
911 {
912 int cbSpaceLeft = DRVCLOUDTUNNEL_OUTPUT_BUFFER_SIZE;
913 int cbStdOut = 0;
914 char *pszBuffer = pThis->pszOutputBuffer;
915 int cBytes = ssh_channel_read_timeout(channel, pszBuffer, cbSpaceLeft, 0, 60000 /* ms */); /* Is 60 seconds really enough? */
916 while (cBytes > 0)
917 {
918 cbStdOut += cBytes;
919 pszBuffer += cBytes;
920 cbSpaceLeft -= cBytes;
921 if (cbSpaceLeft <= 0)
922 break;
923 cBytes = ssh_channel_read_timeout(channel, pszBuffer, cbSpaceLeft, 0, 60000 /* ms */); /* Is 60 seconds really enough? */
924 }
925 if (cBytes < 0)
926 {
927 LogRel(("%s: while executing '%s' ssh_channel_read_timeout returned error\n", pThis->pszInstance, pThis->pszCommandBuffer));
928 Log(("%s: while executing '%s' ssh_channel_read_timeout returned error\n", pThis->pszInstance, pThis->pszCommandBuffer));
929 rc = VERR_INTERNAL_ERROR;
930 }
931 else
932 {
933 /* Make sure the buffer is terminated. */
934 if (cbStdOut < DRVCLOUDTUNNEL_OUTPUT_BUFFER_SIZE)
935 if (cbStdOut > 1 && pThis->pszOutputBuffer[cbStdOut - 1] == '\n')
936 pThis->pszOutputBuffer[cbStdOut - 1] = 0; /* Trim newline */
937 else
938 pThis->pszOutputBuffer[cbStdOut] = 0;
939 else
940 pThis->pszOutputBuffer[DRVCLOUDTUNNEL_OUTPUT_BUFFER_SIZE - 1] = 0; /* No choice but to eat up last character. Could have returned warning though. */
941 if (cbStdOut == 0)
942 Log(("%s: received no output from remote console\n", pThis->pszInstance));
943 else
944 Log(("%s: received output from remote console:\n%s\n", pThis->pszInstance, pThis->pszOutputBuffer));
945 rc = VINF_SUCCESS;
946
947 char *pszErrorBuffer = (char *)RTMemAlloc(DRVCLOUDTUNNEL_OUTPUT_BUFFER_SIZE);
948 if (pszErrorBuffer == NULL)
949 {
950 LogRel(("%s: Failed to allocate error buffer\n", pThis->pszInstance));
951 rc = VERR_INTERNAL_ERROR;
952 }
953 else
954 {
955 /* Report errors if there were any */
956 cBytes = ssh_channel_read_timeout(channel, pszErrorBuffer, DRVCLOUDTUNNEL_OUTPUT_BUFFER_SIZE, 1, 0); /* Peek at stderr */
957 if (cBytes > 0)
958 {
959 LogRel(("%s: WARNING! While executing '%s' remote console reported errors:\n", pThis->pszInstance, pThis->pszCommandBuffer));
960 Log(("%s: WARNING! While executing '%s' remote console reported errors:\n", pThis->pszInstance, pThis->pszCommandBuffer));
961 }
962 while (cBytes > 0)
963 {
964 LogRel(("%.*s", cBytes, pszErrorBuffer));
965 Log(("%.*s", cBytes, pszErrorBuffer));
966 cBytes = ssh_channel_read_timeout(channel, pszErrorBuffer, DRVCLOUDTUNNEL_OUTPUT_BUFFER_SIZE, 1, 1000); /* Wait for a second for more error output */
967 }
968 RTMemFree(pszErrorBuffer);
969 }
970 }
971 ssh_channel_send_eof(channel);
972 }
973 ssh_channel_close(channel);
974 }
975 ssh_channel_free(channel);
976
977 return VINF_SUCCESS;
978}
979
980
981static int drvCloudTunnelCloudInstanceInitialConfig(PDRVCLOUDTUNNEL pThis)
982{
983 LogFlow(("%s: configuring cloud instance...\n", pThis->pszInstance));
984
985 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])\"");
986 if (RT_FAILURE(rc))
987 rc = PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
988 N_("Failed to get network config via console channel"));
989 else
990 {
991 char *pszConfig = RTStrStr(pThis->pszOutputBuffer, "CONFIG: ");
992 if (!pszConfig)
993 rc = PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
994 N_("Failed to parse network config"));
995 else
996 {
997 char **ppapszTokens;
998 size_t cTokens;
999 rc = RTStrSplit(pszConfig + 8, DRVCLOUDTUNNEL_OUTPUT_BUFFER_SIZE - (pszConfig - pThis->pszOutputBuffer) - 8,
1000 " ", &ppapszTokens, &cTokens);
1001 if (RT_SUCCESS(rc))
1002 {
1003 /*
1004 * There should be exactly three tokens:
1005 * 1) Primary network interface name;
1006 * 2) Secondary network interface name;
1007 * 3) Secondary network gateway address.
1008 */
1009 if (cTokens != 3)
1010 Log(("%s: Got %u tokes instead of three while parsing '%s'\n", pThis->pszInstance, cTokens, pThis->pszOutputBuffer));
1011 else
1012 {
1013 char *pszSecondaryInterface = NULL;
1014 char *pszSecondaryGateway = NULL;
1015
1016 if (pThis->pszCloudPrimaryInterface)
1017 RTStrFree(pThis->pszCloudPrimaryInterface);
1018 pThis->pszCloudPrimaryInterface = RTStrDup(ppapszTokens[0]);
1019 pszSecondaryInterface = ppapszTokens[1];
1020 pszSecondaryGateway = ppapszTokens[2];
1021 Log(("%s: primary=%s secondary=%s gateway=%s\n", pThis->pszInstance, pThis->pszCloudPrimaryInterface, pszSecondaryInterface, pszSecondaryGateway));
1022
1023 rc = drvCloudTunnelExecuteRemoteCommand(pThis, "sudo oci-network-config -c");
1024 if (RT_SUCCESS(rc))
1025 rc = drvCloudTunnelExecuteRemoteCommand(pThis, "sudo ip tuntap add dev tap0 mod tap user opc");
1026 if (RT_SUCCESS(rc))
1027 rc = drvCloudTunnelExecuteRemoteCommand(pThis, "sudo sh -c 'echo \"PermitTunnel yes\" >> /etc/ssh/sshd_config'");
1028 if (RT_SUCCESS(rc))
1029 rc = drvCloudTunnelExecuteRemoteCommand(pThis, "sudo kill -SIGHUP $(pgrep -f \"sshd -D\")");
1030 if (RT_SUCCESS(rc))
1031 rc = drvCloudTunnelExecuteRemoteCommand(pThis, "sudo ip link add name br0 type bridge");
1032 if (RT_SUCCESS(rc))
1033 rc = drvCloudTunnelExecuteRemoteCommand(pThis, "sudo ip link set dev tap0 master br0");
1034 if (RT_SUCCESS(rc))
1035 rc = drvCloudTunnelExecuteRemoteCommandNoOutput(pThis, "sudo ip route change default via %s dev %s", pszSecondaryGateway, pszSecondaryInterface);
1036 if (RT_FAILURE(rc))
1037 rc = PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1038 N_("Failed to execute network config command via console channel"));
1039 }
1040
1041 for (size_t i = 0; i < cTokens; i++)
1042 RTStrFree(ppapszTokens[i]);
1043 RTMemFree(ppapszTokens);
1044 }
1045 }
1046 }
1047
1048 return rc;
1049}
1050
1051
1052static int drvCloudTunnelCloudInstanceFinalConfig(PDRVCLOUDTUNNEL pThis)
1053{
1054 if (pThis->pszCloudPrimaryInterface == NULL)
1055 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1056 N_("Failed to finalize cloud instance config because of unknown primary interface name!"));
1057
1058 LogFlow(("%s: finalizing cloud instance configuration...\n", pThis->pszInstance));
1059
1060 int rc = drvCloudTunnelExecuteRemoteCommand(pThis, "sudo ip link set dev %s down", pThis->pszCloudPrimaryInterface);
1061 if (RT_SUCCESS(rc))
1062 rc = drvCloudTunnelExecuteRemoteCommand(pThis, "sudo ip link set dev %s address %RTmac", pThis->pszCloudPrimaryInterface, pThis->targetMac.au8);
1063 if (RT_SUCCESS(rc))
1064 rc = drvCloudTunnelExecuteRemoteCommand(pThis, "sudo ifconfig %s 0.0.0.0", pThis->pszCloudPrimaryInterface); /* Make sure no IP is configured on primary */
1065 if (RT_SUCCESS(rc))
1066 rc = drvCloudTunnelExecuteRemoteCommand(pThis, "sudo ip link set dev %s master br0", pThis->pszCloudPrimaryInterface);
1067 if (RT_SUCCESS(rc))
1068 rc = drvCloudTunnelExecuteRemoteCommand(pThis, "sudo ip link set dev %s up", pThis->pszCloudPrimaryInterface);
1069 if (RT_SUCCESS(rc))
1070 rc = drvCloudTunnelExecuteRemoteCommand(pThis, "sudo ip link set dev tap0 up");
1071 if (RT_SUCCESS(rc))
1072 rc = drvCloudTunnelExecuteRemoteCommand(pThis, "sudo ip link set dev br0 up");
1073 if (RT_FAILURE(rc))
1074 rc = PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1075 N_("Failed to execute network config command via console channel"));
1076
1077 return rc;
1078}
1079
1080
1081static int drvCloudTunnelOpenTunnelChannel(PDRVCLOUDTUNNEL pThis)
1082{
1083 LogFlow(("%s: opening tunnel channel...\n", pThis->pszInstance));
1084 pThis->pSshChannel = ssh_channel_new(pThis->pSshSession);
1085 if (pThis->pSshChannel == NULL)
1086 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1087 N_("Failed to allocate new channel"));
1088 int rc = ssh_channel_open_tunnel(pThis->pSshChannel, 0);
1089 if (rc < 0)
1090 rc = PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1091 N_("Failed to open tunnel channel"));
1092 else
1093 {
1094 /* Set packet receive callback. */
1095 rc = ssh_set_channel_callbacks(pThis->pSshChannel, &pThis->Callbacks);
1096 if (rc != SSH_OK)
1097 rc = PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1098 N_("Failed to set packet receive callback"));
1099 }
1100
1101 return rc;
1102}
1103
1104
1105static void closeTunnelChannel(PDRVCLOUDTUNNEL pThis)
1106{
1107 if (pThis->pSshChannel)
1108 {
1109 LogFlow(("%s: closing tunnel channel %p\n", pThis->pszInstance, pThis->pSshChannel));
1110 ssh_channel_close(pThis->pSshChannel);
1111 ssh_channel_free(pThis->pSshChannel);
1112 pThis->pSshChannel = NULL;
1113 }
1114}
1115
1116
1117static int drvCloudTunnelStartIoThread(PDRVCLOUDTUNNEL pThis)
1118{
1119 LogFlow(("%s: starting I/O thread...\n", pThis->pszInstance));
1120 int rc = createConnectedSockets(pThis);
1121 if (RT_FAILURE(rc))
1122 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1123 N_("CloudTunnel: Failed to create a pair of connected sockets"));
1124
1125 /*
1126 * Start the cloud I/O thread.
1127 */
1128 rc = PDMDrvHlpThreadCreate(pThis->pDrvIns, &pThis->pIoThread,
1129 pThis, drvCloudTunnelIoThread, drvCloudTunnelIoWakeup,
1130 64 * _1K, RTTHREADTYPE_IO, pThis->pszInstanceIo);
1131 if (RT_FAILURE(rc))
1132 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1133 N_("CloudTunnel: Failed to start I/O thread"));
1134
1135 return rc;
1136}
1137
1138static void drvCloudTunnelStopIoThread(PDRVCLOUDTUNNEL pThis)
1139{
1140 if (pThis->pIoThread)
1141 {
1142 LogFlow(("%s: stopping I/O thread...\n", pThis->pszInstance));
1143 int rc = PDMDrvHlpThreadDestroy(pThis->pDrvIns, pThis->pIoThread, NULL);
1144 AssertRC(rc);
1145 pThis->pIoThread = NULL;
1146 }
1147 destroyConnectedSockets(pThis);
1148
1149}
1150
1151static int destroyTunnel(PDRVCLOUDTUNNEL pThis)
1152{
1153 if (pThis->pSshChannel)
1154 {
1155 int rc = ssh_remove_channel_callbacks(pThis->pSshChannel, &pThis->Callbacks);
1156 if (rc != SSH_OK)
1157 LogRel(("%s: WARNING! Failed to remove tunnel channel callbacks.\n", pThis->pszInstance));
1158 }
1159 drvCloudTunnelStopIoThread(pThis);
1160 closeTunnelChannel(pThis);
1161 ssh_disconnect(pThis->pSshSession);
1162 ssh_free(pThis->pSshSession);
1163 pThis->pSshSession = NULL;
1164 return VINF_SUCCESS;
1165}
1166
1167
1168static int drvCloudTunnelNewSession(PDRVCLOUDTUNNEL pThis, bool fPrimary)
1169{
1170 pThis->pSshSession = ssh_new();
1171 if (pThis->pSshSession == NULL)
1172 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1173 N_("CloudTunnel: Failed to allocate new SSH session"));
1174 if (ssh_options_set(pThis->pSshSession, SSH_OPTIONS_LOG_VERBOSITY, &pThis->iSshVerbosity) < 0)
1175 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1176 N_("Failed to set SSH_OPTIONS_LOG_VERBOSITY"));
1177 if (ssh_options_set(pThis->pSshSession, SSH_OPTIONS_USER, pThis->pszUser) < 0)
1178 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1179 N_("Failed to set SSH_OPTIONS_USER"));
1180 if (ssh_options_set(pThis->pSshSession, SSH_OPTIONS_HOST, fPrimary ? pThis->pszPrimaryIP : pThis->pszSecondaryIP) < 0)
1181 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1182 N_("Failed to set SSH_OPTIONS_HOST"));
1183
1184 if (ssh_options_set(pThis->pSshSession, SSH_OPTIONS_TIMEOUT, &pThis->ulTimeoutInSecounds) < 0)
1185 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1186 N_("Failed to set SSH_OPTIONS_TIMEOUT"));
1187
1188 const char *pcszProxyType = fPrimary ? pThis->pszPrimaryProxyType : pThis->pszSecondaryProxyType;
1189 if (pcszProxyType)
1190 {
1191 char szProxyCmd[1024];
1192
1193 const char *pcszProxyUser = fPrimary ? pThis->pszPrimaryProxyUser : pThis->pszSecondaryProxyUser;
1194 if (pcszProxyUser)
1195 RTStrPrintf(szProxyCmd, sizeof(szProxyCmd), "#VBoxProxy%s %s %u %s %s",
1196 fPrimary ? pThis->pszPrimaryProxyType : pThis->pszSecondaryProxyType,
1197 fPrimary ? pThis->pszPrimaryProxyHost : pThis->pszSecondaryProxyHost,
1198 fPrimary ? pThis->u16PrimaryProxyPort : pThis->u16SecondaryProxyPort,
1199 fPrimary ? pThis->pszPrimaryProxyUser : pThis->pszSecondaryProxyUser,
1200 fPrimary ? pThis->pszPrimaryProxyPassword : pThis->pszSecondaryProxyPassword);
1201 else
1202 RTStrPrintf(szProxyCmd, sizeof(szProxyCmd), "#VBoxProxy%s %s %u",
1203 fPrimary ? pThis->pszPrimaryProxyType : pThis->pszSecondaryProxyType,
1204 fPrimary ? pThis->pszPrimaryProxyHost : pThis->pszSecondaryProxyHost,
1205 fPrimary ? pThis->u16PrimaryProxyPort : pThis->u16SecondaryProxyPort);
1206 LogRel(("%s: using proxy command '%s'\n", pThis->pszInstance, szProxyCmd));
1207 if (ssh_options_set(pThis->pSshSession, SSH_OPTIONS_PROXYCOMMAND, szProxyCmd) < 0)
1208 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1209 N_("Failed to set SSH_OPTIONS_PROXYCOMMAND"));
1210 }
1211
1212 int rc = ssh_connect(pThis->pSshSession);
1213 for (int cAttempt = 1; rc != SSH_OK && cAttempt <= 5; cAttempt++)
1214 {
1215 ssh_disconnect(pThis->pSshSession);
1216 /* One more time, just to be sure. */
1217 LogRel(("%s: failed to connect to %s, retrying(#%d)...\n", pThis->pszInstance,
1218 fPrimary ? pThis->pszPrimaryIP : pThis->pszSecondaryIP, cAttempt));
1219 RTThreadSleep(10000); /* Sleep 10 seconds, then retry */
1220 rc = ssh_connect(pThis->pSshSession);
1221 }
1222 if (rc != SSH_OK)
1223 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1224 N_("CloudTunnel: Failed to connect to %s interface"), fPrimary ? "primary" : "secondary");
1225
1226 rc = ssh_userauth_publickey(pThis->pSshSession, NULL, pThis->SshKey);
1227 if (rc != SSH_AUTH_SUCCESS)
1228 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1229 N_("Failed to authenticate with public key"));
1230
1231 return VINF_SUCCESS;
1232}
1233
1234static int drvCloudTunnelSwitchToSecondary(PDRVCLOUDTUNNEL pThis)
1235{
1236 int rc = drvCloudTunnelNewSession(pThis, true /* fPrimary */);
1237 /*
1238 * Establish temporary console channel and configure the cloud instance
1239 * to bridge the tunnel channel to instance's primary interface.
1240 */
1241 if (RT_SUCCESS(rc))
1242 rc = drvCloudTunnelCloudInstanceInitialConfig(pThis);
1243
1244 ssh_disconnect(pThis->pSshSession);
1245 ssh_free(pThis->pSshSession);
1246 pThis->pSshSession = NULL;
1247
1248 return rc;
1249}
1250
1251
1252static int establishTunnel(PDRVCLOUDTUNNEL pThis)
1253{
1254 int rc = drvCloudTunnelNewSession(pThis, false /* fPrimary */);
1255 if (RT_SUCCESS(rc))
1256 rc = drvCloudTunnelCloudInstanceFinalConfig(pThis);
1257 if (RT_SUCCESS(rc))
1258 rc = drvCloudTunnelOpenTunnelChannel(pThis);
1259 if (RT_SUCCESS(rc))
1260 rc = drvCloudTunnelStartIoThread(pThis);
1261 if (RT_FAILURE(rc))
1262 {
1263 destroyTunnel(pThis);
1264 return rc;
1265 }
1266
1267 return rc;
1268}
1269
1270
1271static DECL_NOTHROW(void) drvCloudTunnelSshLogCallback(int priority, const char *function, const char *buffer, void *userdata)
1272{
1273 PDRVCLOUDTUNNEL pThis = (PDRVCLOUDTUNNEL)userdata;
1274#ifdef LOG_ENABLED
1275 const char *pcszVerbosity;
1276 switch (priority)
1277 {
1278 case SSH_LOG_WARNING:
1279 pcszVerbosity = "WARNING";
1280 break;
1281 case SSH_LOG_PROTOCOL:
1282 pcszVerbosity = "PROTOCOL";
1283 break;
1284 case SSH_LOG_PACKET:
1285 pcszVerbosity = "PACKET";
1286 break;
1287 case SSH_LOG_FUNCTIONS:
1288 pcszVerbosity = "FUNCTIONS";
1289 break;
1290 default:
1291 pcszVerbosity = "UNKNOWN";
1292 break;
1293 }
1294 Log3(("%s: SSH-%s: %s: %s\n", pThis->pszInstance, pcszVerbosity, function, buffer));
1295#else
1296 RT_NOREF(priority);
1297 LogRel(("%s: SSH %s: %s\n", pThis->pszInstance, function, buffer));
1298#endif
1299}
1300
1301/* -=-=-=-=- PDMDRVREG -=-=-=-=- */
1302
1303DECLINLINE(void) drvCloudTunnelStrFree(char **ppszString)
1304{
1305 if (*ppszString)
1306 {
1307 RTStrFree(*ppszString);
1308 *ppszString = NULL;
1309 }
1310}
1311
1312DECLINLINE(void) drvCloudTunnelHeapFree(PPDMDRVINS pDrvIns, char **ppszString)
1313{
1314 if (*ppszString)
1315 {
1316 PDMDrvHlpMMHeapFree(pDrvIns, *ppszString);
1317 *ppszString = NULL;
1318 }
1319}
1320
1321/**
1322 * Destruct a driver instance.
1323 *
1324 * Most VM resources are freed by the VM. This callback is provided so that any non-VM
1325 * resources can be freed correctly.
1326 *
1327 * @param pDrvIns The driver instance data.
1328 */
1329static DECLCALLBACK(void) drvCloudTunnelDestruct(PPDMDRVINS pDrvIns)
1330{
1331 LogFlowFunc(("\n"));
1332 PDRVCLOUDTUNNEL pThis = PDMINS_2_DATA(pDrvIns, PDRVCLOUDTUNNEL);
1333 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
1334
1335 ASMAtomicXchgSize(&pThis->fLinkDown, true);
1336
1337 destroyTunnel(pThis);
1338
1339 if (pThis->hIoReqQueue != NIL_RTREQQUEUE)
1340 {
1341 RTReqQueueDestroy(pThis->hIoReqQueue);
1342 pThis->hIoReqQueue = NIL_RTREQQUEUE;
1343 }
1344
1345 drvCloudTunnelStrFree(&pThis->pszCloudPrimaryInterface);
1346
1347 drvCloudTunnelHeapFree(pDrvIns, &pThis->pszPrimaryProxyType);
1348 drvCloudTunnelStrFree(&pThis->pszPrimaryProxyHost);
1349 drvCloudTunnelHeapFree(pDrvIns, &pThis->pszPrimaryProxyUser);
1350 drvCloudTunnelStrFree(&pThis->pszPrimaryProxyPassword);
1351
1352 drvCloudTunnelHeapFree(pDrvIns, &pThis->pszSecondaryProxyType);
1353 drvCloudTunnelStrFree(&pThis->pszSecondaryProxyHost);
1354 drvCloudTunnelHeapFree(pDrvIns, &pThis->pszSecondaryProxyUser);
1355 drvCloudTunnelStrFree(&pThis->pszSecondaryProxyPassword);
1356
1357 drvCloudTunnelStrFree(&pThis->pszSecondaryIP);
1358 drvCloudTunnelStrFree(&pThis->pszPrimaryIP);
1359 drvCloudTunnelStrFree(&pThis->pszUser);
1360
1361 drvCloudTunnelStrFree(&pThis->pszInstanceDev);
1362 drvCloudTunnelStrFree(&pThis->pszInstanceIo);
1363 drvCloudTunnelStrFree(&pThis->pszInstance);
1364
1365 drvCloudTunnelStrFree(&pThis->pszOutputBuffer);
1366 drvCloudTunnelStrFree(&pThis->pszCommandBuffer);
1367
1368 ssh_key_free(pThis->SshKey);
1369
1370 ssh_finalize();
1371 //OPENSSL_cleanup();
1372
1373 // if (pThis->pServer)
1374 // {
1375 // RTUdpServerDestroy(pThis->pServer);
1376 // pThis->pServer = NULL;
1377 // }
1378
1379 /*
1380 * Kill the xmit lock.
1381 */
1382 if (RTCritSectIsInitialized(&pThis->XmitLock))
1383 RTCritSectDelete(&pThis->XmitLock);
1384
1385#ifdef VBOX_WITH_STATISTICS
1386 /*
1387 * Deregister statistics.
1388 */
1389 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatPktSent);
1390 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatPktSentBytes);
1391 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatPktRecv);
1392 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatPktRecvBytes);
1393 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatTransmit);
1394 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatReceive);
1395 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatDevRecv);
1396 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatDevRecvWait);
1397#endif /* VBOX_WITH_STATISTICS */
1398}
1399
1400
1401/**
1402 * Construct a Cloud tunnel network transport driver instance.
1403 *
1404 * @copydoc FNPDMDRVCONSTRUCT
1405 */
1406static DECLCALLBACK(int) drvCloudTunnelConstruct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t fFlags)
1407{
1408 RT_NOREF(fFlags);
1409 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
1410 PDRVCLOUDTUNNEL pThis = PDMINS_2_DATA(pDrvIns, PDRVCLOUDTUNNEL);
1411 PCPDMDRVHLPR3 pHlp = pDrvIns->pHlpR3;
1412
1413 /*
1414 * Init the static parts.
1415 */
1416 pThis->pDrvIns = pDrvIns;
1417 pThis->pszCommandBuffer = NULL;
1418 pThis->pszOutputBuffer = NULL;
1419 pThis->pszInstance = NULL;
1420 pThis->pszPrimaryIP = NULL;
1421 pThis->pszSecondaryIP = NULL;
1422 pThis->pszUser = NULL;
1423 pThis->SshKey = 0;
1424
1425 /* IBase */
1426 pDrvIns->IBase.pfnQueryInterface = drvCloudTunnelQueryInterface;
1427 /* INetwork */
1428 pThis->INetworkUp.pfnBeginXmit = drvCloudTunnelUp_BeginXmit;
1429 pThis->INetworkUp.pfnAllocBuf = drvCloudTunnelUp_AllocBuf;
1430 pThis->INetworkUp.pfnFreeBuf = drvCloudTunnelUp_FreeBuf;
1431 pThis->INetworkUp.pfnSendBuf = drvCloudTunnelUp_SendBuf;
1432 pThis->INetworkUp.pfnEndXmit = drvCloudTunnelUp_EndXmit;
1433 pThis->INetworkUp.pfnSetPromiscuousMode = drvCloudTunnelUp_SetPromiscuousMode;
1434 pThis->INetworkUp.pfnNotifyLinkChanged = drvCloudTunnelUp_NotifyLinkChanged;
1435
1436 /* ??? */
1437 pThis->iSocketIn = INVALID_SOCKET;
1438 pThis->iSocketOut = INVALID_SOCKET;
1439 pThis->pSshSession = 0;
1440 pThis->pSshChannel = 0;
1441
1442 pThis->pDevThread = 0;
1443 pThis->pIoThread = 0;
1444 pThis->hIoReqQueue = NIL_RTREQQUEUE;
1445
1446 pThis->fLinkDown = false;
1447
1448 pThis->pszCloudPrimaryInterface = NULL;
1449
1450#ifdef VBOX_WITH_STATISTICS
1451 /*
1452 * Statistics.
1453 */
1454 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatPktSent, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of sent packets.", "/Drivers/CloudTunnel%d/Packets/Sent", pDrvIns->iInstance);
1455 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatPktSentBytes, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_BYTES, "Number of sent bytes.", "/Drivers/CloudTunnel%d/Bytes/Sent", pDrvIns->iInstance);
1456 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatPktRecv, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of received packets.", "/Drivers/CloudTunnel%d/Packets/Received", pDrvIns->iInstance);
1457 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatPktRecvBytes, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_BYTES, "Number of received bytes.", "/Drivers/CloudTunnel%d/Bytes/Received", pDrvIns->iInstance);
1458 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatTransmit, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS, STAMUNIT_TICKS_PER_CALL, "Profiling packet transmit runs.", "/Drivers/CloudTunnel%d/Transmit", pDrvIns->iInstance);
1459 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatReceive, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS, STAMUNIT_TICKS_PER_CALL, "Profiling packet receive runs.", "/Drivers/CloudTunnel%d/Receive", pDrvIns->iInstance);
1460 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatDevRecv, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS, STAMUNIT_TICKS_PER_CALL, "Profiling device receive runs.", "/Drivers/CloudTunnel%d/DeviceReceive", pDrvIns->iInstance);
1461 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatDevRecvWait, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS, STAMUNIT_TICKS_PER_CALL, "Profiling device receive waits.", "/Drivers/CloudTunnel%d/DeviceReceiveWait", pDrvIns->iInstance);
1462#endif /* VBOX_WITH_STATISTICS */
1463
1464 /*
1465 * Validate the config.
1466 */
1467 PDMDRV_VALIDATE_CONFIG_RETURN(pDrvIns, "SshKey"
1468 "|PrimaryIP"
1469 "|SecondaryIP"
1470 "|TargetMAC"
1471
1472 "|PrimaryProxyType"
1473 "|PrimaryProxyHost"
1474 "|PrimaryProxyPort"
1475 "|PrimaryProxyUser"
1476 "|PrimaryProxyPassword"
1477 "|SecondaryProxyType"
1478 "|SecondaryProxyHost"
1479 "|SecondaryProxyPort"
1480 "|SecondaryProxyUser"
1481 "|SecondaryProxyPassword"
1482
1483 ,"");
1484
1485 /*
1486 * Check that no-one is attached to us.
1487 */
1488 AssertMsgReturn(PDMDrvHlpNoAttach(pDrvIns) == VERR_PDM_NO_ATTACHED_DRIVER,
1489 ("Configuration error: Not possible to attach anything to this driver!\n"),
1490 VERR_PDM_DRVINS_NO_ATTACH);
1491
1492 /*
1493 * Query the network port interface.
1494 */
1495 pThis->pIAboveNet = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMINETWORKDOWN);
1496 if (!pThis->pIAboveNet)
1497 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_MISSING_INTERFACE_ABOVE,
1498 N_("Configuration error: The above device/driver didn't export the network port interface"));
1499
1500 /*
1501 * Read the configuration.
1502 */
1503 int rc;
1504
1505 char szVal[2048];
1506 RTNETADDRIPV4 tmpAddr;
1507 rc = pHlp->pfnCFGMQueryString(pCfg, "PrimaryIP", szVal, sizeof(szVal));
1508 if (RT_FAILURE(rc))
1509 return PDMDRV_SET_ERROR(pDrvIns, rc,
1510 N_("DrvCloudTunnel: Configuration error: Querying \"PrimaryIP\" as string failed"));
1511 rc = RTNetStrToIPv4Addr(szVal, &tmpAddr);
1512 if (RT_FAILURE(rc))
1513 return PDMDRV_SET_ERROR(pDrvIns, rc,
1514 N_("DrvCloudTunnel: Configuration error: \"PrimaryIP\" is not valid"));
1515 else
1516 pThis->pszPrimaryIP = RTStrDup(szVal);
1517
1518 rc = pHlp->pfnCFGMQueryString(pCfg, "SecondaryIP", szVal, sizeof(szVal));
1519 if (RT_FAILURE(rc))
1520 return PDMDRV_SET_ERROR(pDrvIns, rc,
1521 N_("DrvCloudTunnel: Configuration error: Querying \"SecondaryIP\" as string failed"));
1522 rc = RTNetStrToIPv4Addr(szVal, &tmpAddr);
1523 if (RT_FAILURE(rc))
1524 return PDMDRV_SET_ERROR(pDrvIns, rc,
1525 N_("DrvCloudTunnel: Configuration error: \"SecondaryIP\" is not valid"));
1526 else
1527 pThis->pszSecondaryIP = RTStrDup(szVal);
1528 rc = pHlp->pfnCFGMQueryBytes(pCfg, "TargetMAC", pThis->targetMac.au8, sizeof(pThis->targetMac.au8));
1529 if (RT_FAILURE(rc))
1530 return PDMDRV_SET_ERROR(pDrvIns, rc,
1531 N_("DrvCloudTunnel: Configuration error: Failed to get target MAC address"));
1532 /** @todo In the near future we will want to include proxy settings here! */
1533 // Do we want to pass the user name via CFGM?
1534 pThis->pszUser = RTStrDup("opc");
1535 // Is it safe to expose verbosity via CFGM?
1536#ifdef LOG_ENABLED
1537 pThis->iSshVerbosity = SSH_LOG_PACKET; //SSH_LOG_FUNCTIONS;
1538#else
1539 pThis->iSshVerbosity = SSH_LOG_WARNING;
1540#endif
1541
1542 pThis->ulTimeoutInSecounds = 30; /* The default 10-second timeout is too short? */
1543
1544 rc = pHlp->pfnCFGMQueryPassword(pCfg, "SshKey", szVal, sizeof(szVal));
1545 if (RT_FAILURE(rc))
1546 return PDMDRV_SET_ERROR(pDrvIns, rc,
1547 N_("DrvCloudTunnel: Configuration error: Querying \"SshKey\" as password failed"));
1548 rc = ssh_pki_import_privkey_base64(szVal, NULL, NULL, NULL, &pThis->SshKey);
1549 RTMemWipeThoroughly(szVal, sizeof(szVal), 10);
1550 if (rc != SSH_OK)
1551 return PDMDRV_SET_ERROR(pDrvIns, VERR_INVALID_BASE64_ENCODING,
1552 N_("DrvCloudTunnel: Configuration error: Converting \"SshKey\" from base64 failed"));
1553
1554 /* PrimaryProxyType is optional */
1555 rc = pHlp->pfnCFGMQueryStringAllocDef(pCfg, "PrimaryProxyType", &pThis->pszPrimaryProxyType, NULL);
1556 if (RT_FAILURE(rc))
1557 return PDMDRV_SET_ERROR(pDrvIns, rc,
1558 N_("DrvCloudTunnel: Configuration error: Querying \"PrimaryProxyType\" as string failed"));
1559 if (pThis->pszPrimaryProxyType)
1560 {
1561 rc = pHlp->pfnCFGMQueryString(pCfg, "PrimaryProxyHost", szVal, sizeof(szVal));
1562 if (RT_FAILURE(rc))
1563 return PDMDRV_SET_ERROR(pDrvIns, rc,
1564 N_("DrvCloudTunnel: Configuration error: Querying \"PrimaryProxyHost\" as string failed"));
1565 rc = RTNetStrToIPv4Addr(szVal, &tmpAddr);
1566 if (RT_FAILURE(rc))
1567 return PDMDRV_SET_ERROR(pDrvIns, rc,
1568 N_("DrvCloudTunnel: Configuration error: \"PrimaryProxyHost\" is not valid"));
1569 else
1570 pThis->pszPrimaryProxyHost = RTStrDup(szVal);
1571
1572 uint64_t u64Val;
1573 rc = pHlp->pfnCFGMQueryInteger(pCfg, "PrimaryProxyPort", &u64Val);
1574 if (RT_FAILURE(rc))
1575 return PDMDRV_SET_ERROR(pDrvIns, rc,
1576 N_("DrvCloudTunnel: Configuration error: Querying \"PrimaryProxyPort\" as integer failed"));
1577 if (u64Val > 0xFFFF)
1578 return PDMDRV_SET_ERROR(pDrvIns, rc,
1579 N_("DrvCloudTunnel: Configuration error: \"PrimaryProxyPort\" is not valid"));
1580 pThis->u16PrimaryProxyPort = (uint16_t)u64Val;
1581
1582 /* PrimaryProxyUser is optional */
1583 rc = pHlp->pfnCFGMQueryStringAllocDef(pCfg, "PrimaryProxyUser", &pThis->pszPrimaryProxyUser, NULL);
1584 if (RT_FAILURE(rc))
1585 return PDMDRV_SET_ERROR(pDrvIns, rc,
1586 N_("DrvCloudTunnel: Configuration error: Querying \"PrimaryProxyUser\" as string failed"));
1587 /* PrimaryProxyPassword must be present if PrimaryProxyUser is present */
1588 if (pThis->pszPrimaryProxyUser)
1589 {
1590 rc = pHlp->pfnCFGMQueryPassword(pCfg, "PrimaryProxyPassword", szVal, sizeof(szVal));
1591 if (RT_FAILURE(rc))
1592 return PDMDRV_SET_ERROR(pDrvIns, rc,
1593 N_("DrvCloudTunnel: Configuration error: Querying \"PrimaryProxyPassword\" as string failed"));
1594 pThis->pszPrimaryProxyPassword = RTStrDup(szVal);
1595 }
1596 }
1597
1598 /* SecondaryProxyType is optional */
1599 rc = pHlp->pfnCFGMQueryStringAllocDef(pCfg, "SecondaryProxyType", &pThis->pszSecondaryProxyType, NULL);
1600 if (RT_FAILURE(rc))
1601 return PDMDRV_SET_ERROR(pDrvIns, rc,
1602 N_("DrvCloudTunnel: Configuration error: Querying \"SecondaryProxyType\" as string failed"));
1603 if (pThis->pszSecondaryProxyType)
1604 {
1605 if (RT_FAILURE(rc))
1606 return PDMDRV_SET_ERROR(pDrvIns, rc,
1607 N_("DrvCloudTunnel: Configuration error: Querying \"SecondaryProxyType\" as string failed"));
1608
1609 rc = pHlp->pfnCFGMQueryString(pCfg, "SecondaryProxyHost", szVal, sizeof(szVal));
1610 if (RT_FAILURE(rc))
1611 return PDMDRV_SET_ERROR(pDrvIns, rc,
1612 N_("DrvCloudTunnel: Configuration error: Querying \"SecondaryProxyHost\" as string failed"));
1613 rc = RTNetStrToIPv4Addr(szVal, &tmpAddr);
1614 if (RT_FAILURE(rc))
1615 return PDMDRV_SET_ERROR(pDrvIns, rc,
1616 N_("DrvCloudTunnel: Configuration error: \"SecondaryProxyHost\" is not valid"));
1617 else
1618 pThis->pszSecondaryProxyHost = RTStrDup(szVal);
1619
1620 uint64_t u64Val;
1621 rc = pHlp->pfnCFGMQueryInteger(pCfg, "SecondaryProxyPort", &u64Val);
1622 if (RT_FAILURE(rc))
1623 return PDMDRV_SET_ERROR(pDrvIns, rc,
1624 N_("DrvCloudTunnel: Configuration error: Querying \"SecondaryProxyPort\" as integer failed"));
1625 if (u64Val > 0xFFFF)
1626 return PDMDRV_SET_ERROR(pDrvIns, rc,
1627 N_("DrvCloudTunnel: Configuration error: \"SecondaryProxyPort\" is not valid"));
1628 pThis->u16SecondaryProxyPort = (uint16_t)u64Val;
1629
1630 /* SecondaryProxyUser is optional */
1631 rc = pHlp->pfnCFGMQueryStringAllocDef(pCfg, "SecondaryProxyUser", &pThis->pszSecondaryProxyUser, NULL);
1632 if (RT_FAILURE(rc))
1633 return PDMDRV_SET_ERROR(pDrvIns, rc,
1634 N_("DrvCloudTunnel: Configuration error: Querying \"SecondaryProxyUser\" as string failed"));
1635 /* SecondaryProxyPassword must be present if SecondaryProxyUser is present */
1636 if (pThis->pszSecondaryProxyUser)
1637 {
1638 rc = pHlp->pfnCFGMQueryPassword(pCfg, "SecondaryProxyPassword", szVal, sizeof(szVal));
1639 if (RT_FAILURE(rc))
1640 return PDMDRV_SET_ERROR(pDrvIns, rc,
1641 N_("DrvCloudTunnel: Configuration error: Querying \"SecondaryProxyPassword\" as string failed"));
1642 pThis->pszSecondaryProxyPassword = RTStrDup(szVal);
1643 }
1644 }
1645
1646 pThis->pszCommandBuffer = (char *)RTMemAlloc(DRVCLOUDTUNNEL_COMMAND_BUFFER_SIZE);
1647 if (pThis->pszCommandBuffer == NULL)
1648 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_HIF_OPEN_FAILED,
1649 N_("DrvCloudTunnel: Failed to allocate command buffer"));
1650 pThis->pszOutputBuffer = (char *)RTMemAlloc(DRVCLOUDTUNNEL_OUTPUT_BUFFER_SIZE);
1651 if (pThis->pszOutputBuffer == NULL)
1652 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_HIF_OPEN_FAILED,
1653 N_("DrvCloudTunnel: Failed to allocate output buffer"));
1654 /*
1655 * Create unique instance name for logging.
1656 */
1657 rc = RTStrAPrintf(&pThis->pszInstance, "CT#%d", pDrvIns->iInstance);
1658 AssertRC(rc);
1659
1660 LogRel(("%s: primary=%s secondary=%s target-mac=%RTmac\n", pThis->pszInstance, pThis->pszPrimaryIP, pThis->pszSecondaryIP, pThis->targetMac.au8));
1661
1662 /*
1663 * Create unique thread name for cloud I/O.
1664 */
1665 rc = RTStrAPrintf(&pThis->pszInstanceIo, "CTunIO%d", pDrvIns->iInstance);
1666 AssertRC(rc);
1667
1668 /*
1669 * Create unique thread name for device receive function.
1670 */
1671 rc = RTStrAPrintf(&pThis->pszInstanceDev, "CTunDev%d", pDrvIns->iInstance);
1672 AssertRC(rc);
1673
1674 /*
1675 * Create the transmit lock.
1676 */
1677 rc = RTCritSectInit(&pThis->XmitLock);
1678 AssertRCReturn(rc, rc);
1679
1680 /*
1681 * Create the request queue for I/O requests.
1682 */
1683 rc = RTReqQueueCreate(&pThis->hIoReqQueue);
1684 AssertLogRelRCReturn(rc, rc);
1685
1686 /*
1687 * Create the request queue for attached device requests.
1688 */
1689 rc = RTReqQueueCreate(&pThis->hDevReqQueue);
1690 AssertLogRelRCReturn(rc, rc);
1691
1692 /*
1693 * Start the device output thread.
1694 */
1695 rc = PDMDrvHlpThreadCreate(pThis->pDrvIns, &pThis->pDevThread,
1696 pThis, drvCloudTunnelDevThread, drvCloudTunnelDevWakeup,
1697 64 * _1K, RTTHREADTYPE_IO, pThis->pszInstanceDev);
1698 if (RT_FAILURE(rc))
1699 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1700 N_("CloudTunnel: Failed to start device thread"));
1701
1702 rc = ssh_init();
1703 if (rc != SSH_OK)
1704 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1705 N_("CloudTunnel: Failed to initialize libssh"));
1706
1707 memset(&pThis->Callbacks, 0, sizeof(pThis->Callbacks));
1708#ifdef PACKET_CAPTURE_ENABLED
1709 pThis->Callbacks.channel_data_function = drvCloudTunnelReceiveCallbackWithPacketCapture;
1710#else
1711 pThis->Callbacks.channel_data_function = drvCloudTunnelReceiveCallback;
1712#endif
1713 pThis->Callbacks.userdata = pThis;
1714 pThis->Callbacks.channel_write_wontblock_function = channelWriteWontblockCallback;
1715 ssh_callbacks_init(&pThis->Callbacks);
1716
1717 rc = ssh_set_log_callback(drvCloudTunnelSshLogCallback);
1718 if (rc != SSH_OK)
1719 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1720 N_("CloudTunnel: Failed to set libssh log callback"));
1721 rc = ssh_set_log_userdata(pThis);
1722 if (rc != SSH_OK)
1723 return PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1724 N_("CloudTunnel: Failed to set libssh log userdata"));
1725
1726 rc = drvCloudTunnelSwitchToSecondary(pThis);
1727 if (RT_SUCCESS(rc))
1728 rc = establishTunnel(pThis);
1729
1730 return rc;
1731}
1732
1733
1734#if 0
1735/**
1736 * Suspend notification.
1737 *
1738 * @param pDrvIns The driver instance.
1739 */
1740static DECLCALLBACK(void) drvCloudTunnelSuspend(PPDMDRVINS pDrvIns)
1741{
1742 LogFlowFunc(("\n"));
1743 PDRVCLOUDTUNNEL pThis = PDMINS_2_DATA(pDrvIns, PDRVCLOUDTUNNEL);
1744
1745 RT_NOREF(pThis);
1746 // if (pThis->pServer)
1747 // {
1748 // RTUdpServerDestroy(pThis->pServer);
1749 // pThis->pServer = NULL;
1750 // }
1751}
1752
1753
1754/**
1755 * Resume notification.
1756 *
1757 * @param pDrvIns The driver instance.
1758 */
1759static DECLCALLBACK(void) drvCloudTunnelResume(PPDMDRVINS pDrvIns)
1760{
1761 LogFlowFunc(("\n"));
1762 PDRVCLOUDTUNNEL pThis = PDMINS_2_DATA(pDrvIns, PDRVCLOUDTUNNEL);
1763
1764 int rc = RTUdpServerCreate("", pThis->uSrcPort, RTTHREADTYPE_IO, pThis->pszInstance,
1765 drvCloudTunnelReceive, pDrvIns, &pThis->pServer);
1766 if (RT_FAILURE(rc))
1767 PDMDrvHlpVMSetError(pThis->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
1768 N_("CloudTunnel: Failed to start the Cloud tunnel server"));
1769
1770}
1771#endif
1772
1773/**
1774 * Cloud tunnel network transport driver registration record.
1775 */
1776const PDMDRVREG g_DrvCloudTunnel =
1777{
1778 /* u32Version */
1779 PDM_DRVREG_VERSION,
1780 /* szName */
1781 "CloudTunnel",
1782 /* szRCMod */
1783 "",
1784 /* szR0Mod */
1785 "",
1786 /* pszDescription */
1787 "Cloud Tunnel Network Transport Driver",
1788 /* fFlags */
1789 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
1790 /* fClass. */
1791 PDM_DRVREG_CLASS_NETWORK,
1792 /* cMaxInstances */
1793 ~0U,
1794 /* cbInstance */
1795 sizeof(DRVCLOUDTUNNEL),
1796 /* pfnConstruct */
1797 drvCloudTunnelConstruct,
1798 /* pfnDestruct */
1799 drvCloudTunnelDestruct,
1800 /* pfnRelocate */
1801 NULL,
1802 /* pfnIOCtl */
1803 NULL,
1804 /* pfnPowerOn */
1805 NULL,
1806 /* pfnReset */
1807 NULL,
1808 /* pfnSuspend */
1809 NULL, // drvCloudTunnelSuspend,
1810 /* pfnResume */
1811 NULL, // drvCloudTunnelResume,
1812 /* pfnAttach */
1813 NULL,
1814 /* pfnDetach */
1815 NULL,
1816 /* pfnPowerOff */
1817 NULL,
1818 /* pfnSoftReset */
1819 NULL,
1820 /* u32EndVersion */
1821 PDM_DRVREG_VERSION
1822};
1823
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