VirtualBox

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

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

GuestCtrl: Request (IPC) changes, bugfixes, fixed handle leaks.

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