VirtualBox

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

Last change on this file since 46524 was 46524, checked in by vboxsync, 12 years ago

Main/IGuest::UpdateGuestAdditions: Implemented support for passing optional command line arguments to the performing installer on the guest (untested).

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