VirtualBox

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

Last change on this file since 105381 was 98278, checked in by vboxsync, 23 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
Line 
1/* $Id: ConsoleImplTeleporter.cpp 98278 2023-01-24 11:55:00Z vboxsync $ */
2/** @file
3 * VBox Console COM Class implementation, The Teleporter Part.
4 */
5
6/*
7 * Copyright (C) 2010-2023 Oracle and/or its affiliates.
8 *
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
26 */
27
28
29/*********************************************************************************************************************************
30* Header Files *
31*********************************************************************************************************************************/
32#define LOG_GROUP LOG_GROUP_MAIN_CONSOLE
33#include "LoggingNew.h"
34
35#include "ConsoleImpl.h"
36#include "ProgressImpl.h"
37#include "Global.h"
38#include "StringifyEnums.h"
39
40#include "AutoCaller.h"
41#include "HashedPw.h"
42
43#include <iprt/asm.h>
44#include <iprt/err.h>
45#include <iprt/rand.h>
46#include <iprt/socket.h>
47#include <iprt/tcp.h>
48#include <iprt/timer.h>
49
50#include <VBox/vmm/vmapi.h>
51#include <VBox/vmm/ssm.h>
52#include <VBox/vmm/vmmr3vtable.h>
53#include <VBox/err.h>
54#include <VBox/version.h>
55#include <VBox/com/string.h>
56#include "VBox/com/ErrorInfo.h"
57
58
59/*********************************************************************************************************************************
60* Structures and Typedefs *
61*********************************************************************************************************************************/
62/**
63 * Base class for the teleporter state.
64 *
65 * These classes are used as advanced structs, not as proper classes.
66 */
67class TeleporterState
68{
69public:
70 ComPtr<Console> mptrConsole;
71 PUVM mpUVM;
72 PCVMMR3VTABLE mpVMM;
73 ComObjPtr<Progress> mptrProgress;
74 Utf8Str mstrPassword;
75 bool const mfIsSource;
76
77 /** @name stream stuff
78 * @{ */
79 RTSOCKET mhSocket;
80 uint64_t moffStream;
81 uint32_t mcbReadBlock;
82 bool volatile mfStopReading;
83 bool volatile mfEndOfStream;
84 bool volatile mfIOError;
85 /** @} */
86
87 TeleporterState(Console *pConsole, PUVM pUVM, PCVMMR3VTABLE pVMM, Progress *pProgress, bool fIsSource)
88 : mptrConsole(pConsole)
89 , mpUVM(pUVM)
90 , mpVMM(pVMM)
91 , mptrProgress(pProgress)
92 , mfIsSource(fIsSource)
93 , mhSocket(NIL_RTSOCKET)
94 , moffStream(UINT64_MAX / 2)
95 , mcbReadBlock(0)
96 , mfStopReading(false)
97 , mfEndOfStream(false)
98 , mfIOError(false)
99 {
100 pVMM->pfnVMR3RetainUVM(mpUVM);
101 }
102
103 ~TeleporterState()
104 {
105 if (mpVMM)
106 mpVMM->pfnVMR3ReleaseUVM(mpUVM);
107 mpUVM = NULL;
108 }
109};
110
111
112/**
113 * Teleporter state used by the source side.
114 */
115class TeleporterStateSrc : public TeleporterState
116{
117public:
118 Utf8Str mstrHostname;
119 uint32_t muPort;
120 uint32_t mcMsMaxDowntime;
121 MachineState_T menmOldMachineState;
122 bool mfSuspendedByUs;
123 bool mfUnlockedMedia;
124
125 TeleporterStateSrc(Console *pConsole, PUVM pUVM, PCVMMR3VTABLE pVMM, Progress *pProgress, MachineState_T enmOldMachineState)
126 : TeleporterState(pConsole, pUVM, pVMM, pProgress, true /*fIsSource*/)
127 , muPort(UINT32_MAX)
128 , mcMsMaxDowntime(250)
129 , menmOldMachineState(enmOldMachineState)
130 , mfSuspendedByUs(false)
131 , mfUnlockedMedia(false)
132 {
133 }
134};
135
136
137/**
138 * Teleporter state used by the destination side.
139 */
140class TeleporterStateTrg : public TeleporterState
141{
142public:
143 IMachine *mpMachine;
144 IInternalMachineControl *mpControl;
145 PRTTCPSERVER mhServer;
146 PRTTIMERLR mphTimerLR;
147 bool mfLockedMedia;
148 int mRc;
149 Utf8Str mErrorText;
150
151 TeleporterStateTrg(Console *pConsole, PUVM pUVM, PCVMMR3VTABLE pVMM, Progress *pProgress,
152 IMachine *pMachine, IInternalMachineControl *pControl,
153 PRTTIMERLR phTimerLR, bool fStartPaused)
154 : TeleporterState(pConsole, pUVM, pVMM, pProgress, false /*fIsSource*/)
155 , mpMachine(pMachine)
156 , mpControl(pControl)
157 , mhServer(NULL)
158 , mphTimerLR(phTimerLR)
159 , mfLockedMedia(false)
160 , mRc(VINF_SUCCESS)
161 , mErrorText()
162 {
163 RT_NOREF(fStartPaused); /** @todo figure out why fStartPaused isn't used */
164 }
165};
166
167
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 */
174typedef struct TELEPORTERTCPHDR
175{
176 /** Magic value. */
177 uint32_t u32Magic;
178 /** The size of the data block following this header.
179 * 0 indicates the end of the stream, while UINT32_MAX indicates
180 * cancelation. */
181 uint32_t cb;
182} TELEPORTERTCPHDR;
183/** Magic value for TELEPORTERTCPHDR::u32Magic. (Egberto Gismonti Amin) */
184#define TELEPORTERTCPHDR_MAGIC UINT32_C(0x19471205)
185/** The max block size. */
186#define TELEPORTERTCPHDR_MAX_SIZE UINT32_C(0x00fffff8)
187
188
189/*********************************************************************************************************************************
190* Global Variables *
191*********************************************************************************************************************************/
192static const char g_szWelcome[] = "VirtualBox-Teleporter-1.0\n";
193
194
195/**
196 * Reads a string from the socket.
197 *
198 * @returns VBox status code.
199 *
200 * @param pState The teleporter state structure.
201 * @param pszBuf The output buffer.
202 * @param cchBuf The size of the output buffer.
203 *
204 */
205static int teleporterTcpReadLine(TeleporterState *pState, char *pszBuf, size_t cchBuf)
206{
207 char *pszStart = pszBuf;
208 RTSOCKET hSocket = pState->mhSocket;
209
210 AssertReturn(cchBuf > 1, VERR_INTERNAL_ERROR);
211 *pszBuf = '\0';
212
213 /* dead simple approach. */
214 for (;;)
215 {
216 char ch;
217 int vrc = RTTcpRead(hSocket, &ch, sizeof(ch), NULL);
218 if (RT_FAILURE(vrc))
219 {
220 LogRel(("Teleporter: RTTcpRead -> %Rrc while reading string ('%s')\n", vrc, pszStart));
221 return vrc;
222 }
223 if ( ch == '\n'
224 || ch == '\0')
225 return VINF_SUCCESS;
226 if (cchBuf <= 1)
227 {
228 LogRel(("Teleporter: String buffer overflow: '%s'\n", pszStart));
229 return VERR_BUFFER_OVERFLOW;
230 }
231 *pszBuf++ = ch;
232 *pszBuf = '\0';
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.
242 * @param pState The teleporter source state.
243 * @param pszWhich Which ACK is this this?
244 * @param pszNAckMsg Optional NACK message.
245 *
246 * @remarks the setError laziness forces this to be a Console member.
247 */
248HRESULT
249Console::i_teleporterSrcReadACK(TeleporterStateSrc *pState, const char *pszWhich, const char *pszNAckMsg /*= NULL*/)
250{
251 char szMsg[256];
252 int vrc = teleporterTcpReadLine(pState, szMsg, sizeof(szMsg));
253 if (RT_FAILURE(vrc))
254 return setErrorBoth(E_FAIL, vrc, tr("Failed reading ACK(%s): %Rrc"), pszWhich, vrc);
255
256 if (!strcmp(szMsg, "ACK"))
257 return S_OK;
258
259 if (!strncmp(szMsg, RT_STR_TUPLE("NACK=")))
260 {
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)
268 {
269 /*
270 * Well formed NACK, transform it into an error.
271 */
272 if (pszNAckMsg)
273 {
274 LogRel(("Teleporter: %s: NACK=%Rrc (%d)\n", pszWhich, vrc2, vrc2));
275 return setError(E_FAIL, pszNAckMsg);
276 }
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);
292 }
293
294 if (pszMsgText)
295 pszMsgText[-1] = ';';
296 }
297 return setError(E_FAIL, tr("%s: Expected ACK or NACK, got '%s'"), pszWhich, szMsg);
298}
299
300
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 *
306 * @param pState The teleporter source state.
307 * @param pszCommand The command.
308 * @param fWaitForAck Whether to wait for the ACK.
309 *
310 * @remarks the setError laziness forces this to be a Console member.
311 */
312HRESULT Console::i_teleporterSrcSubmitCommand(TeleporterStateSrc *pState, const char *pszCommand, bool fWaitForAck /*= true*/)
313{
314 int vrc = RTTcpSgWriteL(pState->mhSocket, 2, pszCommand, strlen(pszCommand), "\n", sizeof("\n") - 1);
315 if (RT_FAILURE(vrc))
316 return setErrorBoth(E_FAIL, vrc, tr("Failed writing command '%s': %Rrc"), pszCommand, vrc);
317 if (!fWaitForAck)
318 return S_OK;
319 return i_teleporterSrcReadACK(pState, pszCommand);
320}
321
322
323/**
324 * @copydoc SSMSTRMOPS::pfnWrite
325 */
326static DECLCALLBACK(int) teleporterTcpOpWrite(void *pvUser, uint64_t offStream, const void *pvBuf, size_t cbToWrite)
327{
328 RT_NOREF(offStream);
329 TeleporterState *pState = (TeleporterState *)pvUser;
330
331 AssertReturn(cbToWrite > 0, VINF_SUCCESS);
332 AssertReturn(cbToWrite < UINT32_MAX, VERR_OUT_OF_RANGE);
333 AssertReturn(pState->mfIsSource, VERR_INVALID_HANDLE);
334
335 for (;;)
336 {
337 TELEPORTERTCPHDR Hdr;
338 Hdr.u32Magic = TELEPORTERTCPHDR_MAGIC;
339 Hdr.cb = RT_MIN((uint32_t)cbToWrite, TELEPORTERTCPHDR_MAX_SIZE);
340 int vrc = RTTcpSgWriteL(pState->mhSocket, 2, &Hdr, sizeof(Hdr), pvBuf, (size_t)Hdr.cb);
341 if (RT_FAILURE(vrc))
342 {
343 LogRel(("Teleporter/TCP: Write error: %Rrc (cb=%#x)\n", vrc, Hdr.cb));
344 return vrc;
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;
353 }
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 *
366 * @param pState The teleporter state data.
367 */
368static int teleporterTcpReadSelect(TeleporterState *pState)
369{
370 int vrc;
371 do
372 {
373 vrc = RTTcpSelectOne(pState->mhSocket, 1000);
374 if (RT_FAILURE(vrc) && vrc != VERR_TIMEOUT)
375 {
376 pState->mfIOError = true;
377 LogRel(("Teleporter/TCP: Header select error: %Rrc\n", vrc));
378 break;
379 }
380 if (pState->mfStopReading)
381 {
382 vrc = VERR_EOF;
383 break;
384 }
385 } while (vrc == VERR_TIMEOUT);
386 return vrc;
387}
388
389
390/**
391 * @copydoc SSMSTRMOPS::pfnRead
392 */
393static DECLCALLBACK(int) teleporterTcpOpRead(void *pvUser, uint64_t offStream, void *pvBuf, size_t cbToRead, size_t *pcbRead)
394{
395 RT_NOREF(offStream);
396 TeleporterState *pState = (TeleporterState *)pvUser;
397 AssertReturn(!pState->mfIsSource, VERR_INVALID_HANDLE);
398
399 for (;;)
400 {
401 int vrc;
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)
418 {
419 vrc = teleporterTcpReadSelect(pState);
420 if (RT_FAILURE(vrc))
421 return vrc;
422 TELEPORTERTCPHDR Hdr;
423 vrc = RTTcpRead(pState->mhSocket, &Hdr, sizeof(Hdr), NULL);
424 if (RT_FAILURE(vrc))
425 {
426 pState->mfIOError = true;
427 LogRel(("Teleporter/TCP: Header read error: %Rrc\n", vrc));
428 return vrc;
429 }
430
431 if (RT_UNLIKELY( Hdr.u32Magic != TELEPORTERTCPHDR_MAGIC
432 || Hdr.cb > TELEPORTERTCPHDR_MAX_SIZE
433 || Hdr.cb == 0))
434 {
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 }
444 pState->mfIOError = true;
445 LogRel(("Teleporter/TCP: Invalid block: u32Magic=%#x cb=%#x\n", Hdr.u32Magic, Hdr.cb));
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 */
457 vrc = teleporterTcpReadSelect(pState);
458 if (RT_FAILURE(vrc))
459 return vrc;
460 uint32_t cb = (uint32_t)RT_MIN(pState->mcbReadBlock, cbToRead);
461 vrc = RTTcpRead(pState->mhSocket, pvBuf, cb, pcbRead);
462 if (RT_FAILURE(vrc))
463 {
464 pState->mfIOError = true;
465 LogRel(("Teleporter/TCP: Data read error: %Rrc (cb=%#x)\n", vrc, cb));
466 return vrc;
467 }
468 if (pcbRead)
469 {
470 cb = (uint32_t)*pcbRead;
471 pState->moffStream += cb;
472 pState->mcbReadBlock -= cb;
473 return VINF_SUCCESS;
474 }
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;
483 }
484}
485
486
487/**
488 * @copydoc SSMSTRMOPS::pfnSeek
489 */
490static DECLCALLBACK(int) teleporterTcpOpSeek(void *pvUser, int64_t offSeek, unsigned uMethod, uint64_t *poffActual)
491{
492 RT_NOREF(pvUser, offSeek, uMethod, poffActual);
493 return VERR_NOT_SUPPORTED;
494}
495
496
497/**
498 * @copydoc SSMSTRMOPS::pfnTell
499 */
500static DECLCALLBACK(uint64_t) teleporterTcpOpTell(void *pvUser)
501{
502 TeleporterState *pState = (TeleporterState *)pvUser;
503 return pState->moffStream;
504}
505
506
507/**
508 * @copydoc SSMSTRMOPS::pfnSize
509 */
510static DECLCALLBACK(int) teleporterTcpOpSize(void *pvUser, uint64_t *pcb)
511{
512 RT_NOREF(pvUser, pcb);
513 return VERR_NOT_SUPPORTED;
514}
515
516
517/**
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 */
527 int vrc = RTTcpSelectOne(pState->mhSocket, 0);
528 if (vrc != VERR_TIMEOUT)
529 {
530 if (RT_SUCCESS(vrc))
531 {
532 LogRel(("Teleporter/TCP: Incoming data detect by IsOk, assuming it is a cancellation NACK.\n"));
533 vrc = VERR_SSM_CANCELLED;
534 }
535 else
536 LogRel(("Teleporter/TCP: RTTcpSelectOne -> %Rrc (IsOk).\n", vrc));
537 return vrc;
538 }
539 }
540
541 return VINF_SUCCESS;
542}
543
544
545/**
546 * @copydoc SSMSTRMOPS::pfnClose
547 */
548static DECLCALLBACK(int) teleporterTcpOpClose(void *pvUser, bool fCancelled)
549{
550 TeleporterState *pState = (TeleporterState *)pvUser;
551
552 if (pState->mfIsSource)
553 {
554 TELEPORTERTCPHDR EofHdr;
555 EofHdr.u32Magic = TELEPORTERTCPHDR_MAGIC;
556 EofHdr.cb = fCancelled ? UINT32_MAX : 0;
557 int vrc = RTTcpWrite(pState->mhSocket, &EofHdr, sizeof(EofHdr));
558 if (RT_FAILURE(vrc))
559 {
560 LogRel(("Teleporter/TCP: EOF Header write error: %Rrc\n", vrc));
561 return vrc;
562 }
563 }
564 else
565 {
566 ASMAtomicWriteBool(&pState->mfStopReading, true);
567 }
568
569 return VINF_SUCCESS;
570}
571
572
573/**
574 * Method table for a TCP based stream.
575 */
576static SSMSTRMOPS const g_teleporterTcpOps =
577{
578 SSMSTRMOPS_VERSION,
579 teleporterTcpOpWrite,
580 teleporterTcpOpRead,
581 teleporterTcpOpSeek,
582 teleporterTcpOpTell,
583 teleporterTcpOpSize,
584 teleporterTcpOpIsOk,
585 teleporterTcpOpClose,
586 SSMSTRMOPS_VERSION
587};
588
589
590/**
591 * Progress cancelation callback.
592 */
593static void teleporterProgressCancelCallback(void *pvUser)
594{
595 TeleporterState *pState = (TeleporterState *)pvUser;
596 pState->mpVMM->pfnSSMR3Cancel(pState->mpUVM);
597 if (!pState->mfIsSource)
598 {
599 TeleporterStateTrg *pStateTrg = (TeleporterStateTrg *)pState;
600 RTTcpServerShutdown(pStateTrg->mhServer);
601 }
602}
603
604/**
605 * @copydoc PFNVMPROGRESS
606 */
607static DECLCALLBACK(int) teleporterProgressCallback(PUVM pUVM, unsigned uPercent, void *pvUser)
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. */
616 BOOL fCanceled;
617 hrc = pState->mptrProgress->COMGETTER(Canceled)(&fCanceled);
618 if (SUCCEEDED(hrc) && fCanceled)
619 {
620 pState->mpVMM->pfnSSMR3Cancel(pState->mpUVM);
621 return VERR_SSM_CANCELLED;
622 }
623 }
624 }
625
626 NOREF(pUVM);
627 return VINF_SUCCESS;
628}
629
630
631/**
632 * @copydoc FNRTTIMERLR
633 */
634static DECLCALLBACK(void) teleporterDstTimeout(RTTIMERLR hTimerLR, void *pvUser, uint64_t iTick)
635{
636 RT_NOREF(hTimerLR, iTick);
637 /* This is harmless for any open connections. */
638 RTTcpServerShutdown((PRTTCPSERVER)pvUser);
639}
640
641
642/**
643 * Do the teleporter.
644 *
645 * @returns VBox status code.
646 * @param pState The teleporter state.
647 */
648HRESULT Console::i_teleporterSrc(TeleporterStateSrc *pState)
649{
650 AutoCaller autoCaller(this);
651 if (FAILED(autoCaller.hrc())) return autoCaller.hrc();
652
653 /*
654 * Wait for Console::Teleport to change the state.
655 */
656 { AutoWriteLock autoLock(this COMMA_LOCKVAL_SRC_POS); }
657
658 BOOL fCanceled = TRUE;
659 HRESULT hrc = pState->mptrProgress->COMGETTER(Canceled)(&fCanceled);
660 if (FAILED(hrc))
661 return hrc;
662 if (fCanceled)
663 return setError(E_FAIL, tr("canceled"));
664
665 /*
666 * Try connect to the destination machine, disable Nagle.
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);
670 if (RT_FAILURE(vrc))
671 return setErrorBoth(E_FAIL, vrc, tr("Failed to connect to port %u on '%s': %Rrc"),
672 pState->muPort, pState->mstrHostname.c_str(), vrc);
673 vrc = RTTcpSetSendCoalescing(pState->mhSocket, false /*fEnable*/);
674 AssertRC(vrc);
675
676 /* Read and check the welcome message. */
677 char szLine[RT_MAX(128, sizeof(g_szWelcome))];
678 RT_ZERO(szLine);
679 vrc = RTTcpRead(pState->mhSocket, szLine, sizeof(g_szWelcome) - 1, NULL);
680 if (RT_FAILURE(vrc))
681 return setErrorBoth(E_FAIL, vrc, tr("Failed to read welcome message: %Rrc"), vrc);
682 if (strcmp(szLine, g_szWelcome))
683 return setError(E_FAIL, tr("Unexpected welcome %.*Rhxs"), sizeof(g_szWelcome) - 1, szLine);
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))
689 return setErrorBoth(E_FAIL, vrc, tr("Failed to send password: %Rrc"), vrc);
690
691 /* ACK */
692 hrc = i_teleporterSrcReadACK(pState, "password", tr("Invalid password"));
693 if (FAILED(hrc))
694 return hrc;
695
696 /*
697 * Start loading the state.
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.
702 */
703 hrc = i_teleporterSrcSubmitCommand(pState, "load");
704 if (FAILED(hrc))
705 return hrc;
706
707 RTSocketRetain(pState->mhSocket);
708 void *pvUser = static_cast<void *>(static_cast<TeleporterState *>(pState));
709 vrc = pState->mpVMM->pfnVMR3Teleport(pState->mpUVM,
710 pState->mcMsMaxDowntime,
711 &g_teleporterTcpOps, pvUser,
712 teleporterProgressCallback, pvUser,
713 &pState->mfSuspendedByUs);
714 RTSocketRelease(pState->mhSocket);
715 if (RT_FAILURE(vrc))
716 {
717 if ( vrc == VERR_SSM_CANCELLED
718 && RT_SUCCESS(RTTcpSelectOne(pState->mhSocket, 1)))
719 {
720 hrc = i_teleporterSrcReadACK(pState, "load-complete");
721 if (FAILED(hrc))
722 return hrc;
723 }
724 return setErrorBoth(E_FAIL, vrc, "VMR3Teleport -> %Rrc", vrc);
725 }
726
727 hrc = i_teleporterSrcReadACK(pState, "load-complete");
728 if (FAILED(hrc))
729 return hrc;
730
731 /*
732 * We're at the point of no return.
733 */
734 if (FAILED(pState->mptrProgress->NotifyPointOfNoReturn()))
735 {
736 i_teleporterSrcSubmitCommand(pState, "cancel", false /*fWaitForAck*/);
737 return E_FAIL;
738 }
739
740 /*
741 * Hand over any media which we might be sharing.
742 *
743 * Note! This is only important on localhost teleportations.
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
751 hrc = i_teleporterSrcSubmitCommand(pState, "lock-media");
752 if (FAILED(hrc))
753 return hrc;
754
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)
760 hrc = i_teleporterSrcSubmitCommand(pState, "hand-over-paused");
761 else
762 hrc = i_teleporterSrcSubmitCommand(pState, "hand-over-resume");
763 if (FAILED(hrc))
764 return hrc;
765
766 /*
767 * teleporterSrcThreadWrapper will do the automatic power off because it
768 * has to release the AutoVMCaller.
769 */
770 return S_OK;
771}
772
773
774/**
775 * Static thread method wrapper.
776 *
777 * @returns VINF_SUCCESS (ignored).
778 * @param hThreadSelf The thread.
779 * @param pvUser Pointer to a TeleporterStateSrc instance.
780 */
781/*static*/ DECLCALLBACK(int)
782Console::i_teleporterSrcThreadWrapper(RTTHREAD hThreadSelf, void *pvUser)
783{
784 RT_NOREF(hThreadSelf);
785 TeleporterStateSrc *pState = (TeleporterStateSrc *)pvUser;
786
787 /*
788 * Console::teleporterSrc does the work, we just grab onto the VM handle
789 * and do the cleanups afterwards.
790 */
791 SafeVMPtr ptrVM(pState->mptrConsole);
792 HRESULT hrc = ptrVM.hrc();
793
794 if (SUCCEEDED(hrc))
795 hrc = pState->mptrConsole->i_teleporterSrc(pState);
796
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
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))
807 pState->mptrProgress->i_notifyComplete(hrc);
808
809 /* We can no longer be canceled (success), or it doesn't matter any longer (failure). */
810 pState->mptrProgress->i_setCancelCallback(NULL, NULL);
811
812 /*
813 * Write lock the console before resetting mptrCancelableProgress and
814 * fixing the state.
815 */
816 AutoWriteLock autoLock(pState->mptrConsole COMMA_LOCKVAL_SRC_POS);
817 pState->mptrConsole->mptrCancelableProgress.setNull();
818
819 VMSTATE const enmVMState = pState->mpVMM->pfnVMR3GetStateU(pState->mpUVM);
820 MachineState_T const enmMachineState = pState->mptrConsole->mMachineState;
821 if (SUCCEEDED(hrc))
822 {
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 */
829 AssertLogRelMsg(enmVMState == VMSTATE_SUSPENDED, ("%s\n", pState->mpVMM->pfnVMR3GetStateName(enmVMState)));
830 AssertLogRelMsg(enmMachineState == MachineState_TeleportingPausedVM, ("%s\n", ::stringifyMachineState(enmMachineState)));
831
832 ptrVM.release();
833
834 pState->mptrConsole->mVMIsAlreadyPoweringOff = true; /* (Make sure we stick in the TeleportingPausedVM state.) */
835 autoLock.release();
836
837 hrc = pState->mptrConsole->i_powerDown();
838
839 autoLock.acquire();
840 pState->mptrConsole->mVMIsAlreadyPoweringOff = false;
841
842 pState->mptrProgress->i_notifyComplete(hrc);
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 )
856 {
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
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:
887 case VMSTATE_SOFT_RESETTING:
888 case VMSTATE_SOFT_RESETTING_LS:
889 Assert(!pState->mfSuspendedByUs);
890 Assert(!pState->mfUnlockedMedia);
891 pState->mptrConsole->i_setMachineState(MachineState_Running);
892 break;
893
894 case VMSTATE_GURU_MEDITATION:
895 case VMSTATE_GURU_MEDITATION_LS:
896 pState->mptrConsole->i_setMachineState(MachineState_Stuck);
897 break;
898
899 case VMSTATE_FATAL_ERROR:
900 case VMSTATE_FATAL_ERROR_LS:
901 pState->mptrConsole->i_setMachineState(MachineState_Paused);
902 break;
903
904 default:
905 AssertMsgFailed(("%s\n", pState->mpVMM->pfnVMR3GetStateName(enmVMState)));
906 RT_FALL_THRU();
907 case VMSTATE_SUSPENDED:
908 case VMSTATE_SUSPENDED_LS:
909 case VMSTATE_SUSPENDING:
910 case VMSTATE_SUSPENDING_LS:
911 case VMSTATE_SUSPENDING_EXT_LS:
912 if (!pState->mfUnlockedMedia)
913 {
914 pState->mptrConsole->i_setMachineState(MachineState_Paused);
915 if (pState->mfSuspendedByUs)
916 {
917 autoLock.release();
918 int vrc = pState->mpVMM->pfnVMR3Resume(pState->mpUVM, VMRESUMEREASON_TELEPORT_FAILED);
919 AssertLogRelMsgRC(vrc, ("VMR3Resume -> %Rrc\n", vrc));
920 autoLock.acquire();
921 }
922 }
923 else
924 {
925 /* Faking a guru meditation is the best I can think of doing here... */
926 pState->mptrConsole->i_setMachineState(MachineState_Stuck);
927 }
928 break;
929 }
930 }
931 }
932 autoLock.release();
933
934 /*
935 * Cleanup.
936 */
937 Assert(pState->mhSocket == NIL_RTSOCKET);
938 delete pState;
939
940 return VINF_SUCCESS; /* ignored */
941}
942
943
944/**
945 * Start teleporter to the specified target.
946 *
947 * @returns COM status code.
948 *
949 * @param aHostname The name of the target host.
950 * @param aTcpport The TCP port number.
951 * @param aPassword The password.
952 * @param aMaxDowntime Max allowed "downtime" in milliseconds.
953 * @param aProgress Where to return the progress object.
954 */
955HRESULT Console::teleport(const com::Utf8Str &aHostname, ULONG aTcpport, const com::Utf8Str &aPassword,
956 ULONG aMaxDowntime, ComPtr<IProgress> &aProgress)
957{
958 /*
959 * Validate parameters, check+hold object status, write lock the object
960 * and validate the state.
961 */
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
970 AutoCaller autoCaller(this);
971 if (FAILED(autoCaller.hrc())) return autoCaller.hrc();
972
973 AutoWriteLock autoLock(this COMMA_LOCKVAL_SRC_POS);
974 LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
975
976 switch (mMachineState)
977 {
978 case MachineState_Running:
979 case MachineState_Paused:
980 break;
981
982 default:
983 return setError(VBOX_E_INVALID_VM_STATE, tr("Invalid machine state: %s (must be Running or Paused)"),
984 Global::stringifyMachineState(mMachineState));
985 }
986
987
988 /*
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.
991 */
992 LogFlowThisFunc(("Initiating TELEPORT request...\n"));
993
994 ComObjPtr<Progress> ptrProgress;
995 HRESULT hrc = ptrProgress.createObject();
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;
1002
1003 TeleporterStateSrc *pState = new TeleporterStateSrc(this, mpUVM, mpVMM, ptrProgress, mMachineState);
1004 pState->mstrPassword = strPassword;
1005 pState->mstrHostname = aHostname;
1006 pState->muPort = aTcpport;
1007 pState->mcMsMaxDowntime = aMaxDowntime;
1008
1009 void *pvUser = static_cast<void *>(static_cast<TeleporterState *>(pState));
1010 ptrProgress->i_setCancelCallback(teleporterProgressCancelCallback, pvUser);
1011
1012 int vrc = RTThreadCreate(NULL, Console::i_teleporterSrcThreadWrapper, (void *)pState, 0 /*cbStack*/,
1013 RTTHREADTYPE_EMULATION, 0 /*fFlags*/, "Teleport");
1014 if (RT_SUCCESS(vrc))
1015 {
1016 if (mMachineState == MachineState_Running)
1017 hrc = i_setMachineState(MachineState_Teleporting);
1018 else
1019 hrc = i_setMachineState(MachineState_TeleportingPausedVM);
1020 if (SUCCEEDED(hrc))
1021 {
1022 ptrProgress.queryInterfaceTo(aProgress.asOutParam());
1023 mptrCancelableProgress = aProgress;
1024 }
1025 else
1026 ptrProgress->Cancel();
1027 }
1028 else
1029 {
1030 ptrProgress->i_setCancelCallback(NULL, NULL);
1031 delete pState;
1032 hrc = setErrorBoth(E_FAIL, vrc, "RTThreadCreate -> %Rrc", vrc);
1033 }
1034
1035 return hrc;
1036}
1037
1038
1039/**
1040 * Creates a TCP server that listens for the source machine and passes control
1041 * over to Console::teleporterTrgServeConnection().
1042 *
1043 * @returns VBox status code.
1044 * @param pUVM The user-mode VM handle
1045 * @param pVMM The VMM vtable.
1046 * @param pMachine The IMachine for the virtual machine.
1047 * @param pErrorMsg Pointer to the error string for VMSetError.
1048 * @param fStartPaused Whether to start it in the Paused (true) or
1049 * Running (false) state,
1050 * @param pProgress Pointer to the progress object.
1051 * @param pfPowerOffOnFailure Whether the caller should power off
1052 * the VM on failure.
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...
1056 */
1057HRESULT Console::i_teleporterTrg(PUVM pUVM, PCVMMR3VTABLE pVMM, IMachine *pMachine, Utf8Str *pErrorMsg, bool fStartPaused,
1058 Progress *pProgress, bool *pfPowerOffOnFailure)
1059{
1060 LogThisFunc(("pUVM=%p pVMM=%p pMachine=%p fStartPaused=%RTbool pProgress=%p\n", pUVM, pVMM, pMachine, fStartPaused, pProgress));
1061
1062 *pfPowerOffOnFailure = true;
1063
1064 /*
1065 * Get the config.
1066 */
1067 ULONG uPort;
1068 HRESULT hrc = pMachine->COMGETTER(TeleporterPort)(&uPort);
1069 if (FAILED(hrc))
1070 return hrc;
1071 ULONG const uPortOrg = uPort;
1072
1073 Bstr bstrAddress;
1074 hrc = pMachine->COMGETTER(TeleporterAddress)(bstrAddress.asOutParam());
1075 if (FAILED(hrc))
1076 return hrc;
1077 Utf8Str strAddress(bstrAddress);
1078 const char *pszAddress = strAddress.isEmpty() ? NULL : strAddress.c_str();
1079
1080 Bstr bstrPassword;
1081 hrc = pMachine->COMGETTER(TeleporterPassword)(bstrPassword.asOutParam());
1082 if (FAILED(hrc))
1083 return hrc;
1084 Utf8Str strPassword(bstrPassword);
1085 strPassword.append('\n'); /* To simplify password checking. */
1086
1087 /*
1088 * Create the TCP server.
1089 */
1090 int vrc = VINF_SUCCESS; /* Shut up MSC */
1091 PRTTCPSERVER hServer = NULL; /* ditto */
1092 if (uPort)
1093 vrc = RTTcpServerCreateEx(pszAddress, uPort, &hServer);
1094 else
1095 {
1096 for (int cTries = 10240; cTries > 0; cTries--)
1097 {
1098 uPort = RTRandU32Ex(cTries >= 8192 ? 49152 : 1024, 65534);
1099 vrc = RTTcpServerCreateEx(pszAddress, uPort, &hServer);
1100 if (vrc != VERR_NET_ADDRESS_IN_USE)
1101 break;
1102 }
1103 if (RT_SUCCESS(vrc))
1104 {
1105 hrc = pMachine->COMSETTER(TeleporterPort)(uPort);
1106 if (FAILED(hrc))
1107 {
1108 RTTcpServerDestroy(hServer);
1109 return hrc;
1110 }
1111 }
1112 }
1113 if (RT_FAILURE(vrc))
1114 return setErrorBoth(E_FAIL, vrc, tr("RTTcpServerCreateEx failed with status %Rrc"), vrc);
1115
1116 /*
1117 * Create a one-shot timer for timing out after 5 mins.
1118 */
1119 RTTIMERLR hTimerLR;
1120 vrc = RTTimerLRCreateEx(&hTimerLR, 0 /*ns*/, RTTIMER_FLAGS_CPU_ANY, teleporterDstTimeout, hServer);
1121 if (RT_SUCCESS(vrc))
1122 {
1123 vrc = RTTimerLRStart(hTimerLR, 5*60*UINT64_C(1000000000) /*ns*/);
1124 if (RT_SUCCESS(vrc))
1125 {
1126 /*
1127 * Do the job, when it returns we're done.
1128 */
1129 TeleporterStateTrg theState(this, pUVM, pVMM, pProgress, pMachine, mControl, &hTimerLR, fStartPaused);
1130 theState.mstrPassword = strPassword;
1131 theState.mhServer = hServer;
1132
1133 void *pvUser = static_cast<void *>(static_cast<TeleporterState *>(&theState));
1134 if (pProgress->i_setCancelCallback(teleporterProgressCancelCallback, pvUser))
1135 {
1136 LogRel(("Teleporter: Waiting for incoming VM...\n"));
1137 hrc = pProgress->SetNextOperation(Bstr(tr("Waiting for incoming VM")).raw(), 1);
1138 if (SUCCEEDED(hrc))
1139 {
1140 vrc = RTTcpServerListen(hServer, Console::i_teleporterTrgServeConnection, &theState);
1141 pProgress->i_setCancelCallback(NULL, NULL);
1142
1143 if (vrc == VERR_TCP_SERVER_STOP)
1144 {
1145 vrc = theState.mRc;
1146 /* Power off the VM on failure unless the state callback
1147 already did that. */
1148 *pfPowerOffOnFailure = false;
1149 if (RT_SUCCESS(vrc))
1150 hrc = S_OK;
1151 else
1152 {
1153 VMSTATE enmVMState = pVMM->pfnVMR3GetStateU(pUVM);
1154 if ( enmVMState != VMSTATE_OFF
1155 && enmVMState != VMSTATE_POWERING_OFF)
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);
1163 }
1164 }
1165 else if (vrc == VERR_TCP_SERVER_SHUTDOWN)
1166 {
1167 BOOL fCanceled = TRUE;
1168 hrc = pProgress->COMGETTER(Canceled)(&fCanceled);
1169 if (FAILED(hrc) || fCanceled)
1170 hrc = setError(E_FAIL, tr("Teleporting canceled"));
1171 else
1172 hrc = setError(E_FAIL, tr("Teleporter timed out waiting for incoming connection"));
1173 LogRel(("Teleporter: RTTcpServerListen aborted - %Rrc\n", vrc));
1174 }
1175 else
1176 {
1177 hrc = setErrorBoth(E_FAIL, vrc, tr("Unexpected RTTcpServerListen status code %Rrc"), vrc);
1178 LogRel(("Teleporter: Unexpected RTTcpServerListen vrc: %Rrc\n", vrc));
1179 }
1180 }
1181 else
1182 LogThisFunc(("SetNextOperation failed, %Rhrc\n", hrc));
1183 }
1184 else
1185 {
1186 LogThisFunc(("Canceled - check point #1\n"));
1187 hrc = setError(E_FAIL, tr("Teleporting canceled"));
1188 }
1189 }
1190 else
1191 hrc = setErrorBoth(E_FAIL, vrc, "RTTimerLRStart -> %Rrc", vrc);
1192
1193 RTTimerLRDestroy(hTimerLR);
1194 }
1195 else
1196 hrc = setErrorBoth(E_FAIL, vrc, "RTTimerLRCreate -> %Rrc", vrc);
1197 RTTcpServerDestroy(hServer);
1198
1199 /*
1200 * If we change TeleporterPort above, set it back to it's original
1201 * value before returning.
1202 */
1203 if (uPortOrg != uPort)
1204 {
1205 ErrorInfoKeeper Eik;
1206 pMachine->COMSETTER(TeleporterPort)(uPortOrg);
1207 }
1208
1209 return hrc;
1210}
1211
1212
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
1230static int teleporterTcpWriteACK(TeleporterStateTrg *pState, bool fAutomaticUnlock = true)
1231{
1232 int vrc = RTTcpWrite(pState->mhSocket, "ACK\n", sizeof("ACK\n") - 1);
1233 if (RT_FAILURE(vrc))
1234 {
1235 LogRel(("Teleporter: RTTcpWrite(,ACK,) -> %Rrc\n", vrc));
1236 if (fAutomaticUnlock)
1237 teleporterTrgUnlockMedia(pState);
1238 }
1239 return vrc;
1240}
1241
1242
1243static int teleporterTcpWriteNACK(TeleporterStateTrg *pState, int32_t rc2, const char *pszMsgText = NULL)
1244{
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
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);
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;
1266}
1267
1268
1269/**
1270 * @copydoc FNRTTCPSERVE
1271 *
1272 * @returns VINF_SUCCESS or VERR_TCP_SERVER_STOP.
1273 */
1274/*static*/ DECLCALLBACK(int)
1275Console::i_teleporterTrgServeConnection(RTSOCKET hSocket, void *pvUser)
1276{
1277 TeleporterStateTrg *pState = (TeleporterStateTrg *)pvUser;
1278 pState->mhSocket = hSocket;
1279
1280 /*
1281 * Disable Nagle and say hello.
1282 */
1283 int vrc = RTTcpSetSendCoalescing(pState->mhSocket, false /*fEnable*/);
1284 AssertRC(vrc);
1285 vrc = RTTcpWrite(hSocket, g_szWelcome, sizeof(g_szWelcome) - 1);
1286 if (RT_FAILURE(vrc))
1287 {
1288 LogRel(("Teleporter: Failed to write welcome message: %Rrc\n", vrc));
1289 return VINF_SUCCESS;
1290 }
1291
1292 /*
1293 * Password (includes '\n', see i_teleporterTrg).
1294 */
1295 const char *pszPassword = pState->mstrPassword.c_str();
1296 unsigned off = 0;
1297 while (pszPassword[off])
1298 {
1299 char ch;
1300 vrc = RTTcpRead(hSocket, &ch, sizeof(ch), NULL);
1301 if ( RT_FAILURE(vrc)
1302 || pszPassword[off] != ch)
1303 {
1304 if (RT_FAILURE(vrc))
1305 LogRel(("Teleporter: Password read failure (off=%u): %Rrc\n", off, vrc));
1306 else
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 */
1318 teleporterTcpWriteNACK(pState, VERR_AUTHENTICATION_FAILURE);
1319 return VINF_SUCCESS;
1320 }
1321 off++;
1322 }
1323 vrc = teleporterTcpWriteACK(pState);
1324 if (RT_FAILURE(vrc))
1325 return VINF_SUCCESS;
1326
1327 /*
1328 * Update the progress bar, with peer name if available.
1329 */
1330 HRESULT hrc;
1331 RTNETADDR Addr;
1332 vrc = RTTcpGetPeerAddress(hSocket, &Addr);
1333 if (RT_SUCCESS(vrc))
1334 {
1335 LogRel(("Teleporter: Incoming VM from %RTnaddr!\n", &Addr));
1336 hrc = pState->mptrProgress->SetNextOperation(BstrFmt(tr("Teleporting VM from %RTnaddr"), &Addr).raw(), 8);
1337 }
1338 else
1339 {
1340 LogRel(("Teleporter: Incoming VM!\n"));
1341 hrc = pState->mptrProgress->SetNextOperation(Bstr(tr("Teleporting VM")).raw(), 8);
1342 }
1343 AssertMsg(SUCCEEDED(hrc) || hrc == E_FAIL, ("%Rhrc\n", hrc));
1344
1345 /*
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 */
1351 RTTcpServerShutdown(pState->mhServer);
1352 RTTimerLRDestroy(*pState->mphTimerLR);
1353 *pState->mphTimerLR = NIL_RTTIMERLR;
1354
1355 /*
1356 * Command processing loop.
1357 */
1358 bool fDone = false;
1359 for (;;)
1360 {
1361 char szCmd[128];
1362 vrc = teleporterTcpReadLine(pState, szCmd, sizeof(szCmd));
1363 if (RT_FAILURE(vrc))
1364 break;
1365
1366 if (!strcmp(szCmd, "load"))
1367 {
1368 vrc = teleporterTcpWriteACK(pState);
1369 if (RT_FAILURE(vrc))
1370 break;
1371
1372 int vrc2 = pState->mpVMM->pfnVMR3AtErrorRegister(pState->mpUVM, Console::i_genericVMSetErrorCallback,
1373 &pState->mErrorText);
1374 AssertRC(vrc2);
1375 RTSocketRetain(pState->mhSocket); /* For concurrent access by I/O thread and EMT. */
1376 pState->moffStream = 0;
1377
1378 void *pvUser2 = static_cast<void *>(static_cast<TeleporterState *>(pState));
1379 vrc = pState->mpVMM->pfnVMR3LoadFromStream(pState->mpUVM,
1380 &g_teleporterTcpOps, pvUser2,
1381 teleporterProgressCallback, pvUser2,
1382 true /*fTeleporting*/);
1383
1384 RTSocketRelease(pState->mhSocket);
1385 vrc2 = pState->mpVMM->pfnVMR3AtErrorDeregister(pState->mpUVM, Console::i_genericVMSetErrorCallback, &pState->mErrorText);
1386 AssertRC(vrc2);
1387
1388 if (RT_FAILURE(vrc))
1389 {
1390 LogRel(("Teleporter: VMR3LoadFromStream -> %Rrc\n", vrc));
1391 teleporterTcpWriteNACK(pState, vrc, pState->mErrorText.c_str());
1392 break;
1393 }
1394
1395 /* The EOS might not have been read, make sure it is. */
1396 pState->mfStopReading = false;
1397 size_t cbRead;
1398 vrc = teleporterTcpOpRead(pvUser2, pState->moffStream, szCmd, 1, &cbRead);
1399 if (vrc != VERR_EOF)
1400 {
1401 LogRel(("Teleporter: Draining teleporterTcpOpRead -> %Rrc\n", vrc));
1402 teleporterTcpWriteNACK(pState, vrc);
1403 break;
1404 }
1405
1406 vrc = teleporterTcpWriteACK(pState);
1407 }
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 }
1414 else if (!strcmp(szCmd, "lock-media"))
1415 {
1416 hrc = pState->mpControl->LockMedia();
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 }
1428 else if ( !strcmp(szCmd, "hand-over-resume")
1429 || !strcmp(szCmd, "hand-over-paused"))
1430 {
1431 /*
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.
1441 */
1442 if ( SUCCEEDED(pState->mptrProgress->NotifyPointOfNoReturn())
1443 && pState->mfLockedMedia)
1444 {
1445 vrc = teleporterTcpWriteACK(pState);
1446 if (RT_SUCCESS(vrc))
1447 {
1448 if (!strcmp(szCmd, "hand-over-resume"))
1449 vrc = pState->mpVMM->pfnVMR3Resume(pState->mpUVM, VMRESUMEREASON_TELEPORTED);
1450 else
1451 pState->mptrConsole->i_setMachineState(MachineState_Paused);
1452 fDone = true;
1453 break;
1454 }
1455 }
1456 else
1457 {
1458 vrc = pState->mfLockedMedia ? VERR_WRONG_ORDER : VERR_SSM_CANCELLED;
1459 teleporterTcpWriteNACK(pState, vrc);
1460 }
1461 }
1462 else
1463 {
1464 LogRel(("Teleporter: Unknown command '%s' (%.*Rhxs)\n", szCmd, strlen(szCmd), szCmd));
1465 vrc = VERR_NOT_IMPLEMENTED;
1466 teleporterTcpWriteNACK(pState, vrc);
1467 }
1468
1469 if (RT_FAILURE(vrc))
1470 break;
1471 }
1472
1473 if (RT_SUCCESS(vrc) && !fDone)
1474 vrc = VERR_WRONG_ORDER;
1475 if (RT_FAILURE(vrc))
1476 teleporterTrgUnlockMedia(pState);
1477
1478 pState->mRc = vrc;
1479 pState->mhSocket = NIL_RTSOCKET;
1480 LogFlowFunc(("returns mRc=%Rrc\n", vrc));
1481 return VERR_TCP_SERVER_STOP;
1482}
1483
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