VirtualBox

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

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

*: scm cleanup run.

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