VirtualBox

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

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

pr7179. Fixes and improvement in the classes GuestSessionTask, GuestSession, GuestProcess, ThreadTask

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