VirtualBox

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

Last change on this file since 51217 was 51092, checked in by vboxsync, 11 years ago

6813 src-client/MachineDebuggerImpl.cpp + various formatting changes

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