VirtualBox

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

Last change on this file since 38627 was 38627, checked in by vboxsync, 13 years ago

Main/GuestCtrl: Fixed file copy/existence return codes.

  • 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.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#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 else
468 rc = GuestTask::setProgressErrorInfo(rc, aTask->progress, pGuest);
469
470 /* Query file size to make an estimate for our progress object. */
471 if (SUCCEEDED(rc))
472 {
473 LONG64 lFileSize;
474 rc = pGuest->FileQuerySize(Bstr(aTask->strSource).raw(),
475 Bstr(aTask->strUserName).raw(), Bstr(aTask->strPassword).raw(),
476 &lFileSize);
477 if (FAILED(rc))
478 rc = GuestTask::setProgressErrorInfo(rc, aTask->progress, pGuest);
479
480 com::SafeArray<IN_BSTR> args;
481 com::SafeArray<IN_BSTR> env;
482
483 if (SUCCEEDED(rc))
484 {
485 /*
486 * Prepare tool command line.
487 */
488 char szSource[RTPATH_MAX];
489 if (RTStrPrintf(szSource, sizeof(szSource), "%s", aTask->strSource.c_str()) <= sizeof(szSource) - 1)
490 {
491 /*
492 * Normalize path slashes, based on the detected guest.
493 */
494 Utf8Str osType = mData.mOSTypeId;
495 if ( osType.contains("Microsoft", Utf8Str::CaseInsensitive)
496 || osType.contains("Windows", Utf8Str::CaseInsensitive))
497 {
498 /* We have a Windows guest. */
499 RTPathChangeToDosSlashes(szSource, true /* Force conversion. */);
500 }
501 else /* ... or something which isn't from Redmond ... */
502 {
503 RTPathChangeToUnixSlashes(szSource, true /* Force conversion. */);
504 }
505
506 args.push_back(Bstr(szSource).raw()); /* Tell our cat tool which file to output. */
507 }
508 else
509 rc = GuestTask::setProgressErrorInfo(VBOX_E_IPRT_ERROR, aTask->progress,
510 Guest::tr("Error preparing command line"));
511 }
512
513 ComPtr<IProgress> execProgress;
514 ULONG uPID;
515 if (SUCCEEDED(rc))
516 {
517 LogRel(("Copying file \"%s\" to host \"%s\" (%u bytes) ...\n",
518 aTask->strSource.c_str(), aTask->strDest.c_str(), lFileSize));
519
520 /*
521 * Okay, since we gathered all stuff we need until now to start the
522 * actual copying, start the guest part now.
523 */
524 rc = pGuest->ExecuteProcess(Bstr(VBOXSERVICE_TOOL_CAT).raw(),
525 ExecuteProcessFlag_Hidden,
526 ComSafeArrayAsInParam(args),
527 ComSafeArrayAsInParam(env),
528 Bstr(aTask->strUserName).raw(),
529 Bstr(aTask->strPassword).raw(),
530 5 * 1000 /* Wait 5s for getting the process started. */,
531 &uPID, execProgress.asOutParam());
532 if (FAILED(rc))
533 rc = GuestTask::setProgressErrorInfo(rc, aTask->progress, pGuest);
534 }
535
536 if (SUCCEEDED(rc))
537 {
538 BOOL fCompleted = FALSE;
539 BOOL fCanceled = FALSE;
540
541 RTFILE hFileDest;
542 int vrc = RTFileOpen(&hFileDest, aTask->strDest.c_str(),
543 RTFILE_O_WRITE | RTFILE_O_OPEN_CREATE | RTFILE_O_DENY_WRITE);
544 if (RT_FAILURE(vrc))
545 rc = GuestTask::setProgressErrorInfo(VBOX_E_IPRT_ERROR, aTask->progress,
546 Guest::tr("Unable to create/open destination file \"%s\", rc=%Rrc"),
547 aTask->strDest.c_str(), vrc);
548 else
549 {
550 size_t cbToRead = lFileSize;
551 size_t cbTransfered = 0;
552 SafeArray<BYTE> aOutputData(_64K);
553 while (SUCCEEDED(execProgress->COMGETTER(Completed(&fCompleted))))
554 {
555 rc = this->GetProcessOutput(uPID, ProcessOutputFlag_None,
556 10 * 1000 /* Timeout in ms */,
557 _64K, ComSafeArrayAsOutParam(aOutputData));
558 if (SUCCEEDED(rc))
559 {
560 if (!aOutputData.size())
561 {
562 /*
563 * Only bitch about an unexpected end of a file when there already
564 * was data read from that file. If this was the very first read we can
565 * be (almost) sure that this file is not meant to be read by the specified user.
566 */
567 if ( cbTransfered
568 && cbToRead)
569 {
570 rc = GuestTask::setProgressErrorInfo(VBOX_E_IPRT_ERROR, aTask->progress,
571 Guest::tr("Unexpected end of file \"%s\" (%u bytes left, %u bytes written)"),
572 aTask->strSource.c_str(), cbToRead, cbTransfered);
573 }
574 break;
575 }
576
577 vrc = RTFileWrite(hFileDest, aOutputData.raw(), aOutputData.size(), NULL /* No partial writes */);
578 if (RT_FAILURE(vrc))
579 {
580 rc = GuestTask::setProgressErrorInfo(VBOX_E_IPRT_ERROR, aTask->progress,
581 Guest::tr("Error writing to file \"%s\" (%u bytes left), rc=%Rrc"),
582 aTask->strSource.c_str(), cbToRead, vrc);
583 break;
584 }
585
586 cbToRead -= aOutputData.size();
587 cbTransfered += aOutputData.size();
588
589 aTask->progress->SetCurrentOperationProgress(cbTransfered / (lFileSize / 100.0));
590 }
591 else
592 {
593 rc = GuestTask::setProgressErrorInfo(rc, aTask->progress, pGuest);
594 break;
595 }
596 }
597
598 if (SUCCEEDED(rc))
599 aTask->progress->notifyComplete(S_OK);
600
601 RTFileClose(hFileDest);
602 }
603 }
604 }
605 }
606 catch (HRESULT aRC)
607 {
608 rc = aRC;
609 }
610
611 /* Clean up */
612 aTask->rc = rc;
613
614 LogFlowFunc(("rc=%Rhrc\n", rc));
615 LogFlowFuncLeave();
616
617 return VINF_SUCCESS;
618}
619
620HRESULT Guest::taskUpdateGuestAdditions(GuestTask *aTask)
621{
622 LogFlowFuncEnter();
623
624 AutoCaller autoCaller(this);
625 if (FAILED(autoCaller.rc())) return autoCaller.rc();
626
627 /*
628 * Do *not* take a write lock here since we don't (and won't)
629 * touch any class-specific data (of IGuest) here - only the member functions
630 * which get called here can do that.
631 */
632
633 HRESULT rc = S_OK;
634 BOOL fCompleted;
635 BOOL fCanceled;
636
637 try
638 {
639 Guest *pGuest = aTask->pGuest;
640 AssertPtr(pGuest);
641
642 aTask->progress->SetCurrentOperationProgress(10);
643
644 /*
645 * Determine guest OS type and the required installer image.
646 * At the moment only Windows guests are supported.
647 */
648 Utf8Str installerImage;
649 Bstr osTypeId;
650 if ( SUCCEEDED(pGuest->COMGETTER(OSTypeId(osTypeId.asOutParam())))
651 && !osTypeId.isEmpty())
652 {
653 Utf8Str osTypeIdUtf8(osTypeId); /* Needed for .contains(). */
654 if ( osTypeIdUtf8.contains("Microsoft", Utf8Str::CaseInsensitive)
655 || osTypeIdUtf8.contains("Windows", Utf8Str::CaseInsensitive))
656 {
657 if (osTypeIdUtf8.contains("64", Utf8Str::CaseInsensitive))
658 installerImage = "VBOXWINDOWSADDITIONS_AMD64.EXE";
659 else
660 installerImage = "VBOXWINDOWSADDITIONS_X86.EXE";
661 /* Since the installers are located in the root directory,
662 * no further path processing needs to be done (yet). */
663 }
664 else /* Everything else is not supported (yet). */
665 throw GuestTask::setProgressErrorInfo(VBOX_E_NOT_SUPPORTED, aTask->progress,
666 Guest::tr("Detected guest OS (%s) does not support automatic Guest Additions updating, please update manually"),
667 osTypeIdUtf8.c_str());
668 }
669 else
670 throw GuestTask::setProgressErrorInfo(VBOX_E_NOT_SUPPORTED, aTask->progress,
671 Guest::tr("Could not detected guest OS type/version, please update manually"));
672 Assert(!installerImage.isEmpty());
673
674 /*
675 * Try to open the .ISO file and locate the specified installer.
676 */
677 RTISOFSFILE iso;
678 int vrc = RTIsoFsOpen(&iso, aTask->strSource.c_str());
679 if (RT_FAILURE(vrc))
680 {
681 rc = GuestTask::setProgressErrorInfo(VBOX_E_FILE_ERROR, aTask->progress,
682 Guest::tr("Invalid installation medium detected: \"%s\""),
683 aTask->strSource.c_str());
684 }
685 else
686 {
687 uint32_t cbOffset;
688 size_t cbLength;
689 vrc = RTIsoFsGetFileInfo(&iso, installerImage.c_str(), &cbOffset, &cbLength);
690 if ( RT_SUCCESS(vrc)
691 && cbOffset
692 && cbLength)
693 {
694 vrc = RTFileSeek(iso.file, cbOffset, RTFILE_SEEK_BEGIN, NULL);
695 if (RT_FAILURE(vrc))
696 rc = GuestTask::setProgressErrorInfo(VBOX_E_IPRT_ERROR, aTask->progress,
697 Guest::tr("Could not seek to setup file on installation medium \"%s\" (%Rrc)"),
698 aTask->strSource.c_str(), vrc);
699 }
700 else
701 {
702 switch (vrc)
703 {
704 case VERR_FILE_NOT_FOUND:
705 rc = GuestTask::setProgressErrorInfo(VBOX_E_IPRT_ERROR, aTask->progress,
706 Guest::tr("Setup file was not found on installation medium \"%s\""),
707 aTask->strSource.c_str());
708 break;
709
710 default:
711 rc = GuestTask::setProgressErrorInfo(VBOX_E_IPRT_ERROR, aTask->progress,
712 Guest::tr("An unknown error (%Rrc) occured while retrieving information of setup file on installation medium \"%s\""),
713 vrc, aTask->strSource.c_str());
714 break;
715 }
716 }
717
718 /* Specify the ouput path on the guest side. */
719 Utf8Str strInstallerPath = "%TEMP%\\VBoxWindowsAdditions.exe";
720
721 if (RT_SUCCESS(vrc))
722 {
723 /* Okay, we're ready to start our copy routine on the guest! */
724 aTask->progress->SetCurrentOperationProgress(15);
725
726 /* Prepare command line args. */
727 com::SafeArray<IN_BSTR> args;
728 com::SafeArray<IN_BSTR> env;
729
730 args.push_back(Bstr("--output").raw()); /* We want to write a file ... */
731 args.push_back(Bstr(strInstallerPath.c_str()).raw()); /* ... with this path. */
732
733 if (SUCCEEDED(rc))
734 {
735 ComPtr<IProgress> progressCat;
736 ULONG uPID;
737
738 /*
739 * Start built-in "vbox_cat" tool (inside VBoxService) to
740 * copy over/pipe the data into a file on the guest (with
741 * system rights, no username/password specified).
742 */
743 rc = pGuest->executeProcessInternal(Bstr(VBOXSERVICE_TOOL_CAT).raw(),
744 ExecuteProcessFlag_Hidden
745 | ExecuteProcessFlag_WaitForProcessStartOnly,
746 ComSafeArrayAsInParam(args),
747 ComSafeArrayAsInParam(env),
748 Bstr("").raw() /* Username. */,
749 Bstr("").raw() /* Password */,
750 5 * 1000 /* Wait 5s for getting the process started. */,
751 &uPID, progressCat.asOutParam(), &vrc);
752 if (FAILED(rc))
753 {
754 /* Errors which return VBOX_E_NOT_SUPPORTED can be safely skipped by the caller
755 * to silently fall back to "normal" (old) .ISO mounting. */
756
757 /* Due to a very limited COM error range we use vrc for a more detailed error
758 * lookup to figure out what went wrong. */
759 switch (vrc)
760 {
761 /* Guest execution service is not (yet) ready. This basically means that either VBoxService
762 * is not running (yet) or that the Guest Additions are too old (because VBoxService does not
763 * support the guest execution feature in this version). */
764 case VERR_NOT_FOUND:
765 LogRel(("Guest Additions seem not to be installed yet\n"));
766 rc = GuestTask::setProgressErrorInfo(VBOX_E_NOT_SUPPORTED, aTask->progress,
767 Guest::tr("Guest Additions seem not to be installed or are not ready to update yet"));
768 break;
769
770 /* Getting back a VERR_INVALID_PARAMETER indicates that the installed Guest Additions are supporting the guest
771 * execution but not the built-in "vbox_cat" tool of VBoxService (< 4.0). */
772 case VERR_INVALID_PARAMETER:
773 LogRel(("Guest Additions are installed but don't supported automatic updating\n"));
774 rc = GuestTask::setProgressErrorInfo(VBOX_E_NOT_SUPPORTED, aTask->progress,
775 Guest::tr("Installed Guest Additions do not support automatic updating"));
776 break;
777
778 case VERR_TIMEOUT:
779 LogRel(("Guest was unable to start copying the Guest Additions setup within time\n"));
780 rc = GuestTask::setProgressErrorInfo(E_FAIL, aTask->progress,
781 Guest::tr("Guest was unable to start copying the Guest Additions setup within time"));
782 break;
783
784 default:
785 rc = GuestTask::setProgressErrorInfo(E_FAIL, aTask->progress,
786 Guest::tr("Error copying Guest Additions setup file to guest path \"%s\" (%Rrc)"),
787 strInstallerPath.c_str(), vrc);
788 break;
789 }
790 }
791 else
792 {
793 LogRel(("Automatic update of Guest Additions started, using \"%s\"\n", aTask->strSource.c_str()));
794 LogRel(("Copying Guest Additions installer \"%s\" to \"%s\" on guest ...\n",
795 installerImage.c_str(), strInstallerPath.c_str()));
796 aTask->progress->SetCurrentOperationProgress(20);
797
798 /* Wait for process to exit ... */
799 SafeArray<BYTE> aInputData(_64K);
800 while ( SUCCEEDED(progressCat->COMGETTER(Completed(&fCompleted)))
801 && !fCompleted)
802 {
803 size_t cbRead;
804 /* cbLength contains remaining bytes of our installer file
805 * opened above to read. */
806 size_t cbToRead = RT_MIN(cbLength, _64K);
807 if (cbToRead)
808 {
809 vrc = RTFileRead(iso.file, (uint8_t*)aInputData.raw(), cbToRead, &cbRead);
810 if ( cbRead
811 && RT_SUCCESS(vrc))
812 {
813 /* Resize buffer to reflect amount we just have read. */
814 if (cbRead > 0)
815 aInputData.resize(cbRead);
816
817 /* Did we reach the end of the content we want to transfer (last chunk)? */
818 ULONG uFlags = ProcessInputFlag_None;
819 if ( (cbRead < _64K)
820 /* Did we reach the last block which is exactly _64K? */
821 || (cbToRead - cbRead == 0)
822 /* ... or does the user want to cancel? */
823 || ( SUCCEEDED(aTask->progress->COMGETTER(Canceled(&fCanceled)))
824 && fCanceled)
825 )
826 {
827 uFlags |= ProcessInputFlag_EndOfFile;
828 }
829
830 /* Transfer the current chunk ... */
831 #ifdef DEBUG_andy
832 LogRel(("Copying Guest Additions (%u bytes left) ...\n", cbLength));
833 #endif
834 ULONG uBytesWritten;
835 rc = pGuest->SetProcessInput(uPID, uFlags,
836 10 * 1000 /* Wait 10s for getting the input data transfered. */,
837 ComSafeArrayAsInParam(aInputData), &uBytesWritten);
838 if (FAILED(rc))
839 {
840 rc = GuestTask::setProgressErrorInfo(rc, aTask->progress, pGuest);
841 break;
842 }
843
844 /* If task was canceled above also cancel the process execution. */
845 if (fCanceled)
846 progressCat->Cancel();
847
848 #ifdef DEBUG_andy
849 LogRel(("Copying Guest Additions (%u bytes written) ...\n", uBytesWritten));
850 #endif
851 Assert(cbLength >= uBytesWritten);
852 cbLength -= uBytesWritten;
853 }
854 else if (RT_FAILURE(vrc))
855 {
856 rc = GuestTask::setProgressErrorInfo(VBOX_E_IPRT_ERROR, aTask->progress,
857 Guest::tr("Error while reading setup file \"%s\" (To read: %u, Size: %u) from installation medium (%Rrc)"),
858 installerImage.c_str(), cbToRead, cbLength, vrc);
859 }
860 }
861
862 /* Internal progress canceled? */
863 if ( SUCCEEDED(progressCat->COMGETTER(Canceled(&fCanceled)))
864 && fCanceled)
865 {
866 aTask->progress->Cancel();
867 break;
868 }
869 }
870 }
871 }
872 }
873 RTIsoFsClose(&iso);
874
875 if ( SUCCEEDED(rc)
876 && ( SUCCEEDED(aTask->progress->COMGETTER(Canceled(&fCanceled)))
877 && !fCanceled
878 )
879 )
880 {
881 /*
882 * Installer was transferred successfully, so let's start it
883 * (with system rights).
884 */
885 LogRel(("Preparing to execute Guest Additions update ...\n"));
886 aTask->progress->SetCurrentOperationProgress(66);
887
888 /* Prepare command line args for installer. */
889 com::SafeArray<IN_BSTR> installerArgs;
890 com::SafeArray<IN_BSTR> installerEnv;
891
892 /** @todo Only Windows! */
893 installerArgs.push_back(Bstr(strInstallerPath).raw()); /* The actual (internal) installer image (as argv[0]). */
894 /* Note that starting at Windows Vista the lovely session 0 separation applies:
895 * This means that if we run an application with the profile/security context
896 * of VBoxService (system rights!) we're not able to show any UI. */
897 installerArgs.push_back(Bstr("/S").raw()); /* We want to install in silent mode. */
898 installerArgs.push_back(Bstr("/l").raw()); /* ... and logging enabled. */
899 /* Don't quit VBoxService during upgrade because it still is used for this
900 * piece of code we're in right now (that is, here!) ... */
901 installerArgs.push_back(Bstr("/no_vboxservice_exit").raw());
902 /* Tell the installer to report its current installation status
903 * using a running VBoxTray instance via balloon messages in the
904 * Windows taskbar. */
905 installerArgs.push_back(Bstr("/post_installstatus").raw());
906
907 /*
908 * Start the just copied over installer with system rights
909 * in silent mode on the guest. Don't use the hidden flag since there
910 * may be pop ups the user has to process.
911 */
912 ComPtr<IProgress> progressInstaller;
913 ULONG uPID;
914 rc = pGuest->executeProcessInternal(Bstr(strInstallerPath).raw(),
915 ExecuteProcessFlag_WaitForProcessStartOnly,
916 ComSafeArrayAsInParam(installerArgs),
917 ComSafeArrayAsInParam(installerEnv),
918 Bstr("").raw() /* Username */,
919 Bstr("").raw() /* Password */,
920 10 * 1000 /* Wait 10s for getting the process started */,
921 &uPID, progressInstaller.asOutParam(), &vrc);
922 if (SUCCEEDED(rc))
923 {
924 LogRel(("Guest Additions update is running ...\n"));
925
926 /* If the caller does not want to wait for out guest update process to end,
927 * complete the progress object now so that the caller can do other work. */
928 if (aTask->uFlags & AdditionsUpdateFlag_WaitForUpdateStartOnly)
929 aTask->progress->notifyComplete(S_OK);
930 else
931 aTask->progress->SetCurrentOperationProgress(70);
932
933 /* Wait until the Guest Additions installer finishes ... */
934 while ( SUCCEEDED(progressInstaller->COMGETTER(Completed(&fCompleted)))
935 && !fCompleted)
936 {
937 if ( SUCCEEDED(aTask->progress->COMGETTER(Canceled(&fCanceled)))
938 && fCanceled)
939 {
940 progressInstaller->Cancel();
941 break;
942 }
943 /* Progress canceled by Main API? */
944 if ( SUCCEEDED(progressInstaller->COMGETTER(Canceled(&fCanceled)))
945 && fCanceled)
946 {
947 break;
948 }
949 RTThreadSleep(100);
950 }
951
952 ExecuteProcessStatus_T retStatus;
953 ULONG uRetExitCode, uRetFlags;
954 rc = pGuest->GetProcessStatus(uPID, &uRetExitCode, &uRetFlags, &retStatus);
955 if (SUCCEEDED(rc))
956 {
957 if (fCompleted)
958 {
959 if (uRetExitCode == 0)
960 {
961 LogRel(("Guest Additions update successful!\n"));
962 if ( SUCCEEDED(aTask->progress->COMGETTER(Completed(&fCompleted)))
963 && !fCompleted)
964 aTask->progress->notifyComplete(S_OK);
965 }
966 else
967 {
968 LogRel(("Guest Additions update failed (Exit code=%u, Status=%u, Flags=%u)\n",
969 uRetExitCode, retStatus, uRetFlags));
970 rc = GuestTask::setProgressErrorInfo(VBOX_E_IPRT_ERROR, aTask->progress,
971 Guest::tr("Guest Additions update failed with exit code=%u (status=%u, flags=%u)"),
972 uRetExitCode, retStatus, uRetFlags);
973 }
974 }
975 else if ( SUCCEEDED(progressInstaller->COMGETTER(Canceled(&fCanceled)))
976 && fCanceled)
977 {
978 LogRel(("Guest Additions update was canceled\n"));
979 rc = GuestTask::setProgressErrorInfo(VBOX_E_IPRT_ERROR, aTask->progress,
980 Guest::tr("Guest Additions update was canceled by the guest with exit code=%u (status=%u, flags=%u)"),
981 uRetExitCode, retStatus, uRetFlags);
982 }
983 else
984 {
985 LogRel(("Guest Additions update was canceled by the user\n"));
986 }
987 }
988 else
989 rc = GuestTask::setProgressErrorInfo(rc, aTask->progress, pGuest);
990 }
991 else
992 rc = GuestTask::setProgressErrorInfo(rc, aTask->progress, pGuest);
993 }
994 }
995 }
996 catch (HRESULT aRC)
997 {
998 rc = aRC;
999 }
1000
1001 /* Clean up */
1002 aTask->rc = rc;
1003
1004 LogFlowFunc(("rc=%Rhrc\n", rc));
1005 LogFlowFuncLeave();
1006
1007 return VINF_SUCCESS;
1008}
1009#endif
1010
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