VirtualBox

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

Last change on this file since 39336 was 36041, checked in by vboxsync, 14 years ago

Main/VMM: Use UVM w/ refcounting - part 1.

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