VirtualBox

source: vbox/trunk/src/VBox/Main/src-client/GuestCtrlImplTasks.cpp@ 38579

Last change on this file since 38579 was 38579, checked in by vboxsync, 14 years ago

Main/GuestCtrl: Handle files correctly where the file size can be retrieved but content cannot be read due to limited access rights.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 46.8 KB
Line 
1/* $Id: */
2/** @file
3 * VirtualBox Guest Control - Threaded operations (tasks).
4 */
5
6/*
7 * Copyright (C) 2011 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.215389.xyz. 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#include <memory>
19
20#include "GuestImpl.h"
21#include "GuestCtrlImplPrivate.h"
22
23#include "Global.h"
24#include "ConsoleImpl.h"
25#include "ProgressImpl.h"
26#include "VMMDev.h"
27
28#include "AutoCaller.h"
29#include "Logging.h"
30
31#include <VBox/VMMDev.h>
32#ifdef VBOX_WITH_GUEST_CONTROL
33# include <VBox/com/array.h>
34# include <VBox/com/ErrorInfo.h>
35#endif
36
37#include <iprt/file.h>
38#include <iprt/isofs.h>
39#include <iprt/list.h>
40#include <iprt/path.h>
41
42GuestTask::GuestTask(TaskType aTaskType, Guest *aThat, Progress *aProgress)
43 : taskType(aTaskType),
44 pGuest(aThat),
45 progress(aProgress),
46 rc(S_OK)
47{
48
49}
50
51GuestTask::~GuestTask()
52{
53
54}
55
56int GuestTask::startThread()
57{
58 return RTThreadCreate(NULL, GuestTask::taskThread, this,
59 0, RTTHREADTYPE_MAIN_HEAVY_WORKER, 0,
60 "GuestTask");
61}
62
63/* static */
64DECLCALLBACK(int) GuestTask::taskThread(RTTHREAD /* aThread */, void *pvUser)
65{
66 std::auto_ptr<GuestTask> task(static_cast<GuestTask*>(pvUser));
67 AssertReturn(task.get(), VERR_GENERAL_FAILURE);
68
69 Guest *pGuest = task->pGuest;
70
71 LogFlowFuncEnter();
72 LogFlowFunc(("Guest %p\n", pGuest));
73
74 HRESULT rc = S_OK;
75
76 switch (task->taskType)
77 {
78#ifdef VBOX_WITH_GUEST_CONTROL
79 case TaskType_CopyFileToGuest:
80 {
81 rc = pGuest->taskCopyFileToGuest(task.get());
82 break;
83 }
84 case TaskType_CopyFileFromGuest:
85 {
86 rc = pGuest->taskCopyFileFromGuest(task.get());
87 break;
88 }
89 case TaskType_UpdateGuestAdditions:
90 {
91 rc = pGuest->taskUpdateGuestAdditions(task.get());
92 break;
93 }
94#endif
95 default:
96 AssertMsgFailed(("Invalid task type %u specified!\n", task->taskType));
97 break;
98 }
99
100 LogFlowFunc(("rc=%Rhrc\n", rc));
101 LogFlowFuncLeave();
102
103 return VINF_SUCCESS;
104}
105
106/* static */
107int GuestTask::uploadProgress(unsigned uPercent, void *pvUser)
108{
109 GuestTask *pTask = *(GuestTask**)pvUser;
110
111 if ( pTask
112 && !pTask->progress.isNull())
113 {
114 BOOL fCanceled;
115 pTask->progress->COMGETTER(Canceled)(&fCanceled);
116 if (fCanceled)
117 return -1;
118 pTask->progress->SetCurrentOperationProgress(uPercent);
119 }
120 return VINF_SUCCESS;
121}
122
123/* static */
124HRESULT GuestTask::setProgressErrorInfo(HRESULT hr, ComObjPtr<Progress> pProgress,
125 const char *pszText, ...)
126{
127 BOOL fCanceled;
128 BOOL fCompleted;
129 if ( SUCCEEDED(pProgress->COMGETTER(Canceled(&fCanceled)))
130 && !fCanceled
131 && SUCCEEDED(pProgress->COMGETTER(Completed(&fCompleted)))
132 && !fCompleted)
133 {
134 va_list va;
135 va_start(va, pszText);
136 HRESULT hr2 = pProgress->notifyCompleteV(hr,
137 COM_IIDOF(IGuest),
138 Guest::getStaticComponentName(),
139 pszText,
140 va);
141 va_end(va);
142 if (hr2 == S_OK) /* If unable to retrieve error, return input error. */
143 hr2 = hr;
144 return hr2;
145 }
146 return S_OK;
147}
148
149/* static */
150HRESULT GuestTask::setProgressErrorInfo(HRESULT hr,
151 ComObjPtr<Progress> pProgress, ComObjPtr<Guest> pGuest)
152{
153 return setProgressErrorInfo(hr, pProgress,
154 Utf8Str(com::ErrorInfo((IGuest*)pGuest, COM_IIDOF(IGuest)).getText()).c_str());
155}
156
157#ifdef VBOX_WITH_GUEST_CONTROL
158HRESULT Guest::taskCopyFileToGuest(GuestTask *aTask)
159{
160 LogFlowFuncEnter();
161
162 AutoCaller autoCaller(this);
163 if (FAILED(autoCaller.rc())) return autoCaller.rc();
164
165 /*
166 * Do *not* take a write lock here since we don't (and won't)
167 * touch any class-specific data (of IGuest) here - only the member functions
168 * which get called here can do that.
169 */
170
171 HRESULT rc = S_OK;
172
173 try
174 {
175 Guest *pGuest = aTask->pGuest;
176 AssertPtr(pGuest);
177
178 /* Does our source file exist? */
179 if (!RTFileExists(aTask->strSource.c_str()))
180 {
181 rc = GuestTask::setProgressErrorInfo(VBOX_E_IPRT_ERROR, aTask->progress,
182 Guest::tr("Source file \"%s\" does not exist, or is not a file"),
183 aTask->strSource.c_str());
184 }
185 else
186 {
187 RTFILE fileSource;
188 int vrc = RTFileOpen(&fileSource, aTask->strSource.c_str(),
189 RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_WRITE);
190 if (RT_FAILURE(vrc))
191 {
192 rc = GuestTask::setProgressErrorInfo(VBOX_E_IPRT_ERROR, aTask->progress,
193 Guest::tr("Could not open source file \"%s\" for reading (%Rrc)"),
194 aTask->strSource.c_str(), vrc);
195 }
196 else
197 {
198 uint64_t cbSize;
199 vrc = RTFileGetSize(fileSource, &cbSize);
200 if (RT_FAILURE(vrc))
201 {
202 rc = GuestTask::setProgressErrorInfo(VBOX_E_IPRT_ERROR, aTask->progress,
203 Guest::tr("Could not query file size of \"%s\" (%Rrc)"),
204 aTask->strSource.c_str(), vrc);
205 }
206 else
207 {
208 com::SafeArray<IN_BSTR> args;
209 com::SafeArray<IN_BSTR> env;
210
211 /*
212 * Prepare tool command line.
213 */
214 char szOutput[RTPATH_MAX];
215 if (RTStrPrintf(szOutput, sizeof(szOutput), "--output=%s", aTask->strDest.c_str()) <= sizeof(szOutput) - 1)
216 {
217 /*
218 * Normalize path slashes, based on the detected guest.
219 */
220 Utf8Str osType = mData.mOSTypeId;
221 if ( osType.contains("Microsoft", Utf8Str::CaseInsensitive)
222 || osType.contains("Windows", Utf8Str::CaseInsensitive))
223 {
224 /* We have a Windows guest. */
225 RTPathChangeToDosSlashes(szOutput, true /* Force conversion. */);
226 }
227 else /* ... or something which isn't from Redmond ... */
228 {
229 RTPathChangeToUnixSlashes(szOutput, true /* Force conversion. */);
230 }
231
232 args.push_back(Bstr(szOutput).raw()); /* We want to write a file ... */
233 }
234 else
235 {
236 rc = GuestTask::setProgressErrorInfo(VBOX_E_IPRT_ERROR, aTask->progress,
237 Guest::tr("Error preparing command line"));
238 }
239
240 ComPtr<IProgress> execProgress;
241 ULONG uPID;
242 if (SUCCEEDED(rc))
243 {
244 LogRel(("Copying file \"%s\" to guest \"%s\" (%u bytes) ...\n",
245 aTask->strSource.c_str(), aTask->strDest.c_str(), cbSize));
246 /*
247 * Okay, since we gathered all stuff we need until now to start the
248 * actual copying, start the guest part now.
249 */
250 rc = pGuest->ExecuteProcess(Bstr(VBOXSERVICE_TOOL_CAT).raw(),
251 ExecuteProcessFlag_Hidden
252 | ExecuteProcessFlag_WaitForProcessStartOnly,
253 ComSafeArrayAsInParam(args),
254 ComSafeArrayAsInParam(env),
255 Bstr(aTask->strUserName).raw(),
256 Bstr(aTask->strPassword).raw(),
257 5 * 1000 /* Wait 5s for getting the process started. */,
258 &uPID, execProgress.asOutParam());
259 if (FAILED(rc))
260 rc = GuestTask::setProgressErrorInfo(rc, aTask->progress, pGuest);
261 }
262
263 if (SUCCEEDED(rc))
264 {
265 BOOL fCompleted = FALSE;
266 BOOL fCanceled = FALSE;
267
268 size_t cbToRead = cbSize;
269 size_t cbTransfered = 0;
270 size_t cbRead;
271 SafeArray<BYTE> aInputData(_64K);
272 while ( SUCCEEDED(execProgress->COMGETTER(Completed(&fCompleted)))
273 && !fCompleted)
274 {
275 if (!cbToRead)
276 cbRead = 0;
277 else
278 {
279 vrc = RTFileRead(fileSource, (uint8_t*)aInputData.raw(),
280 RT_MIN(cbToRead, _64K), &cbRead);
281 /*
282 * Some other error occured? There might be a chance that RTFileRead
283 * could not resolve/map the native error code to an IPRT code, so just
284 * print a generic error.
285 */
286 if (RT_FAILURE(vrc))
287 {
288 rc = GuestTask::setProgressErrorInfo(VBOX_E_IPRT_ERROR, aTask->progress,
289 Guest::tr("Could not read from file \"%s\" (%Rrc)"),
290 aTask->strSource.c_str(), vrc);
291 break;
292 }
293 }
294
295 /* Resize buffer to reflect amount we just have read.
296 * Size 0 is allowed! */
297 aInputData.resize(cbRead);
298
299 ULONG uFlags = ProcessInputFlag_None;
300 /* Did we reach the end of the content we want to transfer (last chunk)? */
301 if ( (cbRead < _64K)
302 /* Did we reach the last block which is exactly _64K? */
303 || (cbToRead - cbRead == 0)
304 /* ... or does the user want to cancel? */
305 || ( SUCCEEDED(aTask->progress->COMGETTER(Canceled(&fCanceled)))
306 && fCanceled)
307 )
308 {
309 uFlags |= ProcessInputFlag_EndOfFile;
310 }
311
312 /* Transfer the current chunk ... */
313 ULONG uBytesWritten;
314 rc = pGuest->SetProcessInput(uPID, uFlags,
315 10 * 1000 /* Wait 10s for getting the input data transfered. */,
316 ComSafeArrayAsInParam(aInputData), &uBytesWritten);
317 if (FAILED(rc))
318 {
319 rc = GuestTask::setProgressErrorInfo(rc, aTask->progress, pGuest);
320 break;
321 }
322
323 Assert(cbRead <= cbToRead);
324 Assert(cbToRead >= cbRead);
325 cbToRead -= cbRead;
326
327 cbTransfered += uBytesWritten;
328 Assert(cbTransfered <= cbSize);
329 aTask->progress->SetCurrentOperationProgress(cbTransfered / (cbSize / 100.0));
330
331 /* End of file reached? */
332 if (cbToRead == 0)
333 break;
334
335 /* Did the user cancel the operation above? */
336 if (fCanceled)
337 break;
338
339 /* Progress canceled by Main API? */
340 if ( SUCCEEDED(execProgress->COMGETTER(Canceled(&fCanceled)))
341 && fCanceled)
342 {
343 rc = GuestTask::setProgressErrorInfo(VBOX_E_IPRT_ERROR, aTask->progress,
344 Guest::tr("Copy operation of file \"%s\" was canceled on guest side"),
345 aTask->strSource.c_str());
346 break;
347 }
348 }
349
350 if (SUCCEEDED(rc))
351 {
352 /*
353 * If we got here this means the started process either was completed,
354 * canceled or we simply got all stuff transferred.
355 */
356 ExecuteProcessStatus_T retStatus;
357 ULONG uRetExitCode;
358 rc = pGuest->executeWaitForStatusChange(uPID, 10 * 1000 /* 10s timeout. */,
359 &retStatus, &uRetExitCode);
360 if (FAILED(rc))
361 {
362 rc = GuestTask::setProgressErrorInfo(rc, aTask->progress, pGuest);
363 }
364 else
365 {
366 if ( uRetExitCode != 0
367 || retStatus != ExecuteProcessStatus_TerminatedNormally)
368 {
369 rc = GuestTask::setProgressErrorInfo(VBOX_E_IPRT_ERROR, aTask->progress,
370 Guest::tr("Guest reported error %u while copying file \"%s\" to \"%s\""),
371 uRetExitCode, aTask->strSource.c_str(), aTask->strDest.c_str());
372 }
373 }
374 }
375
376 if (SUCCEEDED(rc))
377 {
378 if (fCanceled)
379 {
380 /*
381 * In order to make the progress object to behave nicely, we also have to
382 * notify the object with a complete event when it's canceled.
383 */
384 aTask->progress->notifyComplete(VBOX_E_IPRT_ERROR,
385 COM_IIDOF(IGuest),
386 Guest::getStaticComponentName(),
387 Guest::tr("Copying file \"%s\" canceled"), aTask->strSource.c_str());
388 }
389 else
390 {
391 /*
392 * Even if we succeeded until here make sure to check whether we really transfered
393 * everything.
394 */
395 if ( cbSize > 0
396 && cbTransfered == 0)
397 {
398 /* If nothing was transfered but the file size was > 0 then "vbox_cat" wasn't able to write
399 * to the destination -> access denied. */
400 rc = GuestTask::setProgressErrorInfo(VBOX_E_IPRT_ERROR, aTask->progress,
401 Guest::tr("Access denied when copying file \"%s\" to \"%s\""),
402 aTask->strSource.c_str(), aTask->strDest.c_str());
403 }
404 else if (cbTransfered < cbSize)
405 {
406 /* If we did not copy all let the user know. */
407 rc = GuestTask::setProgressErrorInfo(VBOX_E_IPRT_ERROR, aTask->progress,
408 Guest::tr("Copying file \"%s\" failed (%u/%u bytes transfered)"),
409 aTask->strSource.c_str(), cbTransfered, cbSize);
410 }
411 else /* Yay, all went fine! */
412 aTask->progress->notifyComplete(S_OK);
413 }
414 }
415 }
416 }
417 RTFileClose(fileSource);
418 }
419 }
420 }
421 catch (HRESULT aRC)
422 {
423 rc = aRC;
424 }
425
426 /* Clean up */
427 aTask->rc = rc;
428
429 LogFlowFunc(("rc=%Rhrc\n", rc));
430 LogFlowFuncLeave();
431
432 return VINF_SUCCESS;
433}
434
435HRESULT Guest::taskCopyFileFromGuest(GuestTask *aTask)
436{
437 LogFlowFuncEnter();
438
439 AutoCaller autoCaller(this);
440 if (FAILED(autoCaller.rc())) return autoCaller.rc();
441
442 /*
443 * Do *not* take a write lock here since we don't (and won't)
444 * touch any class-specific data (of IGuest) here - only the member functions
445 * which get called here can do that.
446 */
447
448 HRESULT rc = S_OK;
449
450 try
451 {
452 Guest *pGuest = aTask->pGuest;
453 AssertPtr(pGuest);
454
455 /* Does our source file exist? */
456 BOOL fFileExists;
457 rc = pGuest->FileExists(Bstr(aTask->strSource).raw(),
458 Bstr(aTask->strUserName).raw(), Bstr(aTask->strPassword).raw(),
459 &fFileExists);
460 if (SUCCEEDED(rc))
461 {
462 if (!fFileExists)
463 rc = GuestTask::setProgressErrorInfo(VBOX_E_IPRT_ERROR, aTask->progress,
464 Guest::tr("Source file \"%s\" does not exist, or is not a file"),
465 aTask->strSource.c_str());
466 }
467
468 /* Query file size to make an estimate for our progress object. */
469 if (SUCCEEDED(rc))
470 {
471 LONG64 lFileSize;
472 rc = pGuest->FileQuerySize(Bstr(aTask->strSource).raw(),
473 Bstr(aTask->strUserName).raw(), Bstr(aTask->strPassword).raw(),
474 &lFileSize);
475 if (FAILED(rc))
476 rc = GuestTask::setProgressErrorInfo(rc, aTask->progress, pGuest);
477
478 com::SafeArray<IN_BSTR> args;
479 com::SafeArray<IN_BSTR> env;
480
481 if (SUCCEEDED(rc))
482 {
483 /*
484 * Prepare tool command line.
485 */
486 char szSource[RTPATH_MAX];
487 if (RTStrPrintf(szSource, sizeof(szSource), "%s", aTask->strSource.c_str()) <= sizeof(szSource) - 1)
488 {
489 /*
490 * Normalize path slashes, based on the detected guest.
491 */
492 Utf8Str osType = mData.mOSTypeId;
493 if ( osType.contains("Microsoft", Utf8Str::CaseInsensitive)
494 || osType.contains("Windows", Utf8Str::CaseInsensitive))
495 {
496 /* We have a Windows guest. */
497 RTPathChangeToDosSlashes(szSource, true /* Force conversion. */);
498 }
499 else /* ... or something which isn't from Redmond ... */
500 {
501 RTPathChangeToUnixSlashes(szSource, true /* Force conversion. */);
502 }
503
504 args.push_back(Bstr(szSource).raw()); /* Tell our cat tool which file to output. */
505 }
506 else
507 rc = GuestTask::setProgressErrorInfo(VBOX_E_IPRT_ERROR, aTask->progress,
508 Guest::tr("Error preparing command line"));
509 }
510
511 ComPtr<IProgress> execProgress;
512 ULONG uPID;
513 if (SUCCEEDED(rc))
514 {
515 LogRel(("Copying file \"%s\" to host \"%s\" (%u bytes) ...\n",
516 aTask->strSource.c_str(), aTask->strDest.c_str(), lFileSize));
517
518 /*
519 * Okay, since we gathered all stuff we need until now to start the
520 * actual copying, start the guest part now.
521 */
522 rc = pGuest->ExecuteProcess(Bstr(VBOXSERVICE_TOOL_CAT).raw(),
523 ExecuteProcessFlag_Hidden,
524 ComSafeArrayAsInParam(args),
525 ComSafeArrayAsInParam(env),
526 Bstr(aTask->strUserName).raw(),
527 Bstr(aTask->strPassword).raw(),
528 5 * 1000 /* Wait 5s for getting the process started. */,
529 &uPID, execProgress.asOutParam());
530 if (FAILED(rc))
531 rc = GuestTask::setProgressErrorInfo(rc, aTask->progress, pGuest);
532 }
533
534 if (SUCCEEDED(rc))
535 {
536 BOOL fCompleted = FALSE;
537 BOOL fCanceled = FALSE;
538
539 RTFILE hFileDest;
540 int vrc = RTFileOpen(&hFileDest, aTask->strDest.c_str(),
541 RTFILE_O_WRITE | RTFILE_O_OPEN_CREATE | RTFILE_O_DENY_WRITE);
542 if (RT_FAILURE(vrc))
543 rc = GuestTask::setProgressErrorInfo(VBOX_E_IPRT_ERROR, aTask->progress,
544 Guest::tr("Unable to create/open destination file \"%s\", rc=%Rrc"),
545 aTask->strDest.c_str(), vrc);
546 else
547 {
548 size_t cbToRead = lFileSize;
549 size_t cbTransfered = 0;
550 SafeArray<BYTE> aOutputData(_64K);
551 while (SUCCEEDED(execProgress->COMGETTER(Completed(&fCompleted))))
552 {
553 rc = this->GetProcessOutput(uPID, ProcessOutputFlag_None,
554 10 * 1000 /* Timeout in ms */,
555 _64K, ComSafeArrayAsOutParam(aOutputData));
556 if (SUCCEEDED(rc))
557 {
558 if (!aOutputData.size())
559 {
560 /*
561 * Only bitch about an unexpected end of a file when there already
562 * was data read from that file. If this was the very first read we can
563 * be (almost) sure that this file is not meant to be read by the specified user.
564 */
565 if ( cbTransfered
566 && cbToRead)
567 {
568 rc = GuestTask::setProgressErrorInfo(VBOX_E_IPRT_ERROR, aTask->progress,
569 Guest::tr("Unexpected end of file \"%s\" (%u bytes left, %u bytes written)"),
570 aTask->strSource.c_str(), cbToRead, cbTransfered);
571 }
572 break;
573 }
574
575 vrc = RTFileWrite(hFileDest, aOutputData.raw(), aOutputData.size(), NULL /* No partial writes */);
576 if (RT_FAILURE(vrc))
577 {
578 rc = GuestTask::setProgressErrorInfo(VBOX_E_IPRT_ERROR, aTask->progress,
579 Guest::tr("Error writing to file \"%s\" (%u bytes left), rc=%Rrc"),
580 aTask->strSource.c_str(), cbToRead, vrc);
581 break;
582 }
583
584 cbToRead -= aOutputData.size();
585 cbTransfered += aOutputData.size();
586
587 aTask->progress->SetCurrentOperationProgress(cbTransfered / (lFileSize / 100.0));
588 }
589 else
590 {
591 rc = GuestTask::setProgressErrorInfo(rc, aTask->progress, pGuest);
592 break;
593 }
594 }
595
596 if (SUCCEEDED(rc))
597 aTask->progress->notifyComplete(S_OK);
598
599 RTFileClose(hFileDest);
600 }
601 }
602 }
603 }
604 catch (HRESULT aRC)
605 {
606 rc = aRC;
607 }
608
609 /* Clean up */
610 aTask->rc = rc;
611
612 LogFlowFunc(("rc=%Rhrc\n", rc));
613 LogFlowFuncLeave();
614
615 return VINF_SUCCESS;
616}
617
618HRESULT Guest::taskUpdateGuestAdditions(GuestTask *aTask)
619{
620 LogFlowFuncEnter();
621
622 AutoCaller autoCaller(this);
623 if (FAILED(autoCaller.rc())) return autoCaller.rc();
624
625 /*
626 * Do *not* take a write lock here since we don't (and won't)
627 * touch any class-specific data (of IGuest) here - only the member functions
628 * which get called here can do that.
629 */
630
631 HRESULT rc = S_OK;
632 BOOL fCompleted;
633 BOOL fCanceled;
634
635 try
636 {
637 Guest *pGuest = aTask->pGuest;
638 AssertPtr(pGuest);
639
640 aTask->progress->SetCurrentOperationProgress(10);
641
642 /*
643 * Determine guest OS type and the required installer image.
644 * At the moment only Windows guests are supported.
645 */
646 Utf8Str installerImage;
647 Bstr osTypeId;
648 if ( SUCCEEDED(pGuest->COMGETTER(OSTypeId(osTypeId.asOutParam())))
649 && !osTypeId.isEmpty())
650 {
651 Utf8Str osTypeIdUtf8(osTypeId); /* Needed for .contains(). */
652 if ( osTypeIdUtf8.contains("Microsoft", Utf8Str::CaseInsensitive)
653 || osTypeIdUtf8.contains("Windows", Utf8Str::CaseInsensitive))
654 {
655 if (osTypeIdUtf8.contains("64", Utf8Str::CaseInsensitive))
656 installerImage = "VBOXWINDOWSADDITIONS_AMD64.EXE";
657 else
658 installerImage = "VBOXWINDOWSADDITIONS_X86.EXE";
659 /* Since the installers are located in the root directory,
660 * no further path processing needs to be done (yet). */
661 }
662 else /* Everything else is not supported (yet). */
663 throw GuestTask::setProgressErrorInfo(VBOX_E_NOT_SUPPORTED, aTask->progress,
664 Guest::tr("Detected guest OS (%s) does not support automatic Guest Additions updating, please update manually"),
665 osTypeIdUtf8.c_str());
666 }
667 else
668 throw GuestTask::setProgressErrorInfo(VBOX_E_NOT_SUPPORTED, aTask->progress,
669 Guest::tr("Could not detected guest OS type/version, please update manually"));
670 Assert(!installerImage.isEmpty());
671
672 /*
673 * Try to open the .ISO file and locate the specified installer.
674 */
675 RTISOFSFILE iso;
676 int vrc = RTIsoFsOpen(&iso, aTask->strSource.c_str());
677 if (RT_FAILURE(vrc))
678 {
679 rc = GuestTask::setProgressErrorInfo(VBOX_E_FILE_ERROR, aTask->progress,
680 Guest::tr("Invalid installation medium detected: \"%s\""),
681 aTask->strSource.c_str());
682 }
683 else
684 {
685 uint32_t cbOffset;
686 size_t cbLength;
687 vrc = RTIsoFsGetFileInfo(&iso, installerImage.c_str(), &cbOffset, &cbLength);
688 if ( RT_SUCCESS(vrc)
689 && cbOffset
690 && cbLength)
691 {
692 vrc = RTFileSeek(iso.file, cbOffset, RTFILE_SEEK_BEGIN, NULL);
693 if (RT_FAILURE(vrc))
694 rc = GuestTask::setProgressErrorInfo(VBOX_E_IPRT_ERROR, aTask->progress,
695 Guest::tr("Could not seek to setup file on installation medium \"%s\" (%Rrc)"),
696 aTask->strSource.c_str(), vrc);
697 }
698 else
699 {
700 switch (vrc)
701 {
702 case VERR_FILE_NOT_FOUND:
703 rc = GuestTask::setProgressErrorInfo(VBOX_E_IPRT_ERROR, aTask->progress,
704 Guest::tr("Setup file was not found on installation medium \"%s\""),
705 aTask->strSource.c_str());
706 break;
707
708 default:
709 rc = GuestTask::setProgressErrorInfo(VBOX_E_IPRT_ERROR, aTask->progress,
710 Guest::tr("An unknown error (%Rrc) occured while retrieving information of setup file on installation medium \"%s\""),
711 vrc, aTask->strSource.c_str());
712 break;
713 }
714 }
715
716 /* Specify the ouput path on the guest side. */
717 Utf8Str strInstallerPath = "%TEMP%\\VBoxWindowsAdditions.exe";
718
719 if (RT_SUCCESS(vrc))
720 {
721 /* Okay, we're ready to start our copy routine on the guest! */
722 aTask->progress->SetCurrentOperationProgress(15);
723
724 /* Prepare command line args. */
725 com::SafeArray<IN_BSTR> args;
726 com::SafeArray<IN_BSTR> env;
727
728 args.push_back(Bstr("--output").raw()); /* We want to write a file ... */
729 args.push_back(Bstr(strInstallerPath.c_str()).raw()); /* ... with this path. */
730
731 if (SUCCEEDED(rc))
732 {
733 ComPtr<IProgress> progressCat;
734 ULONG uPID;
735
736 /*
737 * Start built-in "vbox_cat" tool (inside VBoxService) to
738 * copy over/pipe the data into a file on the guest (with
739 * system rights, no username/password specified).
740 */
741 rc = pGuest->executeProcessInternal(Bstr(VBOXSERVICE_TOOL_CAT).raw(),
742 ExecuteProcessFlag_Hidden
743 | ExecuteProcessFlag_WaitForProcessStartOnly,
744 ComSafeArrayAsInParam(args),
745 ComSafeArrayAsInParam(env),
746 Bstr("").raw() /* Username. */,
747 Bstr("").raw() /* Password */,
748 5 * 1000 /* Wait 5s for getting the process started. */,
749 &uPID, progressCat.asOutParam(), &vrc);
750 if (FAILED(rc))
751 {
752 /* Errors which return VBOX_E_NOT_SUPPORTED can be safely skipped by the caller
753 * to silently fall back to "normal" (old) .ISO mounting. */
754
755 /* Due to a very limited COM error range we use vrc for a more detailed error
756 * lookup to figure out what went wrong. */
757 switch (vrc)
758 {
759 /* Guest execution service is not (yet) ready. This basically means that either VBoxService
760 * is not running (yet) or that the Guest Additions are too old (because VBoxService does not
761 * support the guest execution feature in this version). */
762 case VERR_NOT_FOUND:
763 LogRel(("Guest Additions seem not to be installed yet\n"));
764 rc = GuestTask::setProgressErrorInfo(VBOX_E_NOT_SUPPORTED, aTask->progress,
765 Guest::tr("Guest Additions seem not to be installed or are not ready to update yet"));
766 break;
767
768 /* Getting back a VERR_INVALID_PARAMETER indicates that the installed Guest Additions are supporting the guest
769 * execution but not the built-in "vbox_cat" tool of VBoxService (< 4.0). */
770 case VERR_INVALID_PARAMETER:
771 LogRel(("Guest Additions are installed but don't supported automatic updating\n"));
772 rc = GuestTask::setProgressErrorInfo(VBOX_E_NOT_SUPPORTED, aTask->progress,
773 Guest::tr("Installed Guest Additions do not support automatic updating"));
774 break;
775
776 case VERR_TIMEOUT:
777 LogRel(("Guest was unable to start copying the Guest Additions setup within time\n"));
778 rc = GuestTask::setProgressErrorInfo(E_FAIL, aTask->progress,
779 Guest::tr("Guest was unable to start copying the Guest Additions setup within time"));
780 break;
781
782 default:
783 rc = GuestTask::setProgressErrorInfo(E_FAIL, aTask->progress,
784 Guest::tr("Error copying Guest Additions setup file to guest path \"%s\" (%Rrc)"),
785 strInstallerPath.c_str(), vrc);
786 break;
787 }
788 }
789 else
790 {
791 LogRel(("Automatic update of Guest Additions started, using \"%s\"\n", aTask->strSource.c_str()));
792 LogRel(("Copying Guest Additions installer \"%s\" to \"%s\" on guest ...\n",
793 installerImage.c_str(), strInstallerPath.c_str()));
794 aTask->progress->SetCurrentOperationProgress(20);
795
796 /* Wait for process to exit ... */
797 SafeArray<BYTE> aInputData(_64K);
798 while ( SUCCEEDED(progressCat->COMGETTER(Completed(&fCompleted)))
799 && !fCompleted)
800 {
801 size_t cbRead;
802 /* cbLength contains remaining bytes of our installer file
803 * opened above to read. */
804 size_t cbToRead = RT_MIN(cbLength, _64K);
805 if (cbToRead)
806 {
807 vrc = RTFileRead(iso.file, (uint8_t*)aInputData.raw(), cbToRead, &cbRead);
808 if ( cbRead
809 && RT_SUCCESS(vrc))
810 {
811 /* Resize buffer to reflect amount we just have read. */
812 if (cbRead > 0)
813 aInputData.resize(cbRead);
814
815 /* Did we reach the end of the content we want to transfer (last chunk)? */
816 ULONG uFlags = ProcessInputFlag_None;
817 if ( (cbRead < _64K)
818 /* Did we reach the last block which is exactly _64K? */
819 || (cbToRead - cbRead == 0)
820 /* ... or does the user want to cancel? */
821 || ( SUCCEEDED(aTask->progress->COMGETTER(Canceled(&fCanceled)))
822 && fCanceled)
823 )
824 {
825 uFlags |= ProcessInputFlag_EndOfFile;
826 }
827
828 /* Transfer the current chunk ... */
829 #ifdef DEBUG_andy
830 LogRel(("Copying Guest Additions (%u bytes left) ...\n", cbLength));
831 #endif
832 ULONG uBytesWritten;
833 rc = pGuest->SetProcessInput(uPID, uFlags,
834 10 * 1000 /* Wait 10s for getting the input data transfered. */,
835 ComSafeArrayAsInParam(aInputData), &uBytesWritten);
836 if (FAILED(rc))
837 {
838 rc = GuestTask::setProgressErrorInfo(rc, aTask->progress, pGuest);
839 break;
840 }
841
842 /* If task was canceled above also cancel the process execution. */
843 if (fCanceled)
844 progressCat->Cancel();
845
846 #ifdef DEBUG_andy
847 LogRel(("Copying Guest Additions (%u bytes written) ...\n", uBytesWritten));
848 #endif
849 Assert(cbLength >= uBytesWritten);
850 cbLength -= uBytesWritten;
851 }
852 else if (RT_FAILURE(vrc))
853 {
854 rc = GuestTask::setProgressErrorInfo(VBOX_E_IPRT_ERROR, aTask->progress,
855 Guest::tr("Error while reading setup file \"%s\" (To read: %u, Size: %u) from installation medium (%Rrc)"),
856 installerImage.c_str(), cbToRead, cbLength, vrc);
857 }
858 }
859
860 /* Internal progress canceled? */
861 if ( SUCCEEDED(progressCat->COMGETTER(Canceled(&fCanceled)))
862 && fCanceled)
863 {
864 aTask->progress->Cancel();
865 break;
866 }
867 }
868 }
869 }
870 }
871 RTIsoFsClose(&iso);
872
873 if ( SUCCEEDED(rc)
874 && ( SUCCEEDED(aTask->progress->COMGETTER(Canceled(&fCanceled)))
875 && !fCanceled
876 )
877 )
878 {
879 /*
880 * Installer was transferred successfully, so let's start it
881 * (with system rights).
882 */
883 LogRel(("Preparing to execute Guest Additions update ...\n"));
884 aTask->progress->SetCurrentOperationProgress(66);
885
886 /* Prepare command line args for installer. */
887 com::SafeArray<IN_BSTR> installerArgs;
888 com::SafeArray<IN_BSTR> installerEnv;
889
890 /** @todo Only Windows! */
891 installerArgs.push_back(Bstr(strInstallerPath).raw()); /* The actual (internal) installer image (as argv[0]). */
892 /* Note that starting at Windows Vista the lovely session 0 separation applies:
893 * This means that if we run an application with the profile/security context
894 * of VBoxService (system rights!) we're not able to show any UI. */
895 installerArgs.push_back(Bstr("/S").raw()); /* We want to install in silent mode. */
896 installerArgs.push_back(Bstr("/l").raw()); /* ... and logging enabled. */
897 /* Don't quit VBoxService during upgrade because it still is used for this
898 * piece of code we're in right now (that is, here!) ... */
899 installerArgs.push_back(Bstr("/no_vboxservice_exit").raw());
900 /* Tell the installer to report its current installation status
901 * using a running VBoxTray instance via balloon messages in the
902 * Windows taskbar. */
903 installerArgs.push_back(Bstr("/post_installstatus").raw());
904
905 /*
906 * Start the just copied over installer with system rights
907 * in silent mode on the guest. Don't use the hidden flag since there
908 * may be pop ups the user has to process.
909 */
910 ComPtr<IProgress> progressInstaller;
911 ULONG uPID;
912 rc = pGuest->executeProcessInternal(Bstr(strInstallerPath).raw(),
913 ExecuteProcessFlag_WaitForProcessStartOnly,
914 ComSafeArrayAsInParam(installerArgs),
915 ComSafeArrayAsInParam(installerEnv),
916 Bstr("").raw() /* Username */,
917 Bstr("").raw() /* Password */,
918 10 * 1000 /* Wait 10s for getting the process started */,
919 &uPID, progressInstaller.asOutParam(), &vrc);
920 if (SUCCEEDED(rc))
921 {
922 LogRel(("Guest Additions update is running ...\n"));
923
924 /* If the caller does not want to wait for out guest update process to end,
925 * complete the progress object now so that the caller can do other work. */
926 if (aTask->uFlags & AdditionsUpdateFlag_WaitForUpdateStartOnly)
927 aTask->progress->notifyComplete(S_OK);
928 else
929 aTask->progress->SetCurrentOperationProgress(70);
930
931 /* Wait until the Guest Additions installer finishes ... */
932 while ( SUCCEEDED(progressInstaller->COMGETTER(Completed(&fCompleted)))
933 && !fCompleted)
934 {
935 if ( SUCCEEDED(aTask->progress->COMGETTER(Canceled(&fCanceled)))
936 && fCanceled)
937 {
938 progressInstaller->Cancel();
939 break;
940 }
941 /* Progress canceled by Main API? */
942 if ( SUCCEEDED(progressInstaller->COMGETTER(Canceled(&fCanceled)))
943 && fCanceled)
944 {
945 break;
946 }
947 RTThreadSleep(100);
948 }
949
950 ExecuteProcessStatus_T retStatus;
951 ULONG uRetExitCode, uRetFlags;
952 rc = pGuest->GetProcessStatus(uPID, &uRetExitCode, &uRetFlags, &retStatus);
953 if (SUCCEEDED(rc))
954 {
955 if (fCompleted)
956 {
957 if (uRetExitCode == 0)
958 {
959 LogRel(("Guest Additions update successful!\n"));
960 if ( SUCCEEDED(aTask->progress->COMGETTER(Completed(&fCompleted)))
961 && !fCompleted)
962 aTask->progress->notifyComplete(S_OK);
963 }
964 else
965 {
966 LogRel(("Guest Additions update failed (Exit code=%u, Status=%u, Flags=%u)\n",
967 uRetExitCode, retStatus, uRetFlags));
968 rc = GuestTask::setProgressErrorInfo(VBOX_E_IPRT_ERROR, aTask->progress,
969 Guest::tr("Guest Additions update failed with exit code=%u (status=%u, flags=%u)"),
970 uRetExitCode, retStatus, uRetFlags);
971 }
972 }
973 else if ( SUCCEEDED(progressInstaller->COMGETTER(Canceled(&fCanceled)))
974 && fCanceled)
975 {
976 LogRel(("Guest Additions update was canceled\n"));
977 rc = GuestTask::setProgressErrorInfo(VBOX_E_IPRT_ERROR, aTask->progress,
978 Guest::tr("Guest Additions update was canceled by the guest with exit code=%u (status=%u, flags=%u)"),
979 uRetExitCode, retStatus, uRetFlags);
980 }
981 else
982 {
983 LogRel(("Guest Additions update was canceled by the user\n"));
984 }
985 }
986 else
987 rc = GuestTask::setProgressErrorInfo(rc, aTask->progress, pGuest);
988 }
989 else
990 rc = GuestTask::setProgressErrorInfo(rc, aTask->progress, pGuest);
991 }
992 }
993 }
994 catch (HRESULT aRC)
995 {
996 rc = aRC;
997 }
998
999 /* Clean up */
1000 aTask->rc = rc;
1001
1002 LogFlowFunc(("rc=%Rhrc\n", rc));
1003 LogFlowFuncLeave();
1004
1005 return VINF_SUCCESS;
1006}
1007#endif
1008
Note: See TracBrowser for help on using the repository browser.

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette