VirtualBox

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

Last change on this file since 66629 was 65919, checked in by vboxsync, 8 years ago

gcc 7: fall thru

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