VirtualBox

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

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

6813 - DisplayImpl using COM Wrappers

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