VirtualBox

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

Last change on this file since 49517 was 49501, checked in by vboxsync, 11 years ago

Uninitialized variable.

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