VirtualBox

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

Last change on this file since 48535 was 47905, checked in by vboxsync, 11 years ago

Main: warnings.

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