VirtualBox

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

Last change on this file since 55043 was 53873, checked in by vboxsync, 10 years ago

Main/include: remove some unneeded includes, they created an unnecessary dependency

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