VirtualBox

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

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

Main/src-client: Some more rc -> hrc/vrc stuff found by grep. A build fix. bugref:10223

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

© 2023 Oracle
ContactPrivacy policyTerms of Use