VirtualBox

source: vbox/trunk/src/VBox/Main/src-client/ConsoleImplTeleporter.cpp@ 94521

Last change on this file since 94521 was 93444, checked in by vboxsync, 2 years ago

VMM,Main,HostServices: Use a function table for accessing the VBoxVMM.dll/so/dylib functionality, and load it dynamically when the Console object is initialized. Also converted a few drivers in Main to use device helpers to get config values and such. bugref:10074

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 47.3 KB
Line 
1/* $Id: ConsoleImplTeleporter.cpp 93444 2022-01-26 18:01:15Z vboxsync $ */
2/** @file
3 * VBox Console COM Class implementation, The Teleporter Part.
4 */
5
6/*
7 * Copyright (C) 2010-2022 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/*********************************************************************************************************************************
20* Header Files *
21*********************************************************************************************************************************/
22#define LOG_GROUP LOG_GROUP_MAIN_CONSOLE
23#include "LoggingNew.h"
24
25#include "ConsoleImpl.h"
26#include "ProgressImpl.h"
27#include "Global.h"
28#include "StringifyEnums.h"
29
30#include "AutoCaller.h"
31#include "HashedPw.h"
32
33#include <iprt/asm.h>
34#include <iprt/err.h>
35#include <iprt/rand.h>
36#include <iprt/socket.h>
37#include <iprt/tcp.h>
38#include <iprt/timer.h>
39
40#include <VBox/vmm/vmapi.h>
41#include <VBox/vmm/ssm.h>
42#include <VBox/vmm/vmmr3vtable.h>
43#include <VBox/err.h>
44#include <VBox/version.h>
45#include <VBox/com/string.h>
46#include "VBox/com/ErrorInfo.h"
47
48
49/*********************************************************************************************************************************
50* Structures and Typedefs *
51*********************************************************************************************************************************/
52/**
53 * Base class for the teleporter state.
54 *
55 * These classes are used as advanced structs, not as proper classes.
56 */
57class TeleporterState
58{
59public:
60 ComPtr<Console> mptrConsole;
61 PUVM mpUVM;
62 PCVMMR3VTABLE mpVMM;
63 ComObjPtr<Progress> mptrProgress;
64 Utf8Str mstrPassword;
65 bool const mfIsSource;
66
67 /** @name stream stuff
68 * @{ */
69 RTSOCKET mhSocket;
70 uint64_t moffStream;
71 uint32_t mcbReadBlock;
72 bool volatile mfStopReading;
73 bool volatile mfEndOfStream;
74 bool volatile mfIOError;
75 /** @} */
76
77 TeleporterState(Console *pConsole, PUVM pUVM, PCVMMR3VTABLE pVMM, Progress *pProgress, bool fIsSource)
78 : mptrConsole(pConsole)
79 , mpUVM(pUVM)
80 , mpVMM(pVMM)
81 , mptrProgress(pProgress)
82 , mfIsSource(fIsSource)
83 , mhSocket(NIL_RTSOCKET)
84 , moffStream(UINT64_MAX / 2)
85 , mcbReadBlock(0)
86 , mfStopReading(false)
87 , mfEndOfStream(false)
88 , mfIOError(false)
89 {
90 pVMM->pfnVMR3RetainUVM(mpUVM);
91 }
92
93 ~TeleporterState()
94 {
95 if (mpVMM)
96 mpVMM->pfnVMR3ReleaseUVM(mpUVM);
97 mpUVM = NULL;
98 }
99};
100
101
102/**
103 * Teleporter state used by the source side.
104 */
105class TeleporterStateSrc : public TeleporterState
106{
107public:
108 Utf8Str mstrHostname;
109 uint32_t muPort;
110 uint32_t mcMsMaxDowntime;
111 MachineState_T menmOldMachineState;
112 bool mfSuspendedByUs;
113 bool mfUnlockedMedia;
114
115 TeleporterStateSrc(Console *pConsole, PUVM pUVM, PCVMMR3VTABLE pVMM, Progress *pProgress, MachineState_T enmOldMachineState)
116 : TeleporterState(pConsole, pUVM, pVMM, pProgress, true /*fIsSource*/)
117 , muPort(UINT32_MAX)
118 , mcMsMaxDowntime(250)
119 , menmOldMachineState(enmOldMachineState)
120 , mfSuspendedByUs(false)
121 , mfUnlockedMedia(false)
122 {
123 }
124};
125
126
127/**
128 * Teleporter state used by the destination side.
129 */
130class TeleporterStateTrg : public TeleporterState
131{
132public:
133 IMachine *mpMachine;
134 IInternalMachineControl *mpControl;
135 PRTTCPSERVER mhServer;
136 PRTTIMERLR mphTimerLR;
137 bool mfLockedMedia;
138 int mRc;
139 Utf8Str mErrorText;
140
141 TeleporterStateTrg(Console *pConsole, PUVM pUVM, PCVMMR3VTABLE pVMM, Progress *pProgress,
142 IMachine *pMachine, IInternalMachineControl *pControl,
143 PRTTIMERLR phTimerLR, bool fStartPaused)
144 : TeleporterState(pConsole, pUVM, pVMM, pProgress, false /*fIsSource*/)
145 , mpMachine(pMachine)
146 , mpControl(pControl)
147 , mhServer(NULL)
148 , mphTimerLR(phTimerLR)
149 , mfLockedMedia(false)
150 , mRc(VINF_SUCCESS)
151 , mErrorText()
152 {
153 RT_NOREF(fStartPaused); /** @todo figure out why fStartPaused isn't used */
154 }
155};
156
157
158/**
159 * TCP stream header.
160 *
161 * This is an extra layer for fixing the problem with figuring out when the SSM
162 * stream ends.
163 */
164typedef struct TELEPORTERTCPHDR
165{
166 /** Magic value. */
167 uint32_t u32Magic;
168 /** The size of the data block following this header.
169 * 0 indicates the end of the stream, while UINT32_MAX indicates
170 * cancelation. */
171 uint32_t cb;
172} TELEPORTERTCPHDR;
173/** Magic value for TELEPORTERTCPHDR::u32Magic. (Egberto Gismonti Amin) */
174#define TELEPORTERTCPHDR_MAGIC UINT32_C(0x19471205)
175/** The max block size. */
176#define TELEPORTERTCPHDR_MAX_SIZE UINT32_C(0x00fffff8)
177
178
179/*********************************************************************************************************************************
180* Global Variables *
181*********************************************************************************************************************************/
182static const char g_szWelcome[] = "VirtualBox-Teleporter-1.0\n";
183
184
185/**
186 * Reads a string from the socket.
187 *
188 * @returns VBox status code.
189 *
190 * @param pState The teleporter state structure.
191 * @param pszBuf The output buffer.
192 * @param cchBuf The size of the output buffer.
193 *
194 */
195static int teleporterTcpReadLine(TeleporterState *pState, char *pszBuf, size_t cchBuf)
196{
197 char *pszStart = pszBuf;
198 RTSOCKET hSocket = pState->mhSocket;
199
200 AssertReturn(cchBuf > 1, VERR_INTERNAL_ERROR);
201 *pszBuf = '\0';
202
203 /* dead simple approach. */
204 for (;;)
205 {
206 char ch;
207 int rc = RTTcpRead(hSocket, &ch, sizeof(ch), NULL);
208 if (RT_FAILURE(rc))
209 {
210 LogRel(("Teleporter: RTTcpRead -> %Rrc while reading string ('%s')\n", rc, pszStart));
211 return rc;
212 }
213 if ( ch == '\n'
214 || ch == '\0')
215 return VINF_SUCCESS;
216 if (cchBuf <= 1)
217 {
218 LogRel(("Teleporter: String buffer overflow: '%s'\n", pszStart));
219 return VERR_BUFFER_OVERFLOW;
220 }
221 *pszBuf++ = ch;
222 *pszBuf = '\0';
223 cchBuf--;
224 }
225}
226
227
228/**
229 * Reads an ACK or NACK.
230 *
231 * @returns S_OK on ACK, E_FAIL+setError() on failure or NACK.
232 * @param pState The teleporter source state.
233 * @param pszWhich Which ACK is this this?
234 * @param pszNAckMsg Optional NACK message.
235 *
236 * @remarks the setError laziness forces this to be a Console member.
237 */
238HRESULT
239Console::i_teleporterSrcReadACK(TeleporterStateSrc *pState, const char *pszWhich, const char *pszNAckMsg /*= NULL*/)
240{
241 char szMsg[256];
242 int vrc = teleporterTcpReadLine(pState, szMsg, sizeof(szMsg));
243 if (RT_FAILURE(vrc))
244 return setErrorBoth(E_FAIL, vrc, tr("Failed reading ACK(%s): %Rrc"), pszWhich, vrc);
245
246 if (!strcmp(szMsg, "ACK"))
247 return S_OK;
248
249 if (!strncmp(szMsg, RT_STR_TUPLE("NACK=")))
250 {
251 char *pszMsgText = strchr(szMsg, ';');
252 if (pszMsgText)
253 *pszMsgText++ = '\0';
254
255 int32_t vrc2;
256 vrc = RTStrToInt32Full(&szMsg[sizeof("NACK=") - 1], 10, &vrc2);
257 if (vrc == VINF_SUCCESS)
258 {
259 /*
260 * Well formed NACK, transform it into an error.
261 */
262 if (pszNAckMsg)
263 {
264 LogRel(("Teleporter: %s: NACK=%Rrc (%d)\n", pszWhich, vrc2, vrc2));
265 return setError(E_FAIL, pszNAckMsg);
266 }
267
268 if (pszMsgText)
269 {
270 pszMsgText = RTStrStrip(pszMsgText);
271 for (size_t off = 0; pszMsgText[off]; off++)
272 if (pszMsgText[off] == '\r')
273 pszMsgText[off] = '\n';
274
275 LogRel(("Teleporter: %s: NACK=%Rrc (%d) - '%s'\n", pszWhich, vrc2, vrc2, pszMsgText));
276 if (strlen(pszMsgText) > 4)
277 return setError(E_FAIL, "%s", pszMsgText);
278 return setError(E_FAIL, "NACK(%s) - %Rrc (%d) '%s'", pszWhich, vrc2, vrc2, pszMsgText);
279 }
280
281 return setError(E_FAIL, "NACK(%s) - %Rrc (%d)", pszWhich, vrc2, vrc2);
282 }
283
284 if (pszMsgText)
285 pszMsgText[-1] = ';';
286 }
287 return setError(E_FAIL, tr("%s: Expected ACK or NACK, got '%s'"), pszWhich, szMsg);
288}
289
290
291/**
292 * Submitts a command to the destination and waits for the ACK.
293 *
294 * @returns S_OK on ACKed command, E_FAIL+setError() on failure.
295 *
296 * @param pState The teleporter source state.
297 * @param pszCommand The command.
298 * @param fWaitForAck Whether to wait for the ACK.
299 *
300 * @remarks the setError laziness forces this to be a Console member.
301 */
302HRESULT Console::i_teleporterSrcSubmitCommand(TeleporterStateSrc *pState, const char *pszCommand, bool fWaitForAck /*= true*/)
303{
304 int vrc = RTTcpSgWriteL(pState->mhSocket, 2, pszCommand, strlen(pszCommand), "\n", sizeof("\n") - 1);
305 if (RT_FAILURE(vrc))
306 return setErrorBoth(E_FAIL, vrc, tr("Failed writing command '%s': %Rrc"), pszCommand, vrc);
307 if (!fWaitForAck)
308 return S_OK;
309 return i_teleporterSrcReadACK(pState, pszCommand);
310}
311
312
313/**
314 * @copydoc SSMSTRMOPS::pfnWrite
315 */
316static DECLCALLBACK(int) teleporterTcpOpWrite(void *pvUser, uint64_t offStream, const void *pvBuf, size_t cbToWrite)
317{
318 RT_NOREF(offStream);
319 TeleporterState *pState = (TeleporterState *)pvUser;
320
321 AssertReturn(cbToWrite > 0, VINF_SUCCESS);
322 AssertReturn(cbToWrite < UINT32_MAX, VERR_OUT_OF_RANGE);
323 AssertReturn(pState->mfIsSource, VERR_INVALID_HANDLE);
324
325 for (;;)
326 {
327 TELEPORTERTCPHDR Hdr;
328 Hdr.u32Magic = TELEPORTERTCPHDR_MAGIC;
329 Hdr.cb = RT_MIN((uint32_t)cbToWrite, TELEPORTERTCPHDR_MAX_SIZE);
330 int rc = RTTcpSgWriteL(pState->mhSocket, 2, &Hdr, sizeof(Hdr), pvBuf, (size_t)Hdr.cb);
331 if (RT_FAILURE(rc))
332 {
333 LogRel(("Teleporter/TCP: Write error: %Rrc (cb=%#x)\n", rc, Hdr.cb));
334 return rc;
335 }
336 pState->moffStream += Hdr.cb;
337 if (Hdr.cb == cbToWrite)
338 return VINF_SUCCESS;
339
340 /* advance */
341 cbToWrite -= Hdr.cb;
342 pvBuf = (uint8_t const *)pvBuf + Hdr.cb;
343 }
344}
345
346
347/**
348 * Selects and poll for close condition.
349 *
350 * We can use a relatively high poll timeout here since it's only used to get
351 * us out of error paths. In the normal cause of events, we'll get a
352 * end-of-stream header.
353 *
354 * @returns VBox status code.
355 *
356 * @param pState The teleporter state data.
357 */
358static int teleporterTcpReadSelect(TeleporterState *pState)
359{
360 int rc;
361 do
362 {
363 rc = RTTcpSelectOne(pState->mhSocket, 1000);
364 if (RT_FAILURE(rc) && rc != VERR_TIMEOUT)
365 {
366 pState->mfIOError = true;
367 LogRel(("Teleporter/TCP: Header select error: %Rrc\n", rc));
368 break;
369 }
370 if (pState->mfStopReading)
371 {
372 rc = VERR_EOF;
373 break;
374 }
375 } while (rc == VERR_TIMEOUT);
376 return rc;
377}
378
379
380/**
381 * @copydoc SSMSTRMOPS::pfnRead
382 */
383static DECLCALLBACK(int) teleporterTcpOpRead(void *pvUser, uint64_t offStream, void *pvBuf, size_t cbToRead, size_t *pcbRead)
384{
385 RT_NOREF(offStream);
386 TeleporterState *pState = (TeleporterState *)pvUser;
387 AssertReturn(!pState->mfIsSource, VERR_INVALID_HANDLE);
388
389 for (;;)
390 {
391 int rc;
392
393 /*
394 * Check for various conditions and may have been signalled.
395 */
396 if (pState->mfEndOfStream)
397 return VERR_EOF;
398 if (pState->mfStopReading)
399 return VERR_EOF;
400 if (pState->mfIOError)
401 return VERR_IO_GEN_FAILURE;
402
403 /*
404 * If there is no more data in the current block, read the next
405 * block header.
406 */
407 if (!pState->mcbReadBlock)
408 {
409 rc = teleporterTcpReadSelect(pState);
410 if (RT_FAILURE(rc))
411 return rc;
412 TELEPORTERTCPHDR Hdr;
413 rc = RTTcpRead(pState->mhSocket, &Hdr, sizeof(Hdr), NULL);
414 if (RT_FAILURE(rc))
415 {
416 pState->mfIOError = true;
417 LogRel(("Teleporter/TCP: Header read error: %Rrc\n", rc));
418 return rc;
419 }
420
421 if (RT_UNLIKELY( Hdr.u32Magic != TELEPORTERTCPHDR_MAGIC
422 || Hdr.cb > TELEPORTERTCPHDR_MAX_SIZE
423 || Hdr.cb == 0))
424 {
425 if ( Hdr.u32Magic == TELEPORTERTCPHDR_MAGIC
426 && ( Hdr.cb == 0
427 || Hdr.cb == UINT32_MAX)
428 )
429 {
430 pState->mfEndOfStream = true;
431 pState->mcbReadBlock = 0;
432 return Hdr.cb ? VERR_SSM_CANCELLED : VERR_EOF;
433 }
434 pState->mfIOError = true;
435 LogRel(("Teleporter/TCP: Invalid block: u32Magic=%#x cb=%#x\n", Hdr.u32Magic, Hdr.cb));
436 return VERR_IO_GEN_FAILURE;
437 }
438
439 pState->mcbReadBlock = Hdr.cb;
440 if (pState->mfStopReading)
441 return VERR_EOF;
442 }
443
444 /*
445 * Read more data.
446 */
447 rc = teleporterTcpReadSelect(pState);
448 if (RT_FAILURE(rc))
449 return rc;
450 uint32_t cb = (uint32_t)RT_MIN(pState->mcbReadBlock, cbToRead);
451 rc = RTTcpRead(pState->mhSocket, pvBuf, cb, pcbRead);
452 if (RT_FAILURE(rc))
453 {
454 pState->mfIOError = true;
455 LogRel(("Teleporter/TCP: Data read error: %Rrc (cb=%#x)\n", rc, cb));
456 return rc;
457 }
458 if (pcbRead)
459 {
460 cb = (uint32_t)*pcbRead;
461 pState->moffStream += cb;
462 pState->mcbReadBlock -= cb;
463 return VINF_SUCCESS;
464 }
465 pState->moffStream += cb;
466 pState->mcbReadBlock -= cb;
467 if (cbToRead == cb)
468 return VINF_SUCCESS;
469
470 /* Advance to the next block. */
471 cbToRead -= cb;
472 pvBuf = (uint8_t *)pvBuf + cb;
473 }
474}
475
476
477/**
478 * @copydoc SSMSTRMOPS::pfnSeek
479 */
480static DECLCALLBACK(int) teleporterTcpOpSeek(void *pvUser, int64_t offSeek, unsigned uMethod, uint64_t *poffActual)
481{
482 RT_NOREF(pvUser, offSeek, uMethod, poffActual);
483 return VERR_NOT_SUPPORTED;
484}
485
486
487/**
488 * @copydoc SSMSTRMOPS::pfnTell
489 */
490static DECLCALLBACK(uint64_t) teleporterTcpOpTell(void *pvUser)
491{
492 TeleporterState *pState = (TeleporterState *)pvUser;
493 return pState->moffStream;
494}
495
496
497/**
498 * @copydoc SSMSTRMOPS::pfnSize
499 */
500static DECLCALLBACK(int) teleporterTcpOpSize(void *pvUser, uint64_t *pcb)
501{
502 RT_NOREF(pvUser, pcb);
503 return VERR_NOT_SUPPORTED;
504}
505
506
507/**
508 * @copydoc SSMSTRMOPS::pfnIsOk
509 */
510static DECLCALLBACK(int) teleporterTcpOpIsOk(void *pvUser)
511{
512 TeleporterState *pState = (TeleporterState *)pvUser;
513
514 if (pState->mfIsSource)
515 {
516 /* Poll for incoming NACKs and errors from the other side */
517 int rc = RTTcpSelectOne(pState->mhSocket, 0);
518 if (rc != VERR_TIMEOUT)
519 {
520 if (RT_SUCCESS(rc))
521 {
522 LogRel(("Teleporter/TCP: Incoming data detect by IsOk, assuming it is a cancellation NACK.\n"));
523 rc = VERR_SSM_CANCELLED;
524 }
525 else
526 LogRel(("Teleporter/TCP: RTTcpSelectOne -> %Rrc (IsOk).\n", rc));
527 return rc;
528 }
529 }
530
531 return VINF_SUCCESS;
532}
533
534
535/**
536 * @copydoc SSMSTRMOPS::pfnClose
537 */
538static DECLCALLBACK(int) teleporterTcpOpClose(void *pvUser, bool fCancelled)
539{
540 TeleporterState *pState = (TeleporterState *)pvUser;
541
542 if (pState->mfIsSource)
543 {
544 TELEPORTERTCPHDR EofHdr;
545 EofHdr.u32Magic = TELEPORTERTCPHDR_MAGIC;
546 EofHdr.cb = fCancelled ? UINT32_MAX : 0;
547 int rc = RTTcpWrite(pState->mhSocket, &EofHdr, sizeof(EofHdr));
548 if (RT_FAILURE(rc))
549 {
550 LogRel(("Teleporter/TCP: EOF Header write error: %Rrc\n", rc));
551 return rc;
552 }
553 }
554 else
555 {
556 ASMAtomicWriteBool(&pState->mfStopReading, true);
557 }
558
559 return VINF_SUCCESS;
560}
561
562
563/**
564 * Method table for a TCP based stream.
565 */
566static SSMSTRMOPS const g_teleporterTcpOps =
567{
568 SSMSTRMOPS_VERSION,
569 teleporterTcpOpWrite,
570 teleporterTcpOpRead,
571 teleporterTcpOpSeek,
572 teleporterTcpOpTell,
573 teleporterTcpOpSize,
574 teleporterTcpOpIsOk,
575 teleporterTcpOpClose,
576 SSMSTRMOPS_VERSION
577};
578
579
580/**
581 * Progress cancelation callback.
582 */
583static void teleporterProgressCancelCallback(void *pvUser)
584{
585 TeleporterState *pState = (TeleporterState *)pvUser;
586 pState->mpVMM->pfnSSMR3Cancel(pState->mpUVM);
587 if (!pState->mfIsSource)
588 {
589 TeleporterStateTrg *pStateTrg = (TeleporterStateTrg *)pState;
590 RTTcpServerShutdown(pStateTrg->mhServer);
591 }
592}
593
594/**
595 * @copydoc PFNVMPROGRESS
596 */
597static DECLCALLBACK(int) teleporterProgressCallback(PUVM pUVM, unsigned uPercent, void *pvUser)
598{
599 TeleporterState *pState = (TeleporterState *)pvUser;
600 if (pState->mptrProgress)
601 {
602 HRESULT hrc = pState->mptrProgress->SetCurrentOperationProgress(uPercent);
603 if (FAILED(hrc))
604 {
605 /* check if the failure was caused by cancellation. */
606 BOOL fCanceled;
607 hrc = pState->mptrProgress->COMGETTER(Canceled)(&fCanceled);
608 if (SUCCEEDED(hrc) && fCanceled)
609 {
610 pState->mpVMM->pfnSSMR3Cancel(pState->mpUVM);
611 return VERR_SSM_CANCELLED;
612 }
613 }
614 }
615
616 NOREF(pUVM);
617 return VINF_SUCCESS;
618}
619
620
621/**
622 * @copydoc FNRTTIMERLR
623 */
624static DECLCALLBACK(void) teleporterDstTimeout(RTTIMERLR hTimerLR, void *pvUser, uint64_t iTick)
625{
626 RT_NOREF(hTimerLR, iTick);
627 /* This is harmless for any open connections. */
628 RTTcpServerShutdown((PRTTCPSERVER)pvUser);
629}
630
631
632/**
633 * Do the teleporter.
634 *
635 * @returns VBox status code.
636 * @param pState The teleporter state.
637 */
638HRESULT Console::i_teleporterSrc(TeleporterStateSrc *pState)
639{
640 AutoCaller autoCaller(this);
641 if (FAILED(autoCaller.rc())) return autoCaller.rc();
642
643 /*
644 * Wait for Console::Teleport to change the state.
645 */
646 { AutoWriteLock autoLock(this COMMA_LOCKVAL_SRC_POS); }
647
648 BOOL fCanceled = TRUE;
649 HRESULT hrc = pState->mptrProgress->COMGETTER(Canceled)(&fCanceled);
650 if (FAILED(hrc))
651 return hrc;
652 if (fCanceled)
653 return setError(E_FAIL, tr("canceled"));
654
655 /*
656 * Try connect to the destination machine, disable Nagle.
657 * (Note. The caller cleans up mhSocket, so we can return without worries.)
658 */
659 int vrc = RTTcpClientConnect(pState->mstrHostname.c_str(), pState->muPort, &pState->mhSocket);
660 if (RT_FAILURE(vrc))
661 return setErrorBoth(E_FAIL, vrc, tr("Failed to connect to port %u on '%s': %Rrc"),
662 pState->muPort, pState->mstrHostname.c_str(), vrc);
663 vrc = RTTcpSetSendCoalescing(pState->mhSocket, false /*fEnable*/);
664 AssertRC(vrc);
665
666 /* Read and check the welcome message. */
667 char szLine[RT_MAX(128, sizeof(g_szWelcome))];
668 RT_ZERO(szLine);
669 vrc = RTTcpRead(pState->mhSocket, szLine, sizeof(g_szWelcome) - 1, NULL);
670 if (RT_FAILURE(vrc))
671 return setErrorBoth(E_FAIL, vrc, tr("Failed to read welcome message: %Rrc"), vrc);
672 if (strcmp(szLine, g_szWelcome))
673 return setError(E_FAIL, tr("Unexpected welcome %.*Rhxs"), sizeof(g_szWelcome) - 1, szLine);
674
675 /* password */
676 pState->mstrPassword.append('\n');
677 vrc = RTTcpWrite(pState->mhSocket, pState->mstrPassword.c_str(), pState->mstrPassword.length());
678 if (RT_FAILURE(vrc))
679 return setErrorBoth(E_FAIL, vrc, tr("Failed to send password: %Rrc"), vrc);
680
681 /* ACK */
682 hrc = i_teleporterSrcReadACK(pState, "password", tr("Invalid password"));
683 if (FAILED(hrc))
684 return hrc;
685
686 /*
687 * Start loading the state.
688 *
689 * Note! The saved state includes vital configuration data which will be
690 * verified against the VM config on the other end. This is all done
691 * in the first pass, so we should fail pretty promptly on misconfig.
692 */
693 hrc = i_teleporterSrcSubmitCommand(pState, "load");
694 if (FAILED(hrc))
695 return hrc;
696
697 RTSocketRetain(pState->mhSocket);
698 void *pvUser = static_cast<void *>(static_cast<TeleporterState *>(pState));
699 vrc = pState->mpVMM->pfnVMR3Teleport(pState->mpUVM,
700 pState->mcMsMaxDowntime,
701 &g_teleporterTcpOps, pvUser,
702 teleporterProgressCallback, pvUser,
703 &pState->mfSuspendedByUs);
704 RTSocketRelease(pState->mhSocket);
705 if (RT_FAILURE(vrc))
706 {
707 if ( vrc == VERR_SSM_CANCELLED
708 && RT_SUCCESS(RTTcpSelectOne(pState->mhSocket, 1)))
709 {
710 hrc = i_teleporterSrcReadACK(pState, "load-complete");
711 if (FAILED(hrc))
712 return hrc;
713 }
714 return setErrorBoth(E_FAIL, vrc, "VMR3Teleport -> %Rrc", vrc);
715 }
716
717 hrc = i_teleporterSrcReadACK(pState, "load-complete");
718 if (FAILED(hrc))
719 return hrc;
720
721 /*
722 * We're at the point of no return.
723 */
724 if (FAILED(pState->mptrProgress->NotifyPointOfNoReturn()))
725 {
726 i_teleporterSrcSubmitCommand(pState, "cancel", false /*fWaitForAck*/);
727 return E_FAIL;
728 }
729
730 /*
731 * Hand over any media which we might be sharing.
732 *
733 * Note! This is only important on localhost teleportations.
734 */
735 /** @todo Maybe we should only do this if it's a local teleportation... */
736 hrc = mControl->UnlockMedia();
737 if (FAILED(hrc))
738 return hrc;
739 pState->mfUnlockedMedia = true;
740
741 hrc = i_teleporterSrcSubmitCommand(pState, "lock-media");
742 if (FAILED(hrc))
743 return hrc;
744
745 /*
746 * The FINAL step is giving the target instructions how to proceed with the VM.
747 */
748 if ( vrc == VINF_SSM_LIVE_SUSPENDED
749 || pState->menmOldMachineState == MachineState_Paused)
750 hrc = i_teleporterSrcSubmitCommand(pState, "hand-over-paused");
751 else
752 hrc = i_teleporterSrcSubmitCommand(pState, "hand-over-resume");
753 if (FAILED(hrc))
754 return hrc;
755
756 /*
757 * teleporterSrcThreadWrapper will do the automatic power off because it
758 * has to release the AutoVMCaller.
759 */
760 return S_OK;
761}
762
763
764/**
765 * Static thread method wrapper.
766 *
767 * @returns VINF_SUCCESS (ignored).
768 * @param hThreadSelf The thread.
769 * @param pvUser Pointer to a TeleporterStateSrc instance.
770 */
771/*static*/ DECLCALLBACK(int)
772Console::i_teleporterSrcThreadWrapper(RTTHREAD hThreadSelf, void *pvUser)
773{
774 RT_NOREF(hThreadSelf);
775 TeleporterStateSrc *pState = (TeleporterStateSrc *)pvUser;
776
777 /*
778 * Console::teleporterSrc does the work, we just grab onto the VM handle
779 * and do the cleanups afterwards.
780 */
781 SafeVMPtr ptrVM(pState->mptrConsole);
782 HRESULT hrc = ptrVM.rc();
783
784 if (SUCCEEDED(hrc))
785 hrc = pState->mptrConsole->i_teleporterSrc(pState);
786
787 /* Close the connection ASAP on so that the other side can complete. */
788 if (pState->mhSocket != NIL_RTSOCKET)
789 {
790 RTTcpClientClose(pState->mhSocket);
791 pState->mhSocket = NIL_RTSOCKET;
792 }
793
794 /* Aaarg! setMachineState trashes error info on Windows, so we have to
795 complete things here on failure instead of right before cleanup. */
796 if (FAILED(hrc))
797 pState->mptrProgress->i_notifyComplete(hrc);
798
799 /* We can no longer be canceled (success), or it doesn't matter any longer (failure). */
800 pState->mptrProgress->i_setCancelCallback(NULL, NULL);
801
802 /*
803 * Write lock the console before resetting mptrCancelableProgress and
804 * fixing the state.
805 */
806 AutoWriteLock autoLock(pState->mptrConsole COMMA_LOCKVAL_SRC_POS);
807 pState->mptrConsole->mptrCancelableProgress.setNull();
808
809 VMSTATE const enmVMState = pState->mpVMM->pfnVMR3GetStateU(pState->mpUVM);
810 MachineState_T const enmMachineState = pState->mptrConsole->mMachineState;
811 if (SUCCEEDED(hrc))
812 {
813 /*
814 * Automatically shut down the VM on success.
815 *
816 * Note! We have to release the VM caller object or we'll deadlock in
817 * powerDown.
818 */
819 AssertLogRelMsg(enmVMState == VMSTATE_SUSPENDED, ("%s\n", pState->mpVMM->pfnVMR3GetStateName(enmVMState)));
820 AssertLogRelMsg(enmMachineState == MachineState_TeleportingPausedVM, ("%s\n", ::stringifyMachineState(enmMachineState)));
821
822 ptrVM.release();
823
824 pState->mptrConsole->mVMIsAlreadyPoweringOff = true; /* (Make sure we stick in the TeleportingPausedVM state.) */
825 autoLock.release();
826
827 hrc = pState->mptrConsole->i_powerDown();
828
829 autoLock.acquire();
830 pState->mptrConsole->mVMIsAlreadyPoweringOff = false;
831
832 pState->mptrProgress->i_notifyComplete(hrc);
833 }
834 else
835 {
836 /*
837 * Work the state machinery on failure.
838 *
839 * If the state is no longer 'Teleporting*', some other operation has
840 * canceled us and there is nothing we need to do here. In all other
841 * cases, we've failed one way or another.
842 */
843 if ( enmMachineState == MachineState_Teleporting
844 || enmMachineState == MachineState_TeleportingPausedVM
845 )
846 {
847 if (pState->mfUnlockedMedia)
848 {
849 ErrorInfoKeeper Oak;
850 HRESULT hrc2 = pState->mptrConsole->mControl->LockMedia();
851 if (FAILED(hrc2))
852 {
853 uint64_t StartMS = RTTimeMilliTS();
854 do
855 {
856 RTThreadSleep(2);
857 hrc2 = pState->mptrConsole->mControl->LockMedia();
858 } while ( FAILED(hrc2)
859 && RTTimeMilliTS() - StartMS < 2000);
860 }
861 if (SUCCEEDED(hrc2))
862 pState->mfUnlockedMedia = true;
863 else
864 LogRel(("FATAL ERROR: Failed to re-take the media locks. hrc2=%Rhrc\n", hrc2));
865 }
866
867 switch (enmVMState)
868 {
869 case VMSTATE_RUNNING:
870 case VMSTATE_RUNNING_LS:
871 case VMSTATE_DEBUGGING:
872 case VMSTATE_DEBUGGING_LS:
873 case VMSTATE_POWERING_OFF:
874 case VMSTATE_POWERING_OFF_LS:
875 case VMSTATE_RESETTING:
876 case VMSTATE_RESETTING_LS:
877 case VMSTATE_SOFT_RESETTING:
878 case VMSTATE_SOFT_RESETTING_LS:
879 Assert(!pState->mfSuspendedByUs);
880 Assert(!pState->mfUnlockedMedia);
881 pState->mptrConsole->i_setMachineState(MachineState_Running);
882 break;
883
884 case VMSTATE_GURU_MEDITATION:
885 case VMSTATE_GURU_MEDITATION_LS:
886 pState->mptrConsole->i_setMachineState(MachineState_Stuck);
887 break;
888
889 case VMSTATE_FATAL_ERROR:
890 case VMSTATE_FATAL_ERROR_LS:
891 pState->mptrConsole->i_setMachineState(MachineState_Paused);
892 break;
893
894 default:
895 AssertMsgFailed(("%s\n", pState->mpVMM->pfnVMR3GetStateName(enmVMState)));
896 RT_FALL_THRU();
897 case VMSTATE_SUSPENDED:
898 case VMSTATE_SUSPENDED_LS:
899 case VMSTATE_SUSPENDING:
900 case VMSTATE_SUSPENDING_LS:
901 case VMSTATE_SUSPENDING_EXT_LS:
902 if (!pState->mfUnlockedMedia)
903 {
904 pState->mptrConsole->i_setMachineState(MachineState_Paused);
905 if (pState->mfSuspendedByUs)
906 {
907 autoLock.release();
908 int rc = pState->mpVMM->pfnVMR3Resume(pState->mpUVM, VMRESUMEREASON_TELEPORT_FAILED);
909 AssertLogRelMsgRC(rc, ("VMR3Resume -> %Rrc\n", rc));
910 autoLock.acquire();
911 }
912 }
913 else
914 {
915 /* Faking a guru meditation is the best I can think of doing here... */
916 pState->mptrConsole->i_setMachineState(MachineState_Stuck);
917 }
918 break;
919 }
920 }
921 }
922 autoLock.release();
923
924 /*
925 * Cleanup.
926 */
927 Assert(pState->mhSocket == NIL_RTSOCKET);
928 delete pState;
929
930 return VINF_SUCCESS; /* ignored */
931}
932
933
934/**
935 * Start teleporter to the specified target.
936 *
937 * @returns COM status code.
938 *
939 * @param aHostname The name of the target host.
940 * @param aTcpport The TCP port number.
941 * @param aPassword The password.
942 * @param aMaxDowntime Max allowed "downtime" in milliseconds.
943 * @param aProgress Where to return the progress object.
944 */
945HRESULT Console::teleport(const com::Utf8Str &aHostname, ULONG aTcpport, const com::Utf8Str &aPassword,
946 ULONG aMaxDowntime, ComPtr<IProgress> &aProgress)
947{
948 /*
949 * Validate parameters, check+hold object status, write lock the object
950 * and validate the state.
951 */
952 Utf8Str strPassword(aPassword);
953 if (!strPassword.isEmpty())
954 {
955 if (VBoxIsPasswordHashed(&strPassword))
956 return setError(E_INVALIDARG, tr("The specified password resembles a hashed password, expected plain text"));
957 VBoxHashPassword(&strPassword);
958 }
959
960 AutoCaller autoCaller(this);
961 if (FAILED(autoCaller.rc())) return autoCaller.rc();
962
963 AutoWriteLock autoLock(this COMMA_LOCKVAL_SRC_POS);
964 LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
965
966 switch (mMachineState)
967 {
968 case MachineState_Running:
969 case MachineState_Paused:
970 break;
971
972 default:
973 return setError(VBOX_E_INVALID_VM_STATE, tr("Invalid machine state: %s (must be Running or Paused)"),
974 Global::stringifyMachineState(mMachineState));
975 }
976
977
978 /*
979 * Create a progress object, spawn a worker thread and change the state.
980 * Note! The thread won't start working until we release the lock.
981 */
982 LogFlowThisFunc(("Initiating TELEPORT request...\n"));
983
984 ComObjPtr<Progress> ptrProgress;
985 HRESULT hrc = ptrProgress.createObject();
986 if (SUCCEEDED(hrc))
987 hrc = ptrProgress->init(static_cast<IConsole *>(this),
988 Bstr(tr("Teleporter")).raw(),
989 TRUE /*aCancelable*/);
990 if (FAILED(hrc))
991 return hrc;
992
993 TeleporterStateSrc *pState = new TeleporterStateSrc(this, mpUVM, mpVMM, ptrProgress, mMachineState);
994 pState->mstrPassword = strPassword;
995 pState->mstrHostname = aHostname;
996 pState->muPort = aTcpport;
997 pState->mcMsMaxDowntime = aMaxDowntime;
998
999 void *pvUser = static_cast<void *>(static_cast<TeleporterState *>(pState));
1000 ptrProgress->i_setCancelCallback(teleporterProgressCancelCallback, pvUser);
1001
1002 int vrc = RTThreadCreate(NULL, Console::i_teleporterSrcThreadWrapper, (void *)pState, 0 /*cbStack*/,
1003 RTTHREADTYPE_EMULATION, 0 /*fFlags*/, "Teleport");
1004 if (RT_SUCCESS(vrc))
1005 {
1006 if (mMachineState == MachineState_Running)
1007 hrc = i_setMachineState(MachineState_Teleporting);
1008 else
1009 hrc = i_setMachineState(MachineState_TeleportingPausedVM);
1010 if (SUCCEEDED(hrc))
1011 {
1012 ptrProgress.queryInterfaceTo(aProgress.asOutParam());
1013 mptrCancelableProgress = aProgress;
1014 }
1015 else
1016 ptrProgress->Cancel();
1017 }
1018 else
1019 {
1020 ptrProgress->i_setCancelCallback(NULL, NULL);
1021 delete pState;
1022 hrc = setErrorBoth(E_FAIL, vrc, "RTThreadCreate -> %Rrc", vrc);
1023 }
1024
1025 return hrc;
1026}
1027
1028
1029/**
1030 * Creates a TCP server that listens for the source machine and passes control
1031 * over to Console::teleporterTrgServeConnection().
1032 *
1033 * @returns VBox status code.
1034 * @param pUVM The user-mode VM handle
1035 * @param pVMM The VMM vtable.
1036 * @param pMachine The IMachine for the virtual machine.
1037 * @param pErrorMsg Pointer to the error string for VMSetError.
1038 * @param fStartPaused Whether to start it in the Paused (true) or
1039 * Running (false) state,
1040 * @param pProgress Pointer to the progress object.
1041 * @param pfPowerOffOnFailure Whether the caller should power off
1042 * the VM on failure.
1043 *
1044 * @remarks The caller expects error information to be set on failure.
1045 * @todo Check that all the possible failure paths sets error info...
1046 */
1047HRESULT Console::i_teleporterTrg(PUVM pUVM, PCVMMR3VTABLE pVMM, IMachine *pMachine, Utf8Str *pErrorMsg, bool fStartPaused,
1048 Progress *pProgress, bool *pfPowerOffOnFailure)
1049{
1050 LogThisFunc(("pUVM=%p pVMM=%p pMachine=%p fStartPaused=%RTbool pProgress=%p\n", pUVM, pVMM, pMachine, fStartPaused, pProgress));
1051
1052 *pfPowerOffOnFailure = true;
1053
1054 /*
1055 * Get the config.
1056 */
1057 ULONG uPort;
1058 HRESULT hrc = pMachine->COMGETTER(TeleporterPort)(&uPort);
1059 if (FAILED(hrc))
1060 return hrc;
1061 ULONG const uPortOrg = uPort;
1062
1063 Bstr bstrAddress;
1064 hrc = pMachine->COMGETTER(TeleporterAddress)(bstrAddress.asOutParam());
1065 if (FAILED(hrc))
1066 return hrc;
1067 Utf8Str strAddress(bstrAddress);
1068 const char *pszAddress = strAddress.isEmpty() ? NULL : strAddress.c_str();
1069
1070 Bstr bstrPassword;
1071 hrc = pMachine->COMGETTER(TeleporterPassword)(bstrPassword.asOutParam());
1072 if (FAILED(hrc))
1073 return hrc;
1074 Utf8Str strPassword(bstrPassword);
1075 strPassword.append('\n'); /* To simplify password checking. */
1076
1077 /*
1078 * Create the TCP server.
1079 */
1080 int vrc = VINF_SUCCESS; /* Shut up MSC */
1081 PRTTCPSERVER hServer = NULL; /* ditto */
1082 if (uPort)
1083 vrc = RTTcpServerCreateEx(pszAddress, uPort, &hServer);
1084 else
1085 {
1086 for (int cTries = 10240; cTries > 0; cTries--)
1087 {
1088 uPort = RTRandU32Ex(cTries >= 8192 ? 49152 : 1024, 65534);
1089 vrc = RTTcpServerCreateEx(pszAddress, uPort, &hServer);
1090 if (vrc != VERR_NET_ADDRESS_IN_USE)
1091 break;
1092 }
1093 if (RT_SUCCESS(vrc))
1094 {
1095 hrc = pMachine->COMSETTER(TeleporterPort)(uPort);
1096 if (FAILED(hrc))
1097 {
1098 RTTcpServerDestroy(hServer);
1099 return hrc;
1100 }
1101 }
1102 }
1103 if (RT_FAILURE(vrc))
1104 return setErrorBoth(E_FAIL, vrc, tr("RTTcpServerCreateEx failed with status %Rrc"), vrc);
1105
1106 /*
1107 * Create a one-shot timer for timing out after 5 mins.
1108 */
1109 RTTIMERLR hTimerLR;
1110 vrc = RTTimerLRCreateEx(&hTimerLR, 0 /*ns*/, RTTIMER_FLAGS_CPU_ANY, teleporterDstTimeout, hServer);
1111 if (RT_SUCCESS(vrc))
1112 {
1113 vrc = RTTimerLRStart(hTimerLR, 5*60*UINT64_C(1000000000) /*ns*/);
1114 if (RT_SUCCESS(vrc))
1115 {
1116 /*
1117 * Do the job, when it returns we're done.
1118 */
1119 TeleporterStateTrg theState(this, pUVM, pVMM, pProgress, pMachine, mControl, &hTimerLR, fStartPaused);
1120 theState.mstrPassword = strPassword;
1121 theState.mhServer = hServer;
1122
1123 void *pvUser = static_cast<void *>(static_cast<TeleporterState *>(&theState));
1124 if (pProgress->i_setCancelCallback(teleporterProgressCancelCallback, pvUser))
1125 {
1126 LogRel(("Teleporter: Waiting for incoming VM...\n"));
1127 hrc = pProgress->SetNextOperation(Bstr(tr("Waiting for incoming VM")).raw(), 1);
1128 if (SUCCEEDED(hrc))
1129 {
1130 vrc = RTTcpServerListen(hServer, Console::i_teleporterTrgServeConnection, &theState);
1131 pProgress->i_setCancelCallback(NULL, NULL);
1132
1133 if (vrc == VERR_TCP_SERVER_STOP)
1134 {
1135 vrc = theState.mRc;
1136 /* Power off the VM on failure unless the state callback
1137 already did that. */
1138 *pfPowerOffOnFailure = false;
1139 if (RT_SUCCESS(vrc))
1140 hrc = S_OK;
1141 else
1142 {
1143 VMSTATE enmVMState = pVMM->pfnVMR3GetStateU(pUVM);
1144 if ( enmVMState != VMSTATE_OFF
1145 && enmVMState != VMSTATE_POWERING_OFF)
1146 *pfPowerOffOnFailure = true;
1147
1148 /* Set error. */
1149 if (pErrorMsg->length())
1150 hrc = setError(E_FAIL, "%s", pErrorMsg->c_str());
1151 else
1152 hrc = setError(E_FAIL, tr("Teleporation failed (%Rrc)"), vrc);
1153 }
1154 }
1155 else if (vrc == VERR_TCP_SERVER_SHUTDOWN)
1156 {
1157 BOOL fCanceled = TRUE;
1158 hrc = pProgress->COMGETTER(Canceled)(&fCanceled);
1159 if (FAILED(hrc) || fCanceled)
1160 hrc = setError(E_FAIL, tr("Teleporting canceled"));
1161 else
1162 hrc = setError(E_FAIL, tr("Teleporter timed out waiting for incoming connection"));
1163 LogRel(("Teleporter: RTTcpServerListen aborted - %Rrc\n", vrc));
1164 }
1165 else
1166 {
1167 hrc = setErrorBoth(E_FAIL, vrc, tr("Unexpected RTTcpServerListen status code %Rrc"), vrc);
1168 LogRel(("Teleporter: Unexpected RTTcpServerListen rc: %Rrc\n", vrc));
1169 }
1170 }
1171 else
1172 LogThisFunc(("SetNextOperation failed, %Rhrc\n", hrc));
1173 }
1174 else
1175 {
1176 LogThisFunc(("Canceled - check point #1\n"));
1177 hrc = setError(E_FAIL, tr("Teleporting canceled"));
1178 }
1179 }
1180 else
1181 hrc = setErrorBoth(E_FAIL, vrc, "RTTimerLRStart -> %Rrc", vrc);
1182
1183 RTTimerLRDestroy(hTimerLR);
1184 }
1185 else
1186 hrc = setErrorBoth(E_FAIL, vrc, "RTTimerLRCreate -> %Rrc", vrc);
1187 RTTcpServerDestroy(hServer);
1188
1189 /*
1190 * If we change TeleporterPort above, set it back to it's original
1191 * value before returning.
1192 */
1193 if (uPortOrg != uPort)
1194 {
1195 ErrorInfoKeeper Eik;
1196 pMachine->COMSETTER(TeleporterPort)(uPortOrg);
1197 }
1198
1199 return hrc;
1200}
1201
1202
1203/**
1204 * Unlock the media.
1205 *
1206 * This is used in error paths.
1207 *
1208 * @param pState The teleporter state.
1209 */
1210static void teleporterTrgUnlockMedia(TeleporterStateTrg *pState)
1211{
1212 if (pState->mfLockedMedia)
1213 {
1214 pState->mpControl->UnlockMedia();
1215 pState->mfLockedMedia = false;
1216 }
1217}
1218
1219
1220static int teleporterTcpWriteACK(TeleporterStateTrg *pState, bool fAutomaticUnlock = true)
1221{
1222 int rc = RTTcpWrite(pState->mhSocket, "ACK\n", sizeof("ACK\n") - 1);
1223 if (RT_FAILURE(rc))
1224 {
1225 LogRel(("Teleporter: RTTcpWrite(,ACK,) -> %Rrc\n", rc));
1226 if (fAutomaticUnlock)
1227 teleporterTrgUnlockMedia(pState);
1228 }
1229 return rc;
1230}
1231
1232
1233static int teleporterTcpWriteNACK(TeleporterStateTrg *pState, int32_t rc2, const char *pszMsgText = NULL)
1234{
1235 /*
1236 * Unlock media sending the NACK. That way the other doesn't have to spin
1237 * waiting to regain the locks.
1238 */
1239 teleporterTrgUnlockMedia(pState);
1240
1241 char szMsg[256];
1242 size_t cch;
1243 if (pszMsgText && *pszMsgText)
1244 {
1245 cch = RTStrPrintf(szMsg, sizeof(szMsg), "NACK=%d;%s\n", rc2, pszMsgText);
1246 for (size_t off = 6; off + 1 < cch; off++)
1247 if (szMsg[off] == '\n')
1248 szMsg[off] = '\r';
1249 }
1250 else
1251 cch = RTStrPrintf(szMsg, sizeof(szMsg), "NACK=%d\n", rc2);
1252 int rc = RTTcpWrite(pState->mhSocket, szMsg, cch);
1253 if (RT_FAILURE(rc))
1254 LogRel(("Teleporter: RTTcpWrite(,%s,%zu) -> %Rrc\n", szMsg, cch, rc));
1255 return rc;
1256}
1257
1258
1259/**
1260 * @copydoc FNRTTCPSERVE
1261 *
1262 * @returns VINF_SUCCESS or VERR_TCP_SERVER_STOP.
1263 */
1264/*static*/ DECLCALLBACK(int)
1265Console::i_teleporterTrgServeConnection(RTSOCKET hSocket, void *pvUser)
1266{
1267 TeleporterStateTrg *pState = (TeleporterStateTrg *)pvUser;
1268 pState->mhSocket = hSocket;
1269
1270 /*
1271 * Disable Nagle and say hello.
1272 */
1273 int vrc = RTTcpSetSendCoalescing(pState->mhSocket, false /*fEnable*/);
1274 AssertRC(vrc);
1275 vrc = RTTcpWrite(hSocket, g_szWelcome, sizeof(g_szWelcome) - 1);
1276 if (RT_FAILURE(vrc))
1277 {
1278 LogRel(("Teleporter: Failed to write welcome message: %Rrc\n", vrc));
1279 return VINF_SUCCESS;
1280 }
1281
1282 /*
1283 * Password (includes '\n', see teleporterTrg).
1284 */
1285 const char *pszPassword = pState->mstrPassword.c_str();
1286 unsigned off = 0;
1287 while (pszPassword[off])
1288 {
1289 char ch;
1290 vrc = RTTcpRead(hSocket, &ch, sizeof(ch), NULL);
1291 if ( RT_FAILURE(vrc)
1292 || pszPassword[off] != ch)
1293 {
1294 if (RT_FAILURE(vrc))
1295 LogRel(("Teleporter: Password read failure (off=%u): %Rrc\n", off, vrc));
1296 else
1297 LogRel(("Teleporter: Invalid password (off=%u)\n", off));
1298 teleporterTcpWriteNACK(pState, VERR_AUTHENTICATION_FAILURE);
1299 return VINF_SUCCESS;
1300 }
1301 off++;
1302 }
1303 vrc = teleporterTcpWriteACK(pState);
1304 if (RT_FAILURE(vrc))
1305 return VINF_SUCCESS;
1306
1307 /*
1308 * Update the progress bar, with peer name if available.
1309 */
1310 HRESULT hrc;
1311 RTNETADDR Addr;
1312 vrc = RTTcpGetPeerAddress(hSocket, &Addr);
1313 if (RT_SUCCESS(vrc))
1314 {
1315 LogRel(("Teleporter: Incoming VM from %RTnaddr!\n", &Addr));
1316 hrc = pState->mptrProgress->SetNextOperation(BstrFmt(tr("Teleporting VM from %RTnaddr"), &Addr).raw(), 8);
1317 }
1318 else
1319 {
1320 LogRel(("Teleporter: Incoming VM!\n"));
1321 hrc = pState->mptrProgress->SetNextOperation(Bstr(tr("Teleporting VM")).raw(), 8);
1322 }
1323 AssertMsg(SUCCEEDED(hrc) || hrc == E_FAIL, ("%Rhrc\n", hrc));
1324
1325 /*
1326 * Stop the server and cancel the timeout timer.
1327 *
1328 * Note! After this point we must return VERR_TCP_SERVER_STOP, while prior
1329 * to it we must not return that value!
1330 */
1331 RTTcpServerShutdown(pState->mhServer);
1332 RTTimerLRDestroy(*pState->mphTimerLR);
1333 *pState->mphTimerLR = NIL_RTTIMERLR;
1334
1335 /*
1336 * Command processing loop.
1337 */
1338 bool fDone = false;
1339 for (;;)
1340 {
1341 char szCmd[128];
1342 vrc = teleporterTcpReadLine(pState, szCmd, sizeof(szCmd));
1343 if (RT_FAILURE(vrc))
1344 break;
1345
1346 if (!strcmp(szCmd, "load"))
1347 {
1348 vrc = teleporterTcpWriteACK(pState);
1349 if (RT_FAILURE(vrc))
1350 break;
1351
1352 int vrc2 = pState->mpVMM->pfnVMR3AtErrorRegister(pState->mpUVM, Console::i_genericVMSetErrorCallback,
1353 &pState->mErrorText);
1354 AssertRC(vrc2);
1355 RTSocketRetain(pState->mhSocket); /* For concurrent access by I/O thread and EMT. */
1356 pState->moffStream = 0;
1357
1358 void *pvUser2 = static_cast<void *>(static_cast<TeleporterState *>(pState));
1359 vrc = pState->mpVMM->pfnVMR3LoadFromStream(pState->mpUVM,
1360 &g_teleporterTcpOps, pvUser2,
1361 teleporterProgressCallback, pvUser2);
1362
1363 RTSocketRelease(pState->mhSocket);
1364 vrc2 = pState->mpVMM->pfnVMR3AtErrorDeregister(pState->mpUVM, Console::i_genericVMSetErrorCallback, &pState->mErrorText);
1365 AssertRC(vrc2);
1366
1367 if (RT_FAILURE(vrc))
1368 {
1369 LogRel(("Teleporter: VMR3LoadFromStream -> %Rrc\n", vrc));
1370 teleporterTcpWriteNACK(pState, vrc, pState->mErrorText.c_str());
1371 break;
1372 }
1373
1374 /* The EOS might not have been read, make sure it is. */
1375 pState->mfStopReading = false;
1376 size_t cbRead;
1377 vrc = teleporterTcpOpRead(pvUser2, pState->moffStream, szCmd, 1, &cbRead);
1378 if (vrc != VERR_EOF)
1379 {
1380 LogRel(("Teleporter: Draining teleporterTcpOpRead -> %Rrc\n", vrc));
1381 teleporterTcpWriteNACK(pState, vrc);
1382 break;
1383 }
1384
1385 vrc = teleporterTcpWriteACK(pState);
1386 }
1387 else if (!strcmp(szCmd, "cancel"))
1388 {
1389 /* Don't ACK this. */
1390 LogRel(("Teleporter: Received cancel command.\n"));
1391 vrc = VERR_SSM_CANCELLED;
1392 }
1393 else if (!strcmp(szCmd, "lock-media"))
1394 {
1395 hrc = pState->mpControl->LockMedia();
1396 if (SUCCEEDED(hrc))
1397 {
1398 pState->mfLockedMedia = true;
1399 vrc = teleporterTcpWriteACK(pState);
1400 }
1401 else
1402 {
1403 vrc = VERR_FILE_LOCK_FAILED;
1404 teleporterTcpWriteNACK(pState, vrc);
1405 }
1406 }
1407 else if ( !strcmp(szCmd, "hand-over-resume")
1408 || !strcmp(szCmd, "hand-over-paused"))
1409 {
1410 /*
1411 * Point of no return.
1412 *
1413 * Note! Since we cannot tell whether a VMR3Resume failure is
1414 * destructive for the source or not, we have little choice
1415 * but to ACK it first and take any failures locally.
1416 *
1417 * Ideally, we should try resume it first and then ACK (or
1418 * NACK) the request since this would reduce latency and
1419 * make it possible to recover from some VMR3Resume failures.
1420 */
1421 if ( SUCCEEDED(pState->mptrProgress->NotifyPointOfNoReturn())
1422 && pState->mfLockedMedia)
1423 {
1424 vrc = teleporterTcpWriteACK(pState);
1425 if (RT_SUCCESS(vrc))
1426 {
1427 if (!strcmp(szCmd, "hand-over-resume"))
1428 vrc = pState->mpVMM->pfnVMR3Resume(pState->mpUVM, VMRESUMEREASON_TELEPORTED);
1429 else
1430 pState->mptrConsole->i_setMachineState(MachineState_Paused);
1431 fDone = true;
1432 break;
1433 }
1434 }
1435 else
1436 {
1437 vrc = pState->mfLockedMedia ? VERR_WRONG_ORDER : VERR_SSM_CANCELLED;
1438 teleporterTcpWriteNACK(pState, vrc);
1439 }
1440 }
1441 else
1442 {
1443 LogRel(("Teleporter: Unknown command '%s' (%.*Rhxs)\n", szCmd, strlen(szCmd), szCmd));
1444 vrc = VERR_NOT_IMPLEMENTED;
1445 teleporterTcpWriteNACK(pState, vrc);
1446 }
1447
1448 if (RT_FAILURE(vrc))
1449 break;
1450 }
1451
1452 if (RT_SUCCESS(vrc) && !fDone)
1453 vrc = VERR_WRONG_ORDER;
1454 if (RT_FAILURE(vrc))
1455 teleporterTrgUnlockMedia(pState);
1456
1457 pState->mRc = vrc;
1458 pState->mhSocket = NIL_RTSOCKET;
1459 LogFlowFunc(("returns mRc=%Rrc\n", vrc));
1460 return VERR_TCP_SERVER_STOP;
1461}
1462
Note: See TracBrowser for help on using the repository browser.

© 2023 Oracle
ContactPrivacy policyTerms of Use