VirtualBox

source: vbox/trunk/src/VBox/Main/src-client/GuestSessionImplTasks.cpp@ 60622

Last change on this file since 60622 was 60622, checked in by vboxsync, 9 years ago

Guest Control: Added proper handling for (VBoxService) toolbox exit codes, resolving various copyto/copyfrom bugs.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 66.6 KB
Line 
1/* $Id: GuestSessionImplTasks.cpp 60622 2016-04-21 13:00:20Z vboxsync $ */
2/** @file
3 * VirtualBox Main - Guest session tasks.
4 */
5
6/*
7 * Copyright (C) 2012-2016 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.215389.xyz. 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 "GuestImpl.h"
23#ifndef VBOX_WITH_GUEST_CONTROL
24# error "VBOX_WITH_GUEST_CONTROL must defined in this file"
25#endif
26#include "GuestSessionImpl.h"
27#include "GuestCtrlImplPrivate.h"
28
29#include "Global.h"
30#include "AutoCaller.h"
31#include "ConsoleImpl.h"
32#include "ProgressImpl.h"
33
34#include <memory> /* For auto_ptr. */
35
36#include <iprt/env.h>
37#include <iprt/file.h> /* For CopyTo/From. */
38
39#ifdef LOG_GROUP
40 #undef LOG_GROUP
41#endif
42#define LOG_GROUP LOG_GROUP_GUEST_CONTROL
43#include <VBox/log.h>
44
45
46/*********************************************************************************************************************************
47* Defines *
48*********************************************************************************************************************************/
49
50/**
51 * Update file flags.
52 */
53#define UPDATEFILE_FLAG_NONE 0
54/** Copy over the file from host to the
55 * guest. */
56#define UPDATEFILE_FLAG_COPY_FROM_ISO RT_BIT(0)
57/** Execute file on the guest after it has
58 * been successfully transfered. */
59#define UPDATEFILE_FLAG_EXECUTE RT_BIT(7)
60/** File is optional, does not have to be
61 * existent on the .ISO. */
62#define UPDATEFILE_FLAG_OPTIONAL RT_BIT(8)
63
64
65// session task classes
66/////////////////////////////////////////////////////////////////////////////
67
68GuestSessionTask::GuestSessionTask(GuestSession *pSession):ThreadTask("GenericGuestSessionTask")
69{
70 mSession = pSession;
71}
72
73GuestSessionTask::~GuestSessionTask(void)
74{
75}
76
77HRESULT GuestSessionTask::createAndSetProgressObject()
78{
79 LogFlowThisFunc(("Task Description = %s, pTask=%p\n", mDesc.c_str(), this));
80
81 ComObjPtr<Progress> pProgress;
82 HRESULT hr = S_OK;
83 /* Create the progress object. */
84 hr = pProgress.createObject();
85 if (FAILED(hr))
86 return VERR_COM_UNEXPECTED;
87
88 hr = pProgress->init(static_cast<IGuestSession*>(mSession),
89 Bstr(mDesc).raw(),
90 TRUE /* aCancelable */);
91 if (FAILED(hr))
92 return VERR_COM_UNEXPECTED;
93
94 mProgress = pProgress;
95
96 LogFlowFuncLeave();
97
98 return hr;
99}
100
101int GuestSessionTask::getGuestProperty(const ComObjPtr<Guest> &pGuest,
102 const Utf8Str &strPath, Utf8Str &strValue)
103{
104 ComObjPtr<Console> pConsole = pGuest->i_getConsole();
105 const ComPtr<IMachine> pMachine = pConsole->i_machine();
106
107 Assert(!pMachine.isNull());
108 Bstr strTemp, strFlags;
109 LONG64 i64Timestamp;
110 HRESULT hr = pMachine->GetGuestProperty(Bstr(strPath).raw(),
111 strTemp.asOutParam(),
112 &i64Timestamp, strFlags.asOutParam());
113 if (SUCCEEDED(hr))
114 {
115 strValue = strTemp;
116 return VINF_SUCCESS;
117 }
118 return VERR_NOT_FOUND;
119}
120
121int GuestSessionTask::setProgress(ULONG uPercent)
122{
123 if (mProgress.isNull()) /* Progress is optional. */
124 return VINF_SUCCESS;
125
126 BOOL fCanceled;
127 if ( SUCCEEDED(mProgress->COMGETTER(Canceled(&fCanceled)))
128 && fCanceled)
129 return VERR_CANCELLED;
130 BOOL fCompleted;
131 if ( SUCCEEDED(mProgress->COMGETTER(Completed(&fCompleted)))
132 && fCompleted)
133 {
134 AssertMsgFailed(("Setting value of an already completed progress\n"));
135 return VINF_SUCCESS;
136 }
137 HRESULT hr = mProgress->SetCurrentOperationProgress(uPercent);
138 if (FAILED(hr))
139 return VERR_COM_UNEXPECTED;
140
141 return VINF_SUCCESS;
142}
143
144int GuestSessionTask::setProgressSuccess(void)
145{
146 if (mProgress.isNull()) /* Progress is optional. */
147 return VINF_SUCCESS;
148
149 BOOL fCanceled;
150 BOOL fCompleted;
151 if ( SUCCEEDED(mProgress->COMGETTER(Canceled(&fCanceled)))
152 && !fCanceled
153 && SUCCEEDED(mProgress->COMGETTER(Completed(&fCompleted)))
154 && !fCompleted)
155 {
156 HRESULT hr = mProgress->i_notifyComplete(S_OK);
157 if (FAILED(hr))
158 return VERR_COM_UNEXPECTED; /** @todo Find a better rc. */
159 }
160
161 return VINF_SUCCESS;
162}
163
164HRESULT GuestSessionTask::setProgressErrorMsg(HRESULT hr, const Utf8Str &strMsg)
165{
166 LogFlowFunc(("hr=%Rhrc, strMsg=%s\n",
167 hr, strMsg.c_str()));
168
169 if (mProgress.isNull()) /* Progress is optional. */
170 return hr; /* Return original rc. */
171
172 BOOL fCanceled;
173 BOOL fCompleted;
174 if ( SUCCEEDED(mProgress->COMGETTER(Canceled(&fCanceled)))
175 && !fCanceled
176 && SUCCEEDED(mProgress->COMGETTER(Completed(&fCompleted)))
177 && !fCompleted)
178 {
179 HRESULT hr2 = mProgress->i_notifyComplete(hr,
180 COM_IIDOF(IGuestSession),
181 GuestSession::getStaticComponentName(),
182 strMsg.c_str());
183 if (FAILED(hr2))
184 return hr2;
185 }
186 return hr; /* Return original rc. */
187}
188
189SessionTaskOpen::SessionTaskOpen(GuestSession *pSession,
190 uint32_t uFlags,
191 uint32_t uTimeoutMS)
192 : GuestSessionTask(pSession),
193 mFlags(uFlags),
194 mTimeoutMS(uTimeoutMS)
195{
196 m_strTaskName = "gctlSesOpen";
197}
198
199SessionTaskOpen::~SessionTaskOpen(void)
200{
201
202}
203
204int SessionTaskOpen::Run(int *pGuestRc)
205{
206 LogFlowThisFuncEnter();
207
208 ComObjPtr<GuestSession> pSession = mSession;
209 Assert(!pSession.isNull());
210
211 AutoCaller autoCaller(pSession);
212 if (FAILED(autoCaller.rc())) return autoCaller.rc();
213
214 int vrc = pSession->i_startSessionInternal(pGuestRc);
215 /* Nothing to do here anymore. */
216
217 LogFlowFuncLeaveRC(vrc);
218 return vrc;
219}
220
221int SessionTaskOpen::RunAsync(const Utf8Str &strDesc, ComObjPtr<Progress> &pProgress)
222{
223 LogFlowThisFunc(("strDesc=%s\n", strDesc.c_str()));
224
225 mDesc = strDesc;
226 mProgress = pProgress;
227
228 int rc = RTThreadCreate(NULL, SessionTaskOpen::taskThread, this,
229 0, RTTHREADTYPE_MAIN_HEAVY_WORKER, 0,
230 "gctlSesOpen");
231 LogFlowFuncLeaveRC(rc);
232 return rc;
233}
234
235/* static */
236DECLCALLBACK(int) SessionTaskOpen::taskThread(RTTHREAD Thread, void *pvUser)
237{
238 SessionTaskOpen* task = static_cast<SessionTaskOpen*>(pvUser);
239 AssertReturn(task, VERR_GENERAL_FAILURE);
240
241 LogFlowFunc(("pTask=%p\n", task));
242
243 return task->Run(NULL /* guestRc */);
244}
245
246SessionTaskCopyTo::SessionTaskCopyTo(GuestSession *pSession,
247 const Utf8Str &strSource, const Utf8Str &strDest, uint32_t uFlags)
248 : GuestSessionTask(pSession),
249 mSource(strSource),
250 mSourceFile(NULL),
251 mSourceOffset(0),
252 mSourceSize(0),
253 mDest(strDest)
254{
255 mCopyFileFlags = uFlags;
256 m_strTaskName = "gctlCpyTo";
257}
258
259/** @todo Merge this and the above call and let the above call do the open/close file handling so that the
260 * inner code only has to deal with file handles. No time now ... */
261SessionTaskCopyTo::SessionTaskCopyTo(GuestSession *pSession,
262 PRTFILE pSourceFile, size_t cbSourceOffset, uint64_t cbSourceSize,
263 const Utf8Str &strDest, uint32_t uFlags)
264 : GuestSessionTask(pSession)
265{
266 mSourceFile = pSourceFile;
267 mSourceOffset = cbSourceOffset;
268 mSourceSize = cbSourceSize;
269 mDest = strDest;
270 mCopyFileFlags = uFlags;
271 m_strTaskName = "gctlCpyTo";
272}
273
274SessionTaskCopyTo::~SessionTaskCopyTo(void)
275{
276
277}
278
279int SessionTaskCopyTo::Run(void)
280{
281 LogFlowThisFuncEnter();
282
283 ComObjPtr<GuestSession> pSession = mSession;
284 Assert(!pSession.isNull());
285
286 AutoCaller autoCaller(pSession);
287 if (FAILED(autoCaller.rc())) return autoCaller.rc();
288
289 if (mCopyFileFlags)
290 {
291 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
292 Utf8StrFmt(GuestSession::tr("Copy flags (%#x) not implemented yet"),
293 mCopyFileFlags));
294 return VERR_INVALID_PARAMETER;
295 }
296
297 int rc;
298
299 RTMSINTERVAL msTimeout = 30 * 1000; /** @todo 30s timeout for all actions. Make this configurable? */
300
301 RTFILE fileLocal;
302 PRTFILE pFile = &fileLocal;
303
304 if (!mSourceFile)
305 {
306 /* Does our source file exist? */
307 if (!RTFileExists(mSource.c_str()))
308 {
309 rc = setProgressErrorMsg(VBOX_E_IPRT_ERROR,
310 Utf8StrFmt(GuestSession::tr("Source file \"%s\" does not exist or is not a file"),
311 mSource.c_str()));
312 }
313 else
314 {
315 rc = RTFileOpen(pFile, mSource.c_str(),
316 RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_WRITE);
317 if (RT_FAILURE(rc))
318 {
319 rc = setProgressErrorMsg(VBOX_E_IPRT_ERROR,
320 Utf8StrFmt(GuestSession::tr("Could not open source file \"%s\" for reading: %Rrc"),
321 mSource.c_str(), rc));
322 }
323 else
324 {
325 rc = RTFileGetSize(*pFile, &mSourceSize);
326 if (RT_FAILURE(rc))
327 {
328 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
329 Utf8StrFmt(GuestSession::tr("Could not query file size of \"%s\": %Rrc"),
330 mSource.c_str(), rc));
331 }
332 }
333 }
334 }
335 else
336 {
337 rc = VINF_SUCCESS;
338 pFile = mSourceFile;
339 /* Size + offset are optional. */
340 }
341
342 /*
343 * Query information about our destination first.
344 */
345 int guestRc;
346 if (RT_SUCCESS(rc))
347 {
348 GuestFsObjData objData;
349 rc = pSession->i_directoryQueryInfoInternal(mDest, true /* fFollowSymlinks */, objData, &guestRc);
350 if (RT_SUCCESS(rc))
351 {
352 mDest = Utf8StrFmt("%s/%s", mDest.c_str(), RTPathFilename(mSource.c_str()));
353 }
354 else if (rc == VERR_NOT_A_DIRECTORY)
355 {
356 rc = VINF_SUCCESS;
357 }
358 }
359
360 /** @todo Implement sparse file support? */
361
362 /*
363 * Start the actual copying process by cat'ing the source file to the
364 * destination file on the guest.
365 */
366 GuestProcessStartupInfo procInfo;
367 procInfo.mExecutable = Utf8Str(VBOXSERVICE_TOOL_CAT);
368 procInfo.mFlags = ProcessCreateFlag_Hidden;
369
370 /* Set arguments.*/
371 procInfo.mArguments.push_back(procInfo.mExecutable); /* Set argv0. */
372 procInfo.mArguments.push_back(Utf8StrFmt("--output=%s", mDest.c_str())); /** @todo Do we need path conversion? */
373
374 /* Startup process. */
375 ComObjPtr<GuestProcess> pProcess;
376 if (RT_SUCCESS(rc))
377 rc = pSession->i_processCreateExInternal(procInfo, pProcess);
378 if (RT_SUCCESS(rc))
379 {
380 Assert(!pProcess.isNull());
381 rc = pProcess->i_startProcess(msTimeout, &guestRc);
382 }
383
384 if (RT_FAILURE(rc))
385 {
386 switch (rc)
387 {
388 case VERR_GSTCTL_GUEST_ERROR:
389 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
390 GuestProcess::i_guestErrorToString(guestRc));
391 break;
392
393 default:
394 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
395 Utf8StrFmt(GuestSession::tr(
396 "Error while creating guest process for copying file \"%s\" from guest to host: %Rrc"),
397 mSource.c_str(), rc));
398 break;
399 }
400 }
401
402 if (RT_SUCCESS(rc))
403 {
404 ProcessWaitResult_T waitRes;
405 BYTE byBuf[_64K];
406
407 BOOL fCanceled = FALSE;
408 uint64_t cbWrittenTotal = 0;
409 uint64_t cbToRead = mSourceSize;
410
411 for (;;)
412 {
413 rc = pProcess->i_waitFor(ProcessWaitForFlag_StdIn, msTimeout, waitRes, &guestRc);
414 if ( RT_FAILURE(rc)
415 || ( waitRes != ProcessWaitResult_StdIn
416 && waitRes != ProcessWaitResult_WaitFlagNotSupported))
417 {
418 break;
419 }
420
421 /* If the guest does not support waiting for stdin, we now yield in
422 * order to reduce the CPU load due to busy waiting. */
423 if (waitRes == ProcessWaitResult_WaitFlagNotSupported)
424 RTThreadYield(); /* Optional, don't check rc. */
425
426 size_t cbRead = 0;
427 if (mSourceSize) /* If we have nothing to write, take a shortcut. */
428 {
429 /** @todo Not very efficient, but works for now. */
430 rc = RTFileSeek(*pFile, mSourceOffset + cbWrittenTotal,
431 RTFILE_SEEK_BEGIN, NULL /* poffActual */);
432 if (RT_SUCCESS(rc))
433 {
434 rc = RTFileRead(*pFile, (uint8_t*)byBuf,
435 RT_MIN((size_t)cbToRead, sizeof(byBuf)), &cbRead);
436 /*
437 * Some other error occured? There might be a chance that RTFileRead
438 * could not resolve/map the native error code to an IPRT code, so just
439 * print a generic error.
440 */
441 if (RT_FAILURE(rc))
442 {
443 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
444 Utf8StrFmt(GuestSession::tr("Could not read from host file \"%s\" (%Rrc)"),
445 mSource.c_str(), rc));
446 break;
447 }
448 }
449 else
450 {
451 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
452 Utf8StrFmt(GuestSession::tr("Seeking host file \"%s\" to offset %RU64 failed: %Rrc"),
453 mSource.c_str(), cbWrittenTotal, rc));
454 break;
455 }
456 }
457
458 uint32_t fFlags = ProcessInputFlag_None;
459
460 /* Did we reach the end of the content we want to transfer (last chunk)? */
461 if ( (cbRead < sizeof(byBuf))
462 /* Did we reach the last block which is exactly _64K? */
463 || (cbToRead - cbRead == 0)
464 /* ... or does the user want to cancel? */
465 || ( !mProgress.isNull()
466 && SUCCEEDED(mProgress->COMGETTER(Canceled(&fCanceled)))
467 && fCanceled)
468 )
469 {
470 LogFlowThisFunc(("Writing last chunk cbRead=%RU64\n", cbRead));
471 fFlags |= ProcessInputFlag_EndOfFile;
472 }
473
474 uint32_t cbWritten;
475 Assert(sizeof(byBuf) >= cbRead);
476 rc = pProcess->i_writeData(0 /* StdIn */, fFlags,
477 byBuf, cbRead,
478 msTimeout, &cbWritten, &guestRc);
479 if (RT_FAILURE(rc))
480 {
481 switch (rc)
482 {
483 case VERR_GSTCTL_GUEST_ERROR:
484 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
485 GuestProcess::i_guestErrorToString(guestRc));
486 break;
487
488 default:
489 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
490 Utf8StrFmt(GuestSession::tr("Writing to guest file \"%s\" (offset %RU64) failed: %Rrc"),
491 mDest.c_str(), cbWrittenTotal, rc));
492 break;
493 }
494
495 break;
496 }
497
498 /* Only subtract bytes reported written by the guest. */
499 Assert(cbToRead >= cbWritten);
500 cbToRead -= cbWritten;
501
502 /* Update total bytes written to the guest. */
503 cbWrittenTotal += cbWritten;
504 Assert(cbWrittenTotal <= mSourceSize);
505
506 LogFlowThisFunc(("rc=%Rrc, cbWritten=%RU32, cbToRead=%RU64, cbWrittenTotal=%RU64, cbFileSize=%RU64\n",
507 rc, cbWritten, cbToRead, cbWrittenTotal, mSourceSize));
508
509 /* Did the user cancel the operation above? */
510 if (fCanceled)
511 break;
512
513 /* Update the progress.
514 * Watch out for division by zero. */
515 mSourceSize > 0
516 ? rc = setProgress((ULONG)(cbWrittenTotal * 100 / mSourceSize))
517 : rc = setProgress(100);
518 if (RT_FAILURE(rc))
519 break;
520
521 /* End of file reached? */
522 if (!cbToRead)
523 break;
524 } /* for */
525
526 LogFlowThisFunc(("Copy loop ended with rc=%Rrc, cbToRead=%RU64, cbWrittenTotal=%RU64, cbFileSize=%RU64\n",
527 rc, cbToRead, cbWrittenTotal, mSourceSize));
528
529 /*
530 * Wait on termination of guest process until it completed all operations.
531 */
532 if ( !fCanceled
533 || RT_SUCCESS(rc))
534 {
535 rc = pProcess->i_waitFor(ProcessWaitForFlag_Terminate, msTimeout, waitRes, &guestRc);
536 if ( RT_FAILURE(rc)
537 || waitRes != ProcessWaitResult_Terminate)
538 {
539 if (RT_FAILURE(rc))
540 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
541 Utf8StrFmt(
542 GuestSession::tr("Waiting on termination for copying file \"%s\" to guest failed: %Rrc"),
543 mSource.c_str(), rc));
544 else
545 {
546 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
547 Utf8StrFmt(GuestSession::tr(
548 "Waiting on termination for copying file \"%s\" to guest failed with wait result %ld"),
549 mSource.c_str(), waitRes));
550 rc = VERR_GENERAL_FAILURE; /* Fudge. */
551 }
552 }
553 }
554
555 if (RT_SUCCESS(rc))
556 {
557 /*
558 * Newer VBoxService toolbox versions report what went wrong via exit code.
559 * So handle this first.
560 */
561 ProcessStatus_T procStatus;
562 LONG exitCode;
563 if ( ( SUCCEEDED(pProcess->COMGETTER(Status(&procStatus)))
564 && procStatus != ProcessStatus_TerminatedNormally)
565 || ( SUCCEEDED(pProcess->COMGETTER(ExitCode(&exitCode)))
566 && exitCode != 0)
567 )
568 {
569 LogFlowThisFunc(("procStatus=%ld, exitCode=%ld\n", procStatus, exitCode));
570 rc = GuestProcessTool::i_exitCodeToRc(procInfo, exitCode);
571 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
572 Utf8StrFmt(GuestSession::tr("Copying file \"%s\" to guest failed: %Rrc"),
573 mSource.c_str(), rc));
574 }
575 /*
576 * Even if we succeeded until here make sure to check whether we really transfered
577 * everything.
578 */
579 else if ( mSourceSize > 0
580 && cbWrittenTotal == 0)
581 {
582 /* If nothing was transfered but the file size was > 0 then "vbox_cat" wasn't able to write
583 * to the destination -> access denied. */
584 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
585 Utf8StrFmt(GuestSession::tr("Access denied when copying file \"%s\" to guest \"%s\""),
586 mSource.c_str(), mDest.c_str()));
587 rc = VERR_ACCESS_DENIED;
588 }
589 else if (cbWrittenTotal < mSourceSize)
590 {
591 /* If we did not copy all let the user know. */
592 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
593 Utf8StrFmt(GuestSession::tr("Copying file \"%s\" to guest failed (%RU64/%RU64 bytes transfered)"),
594 mSource.c_str(), cbWrittenTotal, mSourceSize));
595 rc = VERR_INTERRUPTED;
596 }
597
598 if (RT_SUCCESS(rc))
599 rc = setProgressSuccess();
600 }
601 } /* processCreateExInteral */
602
603 if (!mSourceFile) /* Only close locally opened files. */
604 RTFileClose(*pFile);
605
606 LogFlowFuncLeaveRC(rc);
607 return rc;
608}
609
610int SessionTaskCopyTo::RunAsync(const Utf8Str &strDesc, ComObjPtr<Progress> &pProgress)
611{
612 LogFlowThisFunc(("strDesc=%s, strSource=%s, strDest=%s, mCopyFileFlags=%x\n",
613 strDesc.c_str(), mSource.c_str(), mDest.c_str(), mCopyFileFlags));
614
615 mDesc = strDesc;
616 mProgress = pProgress;
617
618 int rc = RTThreadCreate(NULL, SessionTaskCopyTo::taskThread, this,
619 0, RTTHREADTYPE_MAIN_HEAVY_WORKER, 0,
620 "gctlCpyTo");
621 LogFlowFuncLeaveRC(rc);
622 return rc;
623}
624
625/* static */
626DECLCALLBACK(int) SessionTaskCopyTo::taskThread(RTTHREAD Thread, void *pvUser)
627{
628 SessionTaskCopyTo* task = static_cast<SessionTaskCopyTo*>(pvUser);
629 AssertReturn(task, VERR_GENERAL_FAILURE);
630
631 LogFlowFunc(("pTask=%p\n", task));
632
633 return task->Run();
634}
635
636SessionTaskCopyFrom::SessionTaskCopyFrom(GuestSession *pSession,
637 const Utf8Str &strSource, const Utf8Str &strDest, uint32_t uFlags)
638 : GuestSessionTask(pSession)
639{
640 mSource = strSource;
641 mDest = strDest;
642 mFlags = uFlags;
643 m_strTaskName = "gctlCpyFrom";
644}
645
646SessionTaskCopyFrom::~SessionTaskCopyFrom(void)
647{
648
649}
650
651int SessionTaskCopyFrom::Run(void)
652{
653 LogFlowThisFuncEnter();
654
655 ComObjPtr<GuestSession> pSession = mSession;
656 Assert(!pSession.isNull());
657
658 AutoCaller autoCaller(pSession);
659 if (FAILED(autoCaller.rc())) return autoCaller.rc();
660
661 RTMSINTERVAL msTimeout = 30 * 1000; /** @todo 30s timeout for all actions. Make this configurable? */
662
663 /*
664 * Note: There will be races between querying file size + reading the guest file's
665 * content because we currently *do not* lock down the guest file when doing the
666 * actual operations.
667 ** @todo Use the IGuestFile API for locking down the file on the guest!
668 */
669 GuestFsObjData objData; int guestRc;
670 int rc = pSession->i_fileQueryInfoInternal(Utf8Str(mSource), false /*fFollowSymlinks*/, objData, &guestRc);
671 if (RT_FAILURE(rc))
672 {
673 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
674 Utf8StrFmt(GuestSession::tr("Querying guest file information for \"%s\" failed: %Rrc"),
675 mSource.c_str(), rc));
676 }
677 else if (objData.mType != FsObjType_File) /* Only single files are supported at the moment. */
678 {
679 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
680 Utf8StrFmt(GuestSession::tr("Object \"%s\" on the guest is not a file"), mSource.c_str()));
681 rc = VERR_NOT_A_FILE;
682 }
683
684 if (RT_SUCCESS(rc))
685 {
686 RTFILE fileDest;
687 rc = RTFileOpen(&fileDest, mDest.c_str(),
688 RTFILE_O_WRITE | RTFILE_O_OPEN_CREATE | RTFILE_O_DENY_WRITE); /** @todo Use the correct open modes! */
689 if (RT_FAILURE(rc))
690 {
691 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
692 Utf8StrFmt(GuestSession::tr("Opening/creating destination file on host \"%s\" failed: %Rrc"),
693 mDest.c_str(), rc));
694 }
695 else
696 {
697 GuestProcessStartupInfo procInfo;
698 procInfo.mName = Utf8StrFmt(GuestSession::tr("Copying file \"%s\" from guest to the host to \"%s\" (%RI64 bytes)"),
699 mSource.c_str(), mDest.c_str(), objData.mObjectSize);
700 procInfo.mExecutable = Utf8Str(VBOXSERVICE_TOOL_CAT);
701 procInfo.mFlags = ProcessCreateFlag_Hidden | ProcessCreateFlag_WaitForStdOut;
702
703 /* Set arguments.*/
704 procInfo.mArguments.push_back(procInfo.mExecutable); /* Set argv0. */
705 procInfo.mArguments.push_back(mSource); /* Which file to output? */
706
707 /* Startup process. */
708 ComObjPtr<GuestProcess> pProcess;
709 rc = pSession->i_processCreateExInternal(procInfo, pProcess);
710 if (RT_SUCCESS(rc))
711 rc = pProcess->i_startProcess(msTimeout, &guestRc);
712 if (RT_FAILURE(rc))
713 {
714 switch (rc)
715 {
716 case VERR_GSTCTL_GUEST_ERROR:
717 setProgressErrorMsg(VBOX_E_IPRT_ERROR, GuestProcess::i_guestErrorToString(guestRc));
718 break;
719
720 default:
721 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
722 Utf8StrFmt(GuestSession::tr(
723 "Error while creating guest process for copying file \"%s\" from guest to host: %Rrc"),
724 mSource.c_str(), rc));
725 break;
726 }
727 }
728 else
729 {
730 ProcessWaitResult_T waitRes;
731 BYTE byBuf[_64K];
732
733 BOOL fCanceled = FALSE;
734 uint64_t cbWrittenTotal = 0;
735 uint64_t cbToRead = objData.mObjectSize;
736
737 for (;;)
738 {
739 rc = pProcess->i_waitFor(ProcessWaitForFlag_StdOut, msTimeout, waitRes, &guestRc);
740 if (RT_FAILURE(rc))
741 {
742 switch (rc)
743 {
744 case VERR_GSTCTL_GUEST_ERROR:
745 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
746 GuestProcess::i_guestErrorToString(guestRc));
747 break;
748
749 default:
750 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
751 Utf8StrFmt(GuestSession::tr("Error while creating guest process for copying file \"%s\" from guest to host: %Rrc"),
752 mSource.c_str(), rc));
753 break;
754 }
755
756 break;
757 }
758
759 if ( waitRes == ProcessWaitResult_StdOut
760 || waitRes == ProcessWaitResult_WaitFlagNotSupported)
761 {
762 /* If the guest does not support waiting for stdin, we now yield in
763 * order to reduce the CPU load due to busy waiting. */
764 if (waitRes == ProcessWaitResult_WaitFlagNotSupported)
765 RTThreadYield(); /* Optional, don't check rc. */
766
767 uint32_t cbRead = 0; /* readData can return with VWRN_GSTCTL_OBJECTSTATE_CHANGED. */
768 rc = pProcess->i_readData(OUTPUT_HANDLE_ID_STDOUT, sizeof(byBuf),
769 msTimeout, byBuf, sizeof(byBuf),
770 &cbRead, &guestRc);
771 if (RT_FAILURE(rc))
772 {
773 switch (rc)
774 {
775 case VERR_GSTCTL_GUEST_ERROR:
776 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
777 GuestProcess::i_guestErrorToString(guestRc));
778 break;
779
780 default:
781 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
782 Utf8StrFmt(GuestSession::tr("Reading from guest file \"%s\" (offset %RU64) failed: %Rrc"),
783 mSource.c_str(), cbWrittenTotal, rc));
784 break;
785 }
786
787 break;
788 }
789
790 if (cbRead)
791 {
792 rc = RTFileWrite(fileDest, byBuf, cbRead, NULL /* No partial writes */);
793 if (RT_FAILURE(rc))
794 {
795 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
796 Utf8StrFmt(GuestSession::tr("Writing to host file \"%s\" (%RU64 bytes left) failed: %Rrc"),
797 mDest.c_str(), cbToRead, rc));
798 break;
799 }
800
801 /* Only subtract bytes reported written by the guest. */
802 Assert(cbToRead >= cbRead);
803 cbToRead -= cbRead;
804
805 /* Update total bytes written to the guest. */
806 cbWrittenTotal += cbRead;
807 Assert(cbWrittenTotal <= (uint64_t)objData.mObjectSize);
808
809 /* Did the user cancel the operation above? */
810 if ( SUCCEEDED(mProgress->COMGETTER(Canceled(&fCanceled)))
811 && fCanceled)
812 break;
813
814 rc = setProgress((ULONG)(cbWrittenTotal / ((uint64_t)objData.mObjectSize / 100.0)));
815 if (RT_FAILURE(rc))
816 break;
817 }
818 }
819 else
820 {
821 break;
822 }
823
824 } /* for */
825
826 LogFlowThisFunc(("rc=%Rrc, guestrc=%Rrc, waitRes=%ld, cbWrittenTotal=%RU64, cbSize=%RI64, cbToRead=%RU64\n",
827 rc, guestRc, waitRes, cbWrittenTotal, objData.mObjectSize, cbToRead));
828
829 /*
830 * Wait on termination of guest process until it completed all operations.
831 */
832 if ( !fCanceled
833 || RT_SUCCESS(rc))
834 {
835 rc = pProcess->i_waitFor(ProcessWaitForFlag_Terminate, msTimeout, waitRes, &guestRc);
836 if ( RT_FAILURE(rc)
837 || waitRes != ProcessWaitResult_Terminate)
838 {
839 if (RT_FAILURE(rc))
840 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
841 Utf8StrFmt(
842 GuestSession::tr("Waiting on termination for copying file \"%s\" from guest failed: %Rrc"),
843 mSource.c_str(), rc));
844 else
845 {
846 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
847 Utf8StrFmt(GuestSession::tr(
848 "Waiting on termination for copying file \"%s\" from guest failed with wait result %ld"),
849 mSource.c_str(), waitRes));
850 rc = VERR_GENERAL_FAILURE; /* Fudge. */
851 }
852 }
853 }
854
855 if (RT_SUCCESS(rc))
856 {
857 ProcessStatus_T procStatus;
858 LONG exitCode;
859 if ( ( SUCCEEDED(pProcess->COMGETTER(Status(&procStatus)))
860 && procStatus != ProcessStatus_TerminatedNormally)
861 || ( SUCCEEDED(pProcess->COMGETTER(ExitCode(&exitCode)))
862 && exitCode != 0)
863 )
864 {
865 LogFlowThisFunc(("procStatus=%ld, exitCode=%ld\n", procStatus, exitCode));
866 rc = GuestProcessTool::i_exitCodeToRc(procInfo, exitCode);
867 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
868 Utf8StrFmt(GuestSession::tr("Copying file \"%s\" to host failed: %Rrc"),
869 mSource.c_str(), rc));
870 }
871 /*
872 * Even if we succeeded until here make sure to check whether we really transfered
873 * everything.
874 */
875 else if ( objData.mObjectSize > 0
876 && cbWrittenTotal == 0)
877 {
878 /* If nothing was transfered but the file size was > 0 then "vbox_cat" wasn't able to write
879 * to the destination -> access denied. */
880 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
881 Utf8StrFmt(GuestSession::tr("Writing guest file \"%s\" to host to \"%s\" failed: Access denied"),
882 mSource.c_str(), mDest.c_str()));
883 rc = VERR_ACCESS_DENIED;
884 }
885 else if (cbWrittenTotal < (uint64_t)objData.mObjectSize)
886 {
887 /* If we did not copy all let the user know. */
888 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
889 Utf8StrFmt(GuestSession::tr("Copying guest file \"%s\" to host to \"%s\" failed (%RU64/%RI64 bytes transfered)"),
890 mSource.c_str(), mDest.c_str(), cbWrittenTotal, objData.mObjectSize));
891 rc = VERR_INTERRUPTED;
892 }
893
894 if (RT_SUCCESS(rc))
895 rc = setProgressSuccess();
896 }
897 }
898
899 RTFileClose(fileDest);
900 }
901 }
902
903 LogFlowFuncLeaveRC(rc);
904 return rc;
905}
906
907int SessionTaskCopyFrom::RunAsync(const Utf8Str &strDesc, ComObjPtr<Progress> &pProgress)
908{
909 LogFlowThisFunc(("strDesc=%s, strSource=%s, strDest=%s, uFlags=%x\n",
910 strDesc.c_str(), mSource.c_str(), mDest.c_str(), mFlags));
911
912 mDesc = strDesc;
913 mProgress = pProgress;
914
915 int rc = RTThreadCreate(NULL, SessionTaskCopyFrom::taskThread, this,
916 0, RTTHREADTYPE_MAIN_HEAVY_WORKER, 0,
917 "gctlCpyFrom");
918 LogFlowFuncLeaveRC(rc);
919 return rc;
920}
921
922/* static */
923DECLCALLBACK(int) SessionTaskCopyFrom::taskThread(RTTHREAD Thread, void *pvUser)
924{
925 SessionTaskCopyFrom* task = static_cast<SessionTaskCopyFrom*>(pvUser);
926 AssertReturn(task, VERR_GENERAL_FAILURE);
927
928 LogFlowFunc(("pTask=%p\n", task));
929
930 return task->Run();
931}
932
933SessionTaskUpdateAdditions::SessionTaskUpdateAdditions(GuestSession *pSession,
934 const Utf8Str &strSource,
935 const ProcessArguments &aArguments,
936 uint32_t uFlags)
937 : GuestSessionTask(pSession)
938{
939 mSource = strSource;
940 mArguments = aArguments;
941 mFlags = uFlags;
942 m_strTaskName = "gctlUpGA";
943}
944
945SessionTaskUpdateAdditions::~SessionTaskUpdateAdditions(void)
946{
947
948}
949
950int SessionTaskUpdateAdditions::i_addProcessArguments(ProcessArguments &aArgumentsDest,
951 const ProcessArguments &aArgumentsSource)
952{
953 int rc = VINF_SUCCESS;
954
955 try
956 {
957 /* Filter out arguments which already are in the destination to
958 * not end up having them specified twice. Not the fastest method on the
959 * planet but does the job. */
960 ProcessArguments::const_iterator itSource = aArgumentsSource.begin();
961 while (itSource != aArgumentsSource.end())
962 {
963 bool fFound = false;
964 ProcessArguments::iterator itDest = aArgumentsDest.begin();
965 while (itDest != aArgumentsDest.end())
966 {
967 if ((*itDest).equalsIgnoreCase((*itSource)))
968 {
969 fFound = true;
970 break;
971 }
972 ++itDest;
973 }
974
975 if (!fFound)
976 aArgumentsDest.push_back((*itSource));
977
978 ++itSource;
979 }
980 }
981 catch(std::bad_alloc &)
982 {
983 return VERR_NO_MEMORY;
984 }
985
986 return rc;
987}
988
989int SessionTaskUpdateAdditions::i_copyFileToGuest(GuestSession *pSession, PRTISOFSFILE pISO,
990 Utf8Str const &strFileSource, const Utf8Str &strFileDest,
991 bool fOptional, uint32_t *pcbSize)
992{
993 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
994 AssertPtrReturn(pISO, VERR_INVALID_POINTER);
995 /* pcbSize is optional. */
996
997 uint32_t cbOffset;
998 size_t cbSize;
999
1000 int rc = RTIsoFsGetFileInfo(pISO, strFileSource.c_str(), &cbOffset, &cbSize);
1001 if (RT_FAILURE(rc))
1002 {
1003 if (fOptional)
1004 return VINF_SUCCESS;
1005
1006 return rc;
1007 }
1008
1009 Assert(cbOffset);
1010 Assert(cbSize);
1011 rc = RTFileSeek(pISO->file, cbOffset, RTFILE_SEEK_BEGIN, NULL);
1012
1013 HRESULT hr = S_OK;
1014 /* Copy over the Guest Additions file to the guest. */
1015 if (RT_SUCCESS(rc))
1016 {
1017 LogRel(("Copying Guest Additions installer file \"%s\" to \"%s\" on guest ...\n",
1018 strFileSource.c_str(), strFileDest.c_str()));
1019
1020 if (RT_SUCCESS(rc))
1021 {
1022 SessionTaskCopyTo *pTask = NULL;
1023 ComObjPtr<Progress> pProgressCopyTo;
1024 try
1025 {
1026 try
1027 {
1028 pTask = new SessionTaskCopyTo(pSession /* GuestSession */,
1029 &pISO->file, cbOffset, cbSize,
1030 strFileDest, FileCopyFlag_None);
1031 }
1032 catch(...)
1033 {
1034 hr = setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1035 GuestSession::tr("Failed to create SessionTaskCopyTo object "));
1036 throw;
1037 }
1038
1039 hr = pTask->Init(Utf8StrFmt(GuestSession::tr("Copying Guest Additions installer file \"%s\" to \"%s\" on guest"),
1040 mSource.c_str(), strFileDest.c_str()));
1041 if (FAILED(hr))
1042 {
1043 delete pTask;
1044 hr = setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1045 GuestSession::tr("Creating progress object for SessionTaskCopyTo object failed"));
1046 throw hr;
1047 }
1048
1049 hr = pTask->createThread(NULL, RTTHREADTYPE_MAIN_HEAVY_WORKER);
1050
1051 if (SUCCEEDED(hr))
1052 {
1053 /* Return progress to the caller. */
1054 pProgressCopyTo = pTask->GetProgressObject();
1055 }
1056 else
1057 hr = setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1058 GuestSession::tr("Starting thread for updating additions failed "));
1059 }
1060 catch(std::bad_alloc &)
1061 {
1062 hr = E_OUTOFMEMORY;
1063 }
1064 catch(HRESULT eHR)
1065 {
1066 hr = eHR;
1067 LogFlowThisFunc(("Exception was caught in the function \n"));
1068 }
1069
1070 if (SUCCEEDED(hr))
1071 {
1072 BOOL fCanceled = FALSE;
1073 hr = pProgressCopyTo->WaitForCompletion(-1);
1074 if ( SUCCEEDED(pProgressCopyTo->COMGETTER(Canceled)(&fCanceled))
1075 && fCanceled)
1076 {
1077 rc = VERR_GENERAL_FAILURE; /* Fudge. */
1078 }
1079 else if (FAILED(hr))
1080 {
1081 Assert(FAILED(hr));
1082 rc = VERR_GENERAL_FAILURE; /* Fudge. */
1083 }
1084 }
1085 }
1086 }
1087
1088 /** @todo Note: Since there is no file locking involved at the moment, there can be modifications
1089 * between finished copying, the verification and the actual execution. */
1090
1091 /* Determine where the installer image ended up and if it has the correct size. */
1092 if (RT_SUCCESS(rc))
1093 {
1094 LogRel(("Verifying Guest Additions installer file \"%s\" ...\n",
1095 strFileDest.c_str()));
1096
1097 GuestFsObjData objData;
1098 int64_t cbSizeOnGuest; int guestRc;
1099 rc = pSession->i_fileQuerySizeInternal(strFileDest, false /*fFollowSymlinks*/, &cbSizeOnGuest, &guestRc);
1100 if ( RT_SUCCESS(rc)
1101 && cbSize == (uint64_t)cbSizeOnGuest)
1102 {
1103 LogFlowThisFunc(("Guest Additions installer file \"%s\" successfully verified\n",
1104 strFileDest.c_str()));
1105 }
1106 else
1107 {
1108 if (RT_SUCCESS(rc)) /* Size does not match. */
1109 {
1110 LogRel(("Size of Guest Additions installer file \"%s\" does not match: %RI64 bytes copied, %RU64 bytes expected\n",
1111 strFileDest.c_str(), cbSizeOnGuest, cbSize));
1112 rc = VERR_BROKEN_PIPE; /** @todo Find a better error. */
1113 }
1114 else
1115 {
1116 switch (rc)
1117 {
1118 case VERR_GSTCTL_GUEST_ERROR:
1119 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1120 GuestProcess::i_guestErrorToString(guestRc));
1121 break;
1122
1123 default:
1124 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1125 Utf8StrFmt(GuestSession::tr("Error while querying size for file \"%s\": %Rrc"),
1126 strFileDest.c_str(), rc));
1127 break;
1128 }
1129 }
1130 }
1131
1132 if (RT_SUCCESS(rc))
1133 {
1134 if (pcbSize)
1135 *pcbSize = (uint32_t)cbSizeOnGuest;
1136 }
1137 }
1138
1139 return rc;
1140}
1141
1142int SessionTaskUpdateAdditions::i_runFileOnGuest(GuestSession *pSession, GuestProcessStartupInfo &procInfo)
1143{
1144 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1145
1146 LogRel(("Running %s ...\n", procInfo.mName.c_str()));
1147
1148 GuestProcessTool procTool; int guestRc;
1149 int vrc = procTool.Init(pSession, procInfo, false /* Async */, &guestRc);
1150 if (RT_SUCCESS(vrc))
1151 {
1152 if (RT_SUCCESS(guestRc))
1153 vrc = procTool.i_wait(GUESTPROCESSTOOL_FLAG_NONE, &guestRc);
1154 if (RT_SUCCESS(vrc))
1155 vrc = procTool.i_terminatedOk();
1156 }
1157
1158 if (RT_FAILURE(vrc))
1159 {
1160 switch (vrc)
1161 {
1162 case VWRN_GSTCTL_PROCESS_EXIT_CODE:
1163 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1164 Utf8StrFmt(GuestSession::tr("Running update file \"%s\" on guest failed: %Rrc"),
1165 procInfo.mExecutable.c_str(), procTool.i_getRc()));
1166 break;
1167
1168 case VERR_GSTCTL_GUEST_ERROR:
1169 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1170 GuestProcess::i_guestErrorToString(guestRc));
1171 break;
1172
1173 case VERR_INVALID_STATE: /** @todo Special guest control rc needed! */
1174 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1175 Utf8StrFmt(GuestSession::tr("Update file \"%s\" reported invalid running state"),
1176 procInfo.mExecutable.c_str()));
1177 break;
1178
1179 default:
1180 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1181 Utf8StrFmt(GuestSession::tr("Error while running update file \"%s\" on guest: %Rrc"),
1182 procInfo.mExecutable.c_str(), vrc));
1183 break;
1184 }
1185 }
1186
1187 return vrc;
1188}
1189
1190int SessionTaskUpdateAdditions::Run(void)
1191{
1192 LogFlowThisFuncEnter();
1193
1194 ComObjPtr<GuestSession> pSession = mSession;
1195 Assert(!pSession.isNull());
1196
1197 AutoCaller autoCaller(pSession);
1198 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1199
1200 int rc = setProgress(10);
1201 if (RT_FAILURE(rc))
1202 return rc;
1203
1204 HRESULT hr = S_OK;
1205
1206 LogRel(("Automatic update of Guest Additions started, using \"%s\"\n", mSource.c_str()));
1207
1208 ComObjPtr<Guest> pGuest(mSession->i_getParent());
1209#if 0
1210 /*
1211 * Wait for the guest being ready within 30 seconds.
1212 */
1213 AdditionsRunLevelType_T addsRunLevel;
1214 uint64_t tsStart = RTTimeSystemMilliTS();
1215 while ( SUCCEEDED(hr = pGuest->COMGETTER(AdditionsRunLevel)(&addsRunLevel))
1216 && ( addsRunLevel != AdditionsRunLevelType_Userland
1217 && addsRunLevel != AdditionsRunLevelType_Desktop))
1218 {
1219 if ((RTTimeSystemMilliTS() - tsStart) > 30 * 1000)
1220 {
1221 rc = VERR_TIMEOUT;
1222 break;
1223 }
1224
1225 RTThreadSleep(100); /* Wait a bit. */
1226 }
1227
1228 if (FAILED(hr)) rc = VERR_TIMEOUT;
1229 if (rc == VERR_TIMEOUT)
1230 hr = setProgressErrorMsg(VBOX_E_NOT_SUPPORTED,
1231 Utf8StrFmt(GuestSession::tr("Guest Additions were not ready within time, giving up")));
1232#else
1233 /*
1234 * For use with the GUI we don't want to wait, just return so that the manual .ISO mounting
1235 * can continue.
1236 */
1237 AdditionsRunLevelType_T addsRunLevel;
1238 if ( FAILED(hr = pGuest->COMGETTER(AdditionsRunLevel)(&addsRunLevel))
1239 || ( addsRunLevel != AdditionsRunLevelType_Userland
1240 && addsRunLevel != AdditionsRunLevelType_Desktop))
1241 {
1242 if (addsRunLevel == AdditionsRunLevelType_System)
1243 hr = setProgressErrorMsg(VBOX_E_NOT_SUPPORTED,
1244 Utf8StrFmt(GuestSession::tr("Guest Additions are installed but not fully loaded yet, aborting automatic update")));
1245 else
1246 hr = setProgressErrorMsg(VBOX_E_NOT_SUPPORTED,
1247 Utf8StrFmt(GuestSession::tr("Guest Additions not installed or ready, aborting automatic update")));
1248 rc = VERR_NOT_SUPPORTED;
1249 }
1250#endif
1251
1252 if (RT_SUCCESS(rc))
1253 {
1254 /*
1255 * Determine if we are able to update automatically. This only works
1256 * if there are recent Guest Additions installed already.
1257 */
1258 Utf8Str strAddsVer;
1259 rc = getGuestProperty(pGuest, "/VirtualBox/GuestAdd/Version", strAddsVer);
1260 if ( RT_SUCCESS(rc)
1261 && RTStrVersionCompare(strAddsVer.c_str(), "4.1") < 0)
1262 {
1263 hr = setProgressErrorMsg(VBOX_E_NOT_SUPPORTED,
1264 Utf8StrFmt(GuestSession::tr("Guest has too old Guest Additions (%s) installed for automatic updating, please update manually"),
1265 strAddsVer.c_str()));
1266 rc = VERR_NOT_SUPPORTED;
1267 }
1268 }
1269
1270 Utf8Str strOSVer;
1271 eOSType osType = eOSType_Unknown;
1272 if (RT_SUCCESS(rc))
1273 {
1274 /*
1275 * Determine guest OS type and the required installer image.
1276 */
1277 Utf8Str strOSType;
1278 rc = getGuestProperty(pGuest, "/VirtualBox/GuestInfo/OS/Product", strOSType);
1279 if (RT_SUCCESS(rc))
1280 {
1281 if ( strOSType.contains("Microsoft", Utf8Str::CaseInsensitive)
1282 || strOSType.contains("Windows", Utf8Str::CaseInsensitive))
1283 {
1284 osType = eOSType_Windows;
1285
1286 /*
1287 * Determine guest OS version.
1288 */
1289 rc = getGuestProperty(pGuest, "/VirtualBox/GuestInfo/OS/Release", strOSVer);
1290 if (RT_FAILURE(rc))
1291 {
1292 hr = setProgressErrorMsg(VBOX_E_NOT_SUPPORTED,
1293 Utf8StrFmt(GuestSession::tr("Unable to detected guest OS version, please update manually")));
1294 rc = VERR_NOT_SUPPORTED;
1295 }
1296
1297 /* Because Windows 2000 + XP and is bitching with WHQL popups even if we have signed drivers we
1298 * can't do automated updates here. */
1299 /* Windows XP 64-bit (5.2) is a Windows 2003 Server actually, so skip this here. */
1300 if ( RT_SUCCESS(rc)
1301 && RTStrVersionCompare(strOSVer.c_str(), "5.0") >= 0)
1302 {
1303 if ( strOSVer.startsWith("5.0") /* Exclude the build number. */
1304 || strOSVer.startsWith("5.1") /* Exclude the build number. */)
1305 {
1306 /* If we don't have AdditionsUpdateFlag_WaitForUpdateStartOnly set we can't continue
1307 * because the Windows Guest Additions installer will fail because of WHQL popups. If the
1308 * flag is set this update routine ends successfully as soon as the installer was started
1309 * (and the user has to deal with it in the guest). */
1310 if (!(mFlags & AdditionsUpdateFlag_WaitForUpdateStartOnly))
1311 {
1312 hr = setProgressErrorMsg(VBOX_E_NOT_SUPPORTED,
1313 Utf8StrFmt(GuestSession::tr("Windows 2000 and XP are not supported for automatic updating due to WHQL interaction, please update manually")));
1314 rc = VERR_NOT_SUPPORTED;
1315 }
1316 }
1317 }
1318 else
1319 {
1320 hr = setProgressErrorMsg(VBOX_E_NOT_SUPPORTED,
1321 Utf8StrFmt(GuestSession::tr("%s (%s) not supported for automatic updating, please update manually"),
1322 strOSType.c_str(), strOSVer.c_str()));
1323 rc = VERR_NOT_SUPPORTED;
1324 }
1325 }
1326 else if (strOSType.contains("Solaris", Utf8Str::CaseInsensitive))
1327 {
1328 osType = eOSType_Solaris;
1329 }
1330 else /* Everything else hopefully means Linux :-). */
1331 osType = eOSType_Linux;
1332
1333#if 1 /* Only Windows is supported (and tested) at the moment. */
1334 if ( RT_SUCCESS(rc)
1335 && osType != eOSType_Windows)
1336 {
1337 hr = setProgressErrorMsg(VBOX_E_NOT_SUPPORTED,
1338 Utf8StrFmt(GuestSession::tr("Detected guest OS (%s) does not support automatic Guest Additions updating, please update manually"),
1339 strOSType.c_str()));
1340 rc = VERR_NOT_SUPPORTED;
1341 }
1342#endif
1343 }
1344 }
1345
1346 RTISOFSFILE iso;
1347 if (RT_SUCCESS(rc))
1348 {
1349 /*
1350 * Try to open the .ISO file to extract all needed files.
1351 */
1352 rc = RTIsoFsOpen(&iso, mSource.c_str());
1353 if (RT_FAILURE(rc))
1354 {
1355 hr = setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1356 Utf8StrFmt(GuestSession::tr("Unable to open Guest Additions .ISO file \"%s\": %Rrc"),
1357 mSource.c_str(), rc));
1358 }
1359 else
1360 {
1361 /* Set default installation directories. */
1362 Utf8Str strUpdateDir = "/tmp/";
1363 if (osType == eOSType_Windows)
1364 strUpdateDir = "C:\\Temp\\";
1365
1366 rc = setProgress(5);
1367
1368 /* Try looking up the Guest Additions installation directory. */
1369 if (RT_SUCCESS(rc))
1370 {
1371 /* Try getting the installed Guest Additions version to know whether we
1372 * can install our temporary Guest Addition data into the original installation
1373 * directory.
1374 *
1375 * Because versions prior to 4.2 had bugs wrt spaces in paths we have to choose
1376 * a different location then.
1377 */
1378 bool fUseInstallDir = false;
1379
1380 Utf8Str strAddsVer;
1381 rc = getGuestProperty(pGuest, "/VirtualBox/GuestAdd/Version", strAddsVer);
1382 if ( RT_SUCCESS(rc)
1383 && RTStrVersionCompare(strAddsVer.c_str(), "4.2r80329") > 0)
1384 {
1385 fUseInstallDir = true;
1386 }
1387
1388 if (fUseInstallDir)
1389 {
1390 if (RT_SUCCESS(rc))
1391 rc = getGuestProperty(pGuest, "/VirtualBox/GuestAdd/InstallDir", strUpdateDir);
1392 if (RT_SUCCESS(rc))
1393 {
1394 if (osType == eOSType_Windows)
1395 {
1396 strUpdateDir.findReplace('/', '\\');
1397 strUpdateDir.append("\\Update\\");
1398 }
1399 else
1400 strUpdateDir.append("/update/");
1401 }
1402 }
1403 }
1404
1405 if (RT_SUCCESS(rc))
1406 LogRel(("Guest Additions update directory is: %s\n",
1407 strUpdateDir.c_str()));
1408
1409 /* Create the installation directory. */
1410 int guestRc;
1411 rc = pSession->i_directoryCreateInternal(strUpdateDir,
1412 755 /* Mode */, DirectoryCreateFlag_Parents, &guestRc);
1413 if (RT_FAILURE(rc))
1414 {
1415 switch (rc)
1416 {
1417 case VERR_GSTCTL_GUEST_ERROR:
1418 hr = setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1419 GuestProcess::i_guestErrorToString(guestRc));
1420 break;
1421
1422 default:
1423 hr = setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1424 Utf8StrFmt(GuestSession::tr("Error creating installation directory \"%s\" on the guest: %Rrc"),
1425 strUpdateDir.c_str(), rc));
1426 break;
1427 }
1428 }
1429 if (RT_SUCCESS(rc))
1430 rc = setProgress(10);
1431
1432 if (RT_SUCCESS(rc))
1433 {
1434 /* Prepare the file(s) we want to copy over to the guest and
1435 * (maybe) want to run. */
1436 switch (osType)
1437 {
1438 case eOSType_Windows:
1439 {
1440 /* Do we need to install our certificates? We do this for W2K and up. */
1441 bool fInstallCert = false;
1442
1443 /* Only Windows 2000 and up need certificates to be installed. */
1444 if (RTStrVersionCompare(strOSVer.c_str(), "5.0") >= 0)
1445 {
1446 fInstallCert = true;
1447 LogRel(("Certificates for auto updating WHQL drivers will be installed\n"));
1448 }
1449 else
1450 LogRel(("Skipping installation of certificates for WHQL drivers\n"));
1451
1452 if (fInstallCert)
1453 {
1454 /* Our certificate. */
1455 mFiles.push_back(InstallerFile("CERT/ORACLE_VBOX.CER",
1456 strUpdateDir + "oracle-vbox.cer",
1457 UPDATEFILE_FLAG_COPY_FROM_ISO | UPDATEFILE_FLAG_OPTIONAL));
1458 /* Our certificate installation utility. */
1459 /* First pass: Copy over the file + execute it to remove any existing
1460 * VBox certificates. */
1461 GuestProcessStartupInfo siCertUtilRem;
1462 siCertUtilRem.mName = "VirtualBox Certificate Utility, removing old VirtualBox certificates";
1463 siCertUtilRem.mArguments.push_back(Utf8Str("remove-trusted-publisher"));
1464 siCertUtilRem.mArguments.push_back(Utf8Str("--root")); /* Add root certificate as well. */
1465 siCertUtilRem.mArguments.push_back(Utf8Str(strUpdateDir + "oracle-vbox.cer"));
1466 siCertUtilRem.mArguments.push_back(Utf8Str(strUpdateDir + "oracle-vbox.cer"));
1467 mFiles.push_back(InstallerFile("CERT/VBOXCERTUTIL.EXE",
1468 strUpdateDir + "VBoxCertUtil.exe",
1469 UPDATEFILE_FLAG_COPY_FROM_ISO | UPDATEFILE_FLAG_EXECUTE |
1470 UPDATEFILE_FLAG_OPTIONAL,
1471 siCertUtilRem));
1472 /* Second pass: Only execute (but don't copy) again, this time installng the
1473 * recent certificates just copied over. */
1474 GuestProcessStartupInfo siCertUtilAdd;
1475 siCertUtilAdd.mName = "VirtualBox Certificate Utility, installing VirtualBox certificates";
1476 siCertUtilAdd.mArguments.push_back(Utf8Str("add-trusted-publisher"));
1477 siCertUtilAdd.mArguments.push_back(Utf8Str("--root")); /* Add root certificate as well. */
1478 siCertUtilAdd.mArguments.push_back(Utf8Str(strUpdateDir + "oracle-vbox.cer"));
1479 siCertUtilAdd.mArguments.push_back(Utf8Str(strUpdateDir + "oracle-vbox.cer"));
1480 mFiles.push_back(InstallerFile("CERT/VBOXCERTUTIL.EXE",
1481 strUpdateDir + "VBoxCertUtil.exe",
1482 UPDATEFILE_FLAG_EXECUTE | UPDATEFILE_FLAG_OPTIONAL,
1483 siCertUtilAdd));
1484 }
1485 /* The installers in different flavors, as we don't know (and can't assume)
1486 * the guest's bitness. */
1487 mFiles.push_back(InstallerFile("VBOXWINDOWSADDITIONS_X86.EXE",
1488 strUpdateDir + "VBoxWindowsAdditions-x86.exe",
1489 UPDATEFILE_FLAG_COPY_FROM_ISO));
1490 mFiles.push_back(InstallerFile("VBOXWINDOWSADDITIONS_AMD64.EXE",
1491 strUpdateDir + "VBoxWindowsAdditions-amd64.exe",
1492 UPDATEFILE_FLAG_COPY_FROM_ISO));
1493 /* The stub loader which decides which flavor to run. */
1494 GuestProcessStartupInfo siInstaller;
1495 siInstaller.mName = "VirtualBox Windows Guest Additions Installer";
1496 /* Set a running timeout of 5 minutes -- the Windows Guest Additions
1497 * setup can take quite a while, so be on the safe side. */
1498 siInstaller.mTimeoutMS = 5 * 60 * 1000;
1499 siInstaller.mArguments.push_back(Utf8Str("/S")); /* We want to install in silent mode. */
1500 siInstaller.mArguments.push_back(Utf8Str("/l")); /* ... and logging enabled. */
1501 /* Don't quit VBoxService during upgrade because it still is used for this
1502 * piece of code we're in right now (that is, here!) ... */
1503 siInstaller.mArguments.push_back(Utf8Str("/no_vboxservice_exit"));
1504 /* Tell the installer to report its current installation status
1505 * using a running VBoxTray instance via balloon messages in the
1506 * Windows taskbar. */
1507 siInstaller.mArguments.push_back(Utf8Str("/post_installstatus"));
1508 /* Add optional installer command line arguments from the API to the
1509 * installer's startup info. */
1510 rc = i_addProcessArguments(siInstaller.mArguments, mArguments);
1511 AssertRC(rc);
1512 /* If the caller does not want to wait for out guest update process to end,
1513 * complete the progress object now so that the caller can do other work. */
1514 if (mFlags & AdditionsUpdateFlag_WaitForUpdateStartOnly)
1515 siInstaller.mFlags |= ProcessCreateFlag_WaitForProcessStartOnly;
1516 mFiles.push_back(InstallerFile("VBOXWINDOWSADDITIONS.EXE",
1517 strUpdateDir + "VBoxWindowsAdditions.exe",
1518 UPDATEFILE_FLAG_COPY_FROM_ISO | UPDATEFILE_FLAG_EXECUTE, siInstaller));
1519 break;
1520 }
1521 case eOSType_Linux:
1522 /** @todo Add Linux support. */
1523 break;
1524 case eOSType_Solaris:
1525 /** @todo Add Solaris support. */
1526 break;
1527 default:
1528 AssertReleaseMsgFailed(("Unsupported guest type: %d\n", osType));
1529 break;
1530 }
1531 }
1532
1533 if (RT_SUCCESS(rc))
1534 {
1535 /* We want to spend 40% total for all copying operations. So roughly
1536 * calculate the specific percentage step of each copied file. */
1537 uint8_t uOffset = 20; /* Start at 20%. */
1538 uint8_t uStep = 40 / (uint8_t)mFiles.size(); Assert(mFiles.size() <= 10);
1539
1540 LogRel(("Copying over Guest Additions update files to the guest ...\n"));
1541
1542 std::vector<InstallerFile>::const_iterator itFiles = mFiles.begin();
1543 while (itFiles != mFiles.end())
1544 {
1545 if (itFiles->fFlags & UPDATEFILE_FLAG_COPY_FROM_ISO)
1546 {
1547 bool fOptional = false;
1548 if (itFiles->fFlags & UPDATEFILE_FLAG_OPTIONAL)
1549 fOptional = true;
1550 rc = i_copyFileToGuest(pSession, &iso, itFiles->strSource, itFiles->strDest,
1551 fOptional, NULL /* cbSize */);
1552 if (RT_FAILURE(rc))
1553 {
1554 hr = setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1555 Utf8StrFmt(GuestSession::tr("Error while copying file \"%s\" to \"%s\" on the guest: %Rrc"),
1556 itFiles->strSource.c_str(), itFiles->strDest.c_str(), rc));
1557 break;
1558 }
1559 }
1560
1561 rc = setProgress(uOffset);
1562 if (RT_FAILURE(rc))
1563 break;
1564 uOffset += uStep;
1565
1566 ++itFiles;
1567 }
1568 }
1569
1570 /* Done copying, close .ISO file. */
1571 RTIsoFsClose(&iso);
1572
1573 if (RT_SUCCESS(rc))
1574 {
1575 /* We want to spend 35% total for all copying operations. So roughly
1576 * calculate the specific percentage step of each copied file. */
1577 uint8_t uOffset = 60; /* Start at 60%. */
1578 uint8_t uStep = 35 / (uint8_t)mFiles.size(); Assert(mFiles.size() <= 10);
1579
1580 LogRel(("Executing Guest Additions update files ...\n"));
1581
1582 std::vector<InstallerFile>::iterator itFiles = mFiles.begin();
1583 while (itFiles != mFiles.end())
1584 {
1585 if (itFiles->fFlags & UPDATEFILE_FLAG_EXECUTE)
1586 {
1587 rc = i_runFileOnGuest(pSession, itFiles->mProcInfo);
1588 if (RT_FAILURE(rc))
1589 break;
1590 }
1591
1592 rc = setProgress(uOffset);
1593 if (RT_FAILURE(rc))
1594 break;
1595 uOffset += uStep;
1596
1597 ++itFiles;
1598 }
1599 }
1600
1601 if (RT_SUCCESS(rc))
1602 {
1603 LogRel(("Automatic update of Guest Additions succeeded\n"));
1604 rc = setProgressSuccess();
1605 }
1606 }
1607 }
1608
1609 if (RT_FAILURE(rc))
1610 {
1611 if (rc == VERR_CANCELLED)
1612 {
1613 LogRel(("Automatic update of Guest Additions was canceled\n"));
1614
1615 hr = setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1616 Utf8StrFmt(GuestSession::tr("Installation was canceled")));
1617 }
1618 else
1619 {
1620 Utf8Str strError = Utf8StrFmt("No further error information available (%Rrc)", rc);
1621 if (!mProgress.isNull()) /* Progress object is optional. */
1622 {
1623 com::ProgressErrorInfo errorInfo(mProgress);
1624 if ( errorInfo.isFullAvailable()
1625 || errorInfo.isBasicAvailable())
1626 {
1627 strError = errorInfo.getText();
1628 }
1629 }
1630
1631 LogRel(("Automatic update of Guest Additions failed: %s (%Rhrc)\n",
1632 strError.c_str(), hr));
1633 }
1634
1635 LogRel(("Please install Guest Additions manually\n"));
1636 }
1637
1638 /** @todo Clean up copied / left over installation files. */
1639
1640 LogFlowFuncLeaveRC(rc);
1641 return rc;
1642}
1643
1644int SessionTaskUpdateAdditions::RunAsync(const Utf8Str &strDesc, ComObjPtr<Progress> &pProgress)
1645{
1646 LogFlowThisFunc(("strDesc=%s, strSource=%s, uFlags=%x\n",
1647 strDesc.c_str(), mSource.c_str(), mFlags));
1648
1649 mDesc = strDesc;
1650 mProgress = pProgress;
1651
1652 int rc = RTThreadCreate(NULL, SessionTaskUpdateAdditions::taskThread, this,
1653 0, RTTHREADTYPE_MAIN_HEAVY_WORKER, 0,
1654 "gctlUpGA");
1655 LogFlowFuncLeaveRC(rc);
1656 return rc;
1657}
1658
1659/* static */
1660DECLCALLBACK(int) SessionTaskUpdateAdditions::taskThread(RTTHREAD Thread, void *pvUser)
1661{
1662 SessionTaskUpdateAdditions* task = static_cast<SessionTaskUpdateAdditions*>(pvUser);
1663 AssertReturn(task, VERR_GENERAL_FAILURE);
1664
1665 LogFlowFunc(("pTask=%p\n", task));
1666
1667 return task->Run();
1668}
1669
Note: See TracBrowser for help on using the repository browser.

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette