VirtualBox

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

Last change on this file since 71256 was 71256, checked in by vboxsync, 7 years ago

Guest Control: Implemented copying directories from guest to host via Main (no support for filters yet).

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 85.4 KB
Line 
1/* $Id: GuestSessionImplTasks.cpp 71256 2018-03-07 13:11:42Z vboxsync $ */
2/** @file
3 * VirtualBox Main - Guest session tasks.
4 */
5
6/*
7 * Copyright (C) 2012-2018 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/*********************************************************************************************************************************
20* Header Files *
21*********************************************************************************************************************************/
22#define LOG_GROUP LOG_GROUP_MAIN_GUESTSESSION
23#include "LoggingNew.h"
24
25#include "GuestImpl.h"
26#ifndef VBOX_WITH_GUEST_CONTROL
27# error "VBOX_WITH_GUEST_CONTROL must defined in this file"
28#endif
29#include "GuestSessionImpl.h"
30#include "GuestCtrlImplPrivate.h"
31
32#include "Global.h"
33#include "AutoCaller.h"
34#include "ConsoleImpl.h"
35#include "ProgressImpl.h"
36
37#include <memory> /* For auto_ptr. */
38
39#include <iprt/env.h>
40#include <iprt/file.h> /* For CopyTo/From. */
41#include <iprt/dir.h>
42#include <iprt/path.h>
43
44
45/*********************************************************************************************************************************
46* Defines *
47*********************************************************************************************************************************/
48
49/**
50 * Update file flags.
51 */
52#define UPDATEFILE_FLAG_NONE 0
53/** Copy over the file from host to the
54 * guest. */
55#define UPDATEFILE_FLAG_COPY_FROM_ISO RT_BIT(0)
56/** Execute file on the guest after it has
57 * been successfully transfered. */
58#define UPDATEFILE_FLAG_EXECUTE RT_BIT(7)
59/** File is optional, does not have to be
60 * existent on the .ISO. */
61#define UPDATEFILE_FLAG_OPTIONAL RT_BIT(8)
62
63
64// session task classes
65/////////////////////////////////////////////////////////////////////////////
66
67GuestSessionTask::GuestSessionTask(GuestSession *pSession)
68 : ThreadTask("GenericGuestSessionTask")
69{
70 mSession = pSession;
71}
72
73GuestSessionTask::~GuestSessionTask(void)
74{
75}
76
77HRESULT GuestSessionTask::createAndSetProgressObject()
78{
79 LogFlowThisFunc(("Task Description = %s, pTask=%p\n", mDesc.c_str(), this));
80
81 ComObjPtr<Progress> pProgress;
82 HRESULT hr = S_OK;
83 /* Create the progress object. */
84 hr = pProgress.createObject();
85 if (FAILED(hr))
86 return VERR_COM_UNEXPECTED;
87
88 hr = pProgress->init(static_cast<IGuestSession*>(mSession),
89 Bstr(mDesc).raw(),
90 TRUE /* aCancelable */);
91 if (FAILED(hr))
92 return VERR_COM_UNEXPECTED;
93
94 mProgress = pProgress;
95
96 LogFlowFuncLeave();
97
98 return hr;
99}
100
101int GuestSessionTask::RunAsync(const Utf8Str &strDesc, ComObjPtr<Progress> &pProgress)
102{
103 LogFlowThisFunc(("strDesc=%s\n", strDesc.c_str()));
104
105 mDesc = strDesc;
106 mProgress = pProgress;
107 HRESULT hrc = createThreadWithType(RTTHREADTYPE_MAIN_HEAVY_WORKER);
108
109 LogFlowThisFunc(("Returning hrc=%Rhrc\n", hrc));
110 return Global::vboxStatusCodeToCOM(hrc);
111}
112
113
114int GuestSessionTask::getGuestProperty(const ComObjPtr<Guest> &pGuest,
115 const Utf8Str &strPath, Utf8Str &strValue)
116{
117 ComObjPtr<Console> pConsole = pGuest->i_getConsole();
118 const ComPtr<IMachine> pMachine = pConsole->i_machine();
119
120 Assert(!pMachine.isNull());
121 Bstr strTemp, strFlags;
122 LONG64 i64Timestamp;
123 HRESULT hr = pMachine->GetGuestProperty(Bstr(strPath).raw(),
124 strTemp.asOutParam(),
125 &i64Timestamp, strFlags.asOutParam());
126 if (SUCCEEDED(hr))
127 {
128 strValue = strTemp;
129 return VINF_SUCCESS;
130 }
131 return VERR_NOT_FOUND;
132}
133
134int GuestSessionTask::setProgress(ULONG uPercent)
135{
136 if (mProgress.isNull()) /* Progress is optional. */
137 return VINF_SUCCESS;
138
139 BOOL fCanceled;
140 if ( SUCCEEDED(mProgress->COMGETTER(Canceled(&fCanceled)))
141 && fCanceled)
142 return VERR_CANCELLED;
143 BOOL fCompleted;
144 if ( SUCCEEDED(mProgress->COMGETTER(Completed(&fCompleted)))
145 && fCompleted)
146 {
147 AssertMsgFailed(("Setting value of an already completed progress\n"));
148 return VINF_SUCCESS;
149 }
150 HRESULT hr = mProgress->SetCurrentOperationProgress(uPercent);
151 if (FAILED(hr))
152 return VERR_COM_UNEXPECTED;
153
154 return VINF_SUCCESS;
155}
156
157int GuestSessionTask::setProgressSuccess(void)
158{
159 if (mProgress.isNull()) /* Progress is optional. */
160 return VINF_SUCCESS;
161
162 BOOL fCanceled;
163 BOOL fCompleted;
164 if ( SUCCEEDED(mProgress->COMGETTER(Canceled(&fCanceled)))
165 && !fCanceled
166 && SUCCEEDED(mProgress->COMGETTER(Completed(&fCompleted)))
167 && !fCompleted)
168 {
169 HRESULT hr = mProgress->i_notifyComplete(S_OK);
170 if (FAILED(hr))
171 return VERR_COM_UNEXPECTED; /** @todo Find a better rc. */
172 }
173
174 return VINF_SUCCESS;
175}
176
177HRESULT GuestSessionTask::setProgressErrorMsg(HRESULT hr, const Utf8Str &strMsg)
178{
179 LogFlowFunc(("hr=%Rhrc, strMsg=%s\n",
180 hr, strMsg.c_str()));
181
182 if (mProgress.isNull()) /* Progress is optional. */
183 return hr; /* Return original rc. */
184
185 BOOL fCanceled;
186 BOOL fCompleted;
187 if ( SUCCEEDED(mProgress->COMGETTER(Canceled(&fCanceled)))
188 && !fCanceled
189 && SUCCEEDED(mProgress->COMGETTER(Completed(&fCompleted)))
190 && !fCompleted)
191 {
192 HRESULT hr2 = mProgress->i_notifyComplete(hr,
193 COM_IIDOF(IGuestSession),
194 GuestSession::getStaticComponentName(),
195 strMsg.c_str());
196 if (FAILED(hr2))
197 return hr2;
198 }
199 return hr; /* Return original rc. */
200}
201
202/**
203 * Creates a directory on the guest.
204 *
205 * @return VBox status code. VWRN_ALREADY_EXISTS if directory on the guest already exists.
206 * @param strPath Absolute path to directory on the guest (guest style path) to create.
207 * @param enmDirecotryCreateFlags Directory creation flags.
208 * @param uMode Directory mode to use for creation.
209 * @param fFollowSymlinks Whether to follow symlinks on the guest or not.
210 */
211int GuestSessionTask::directoryCreate(const com::Utf8Str &strPath,
212 DirectoryCreateFlag_T enmDirecotryCreateFlags, uint32_t uMode, bool fFollowSymlinks)
213{
214 LogFlowFunc(("strPath=%s, fFlags=0x%x, uMode=%RU32, fFollowSymlinks=%RTbool\n",
215 strPath.c_str(), enmDirecotryCreateFlags, uMode, fFollowSymlinks));
216
217 GuestFsObjData objData; int guestRc;
218
219 int rc = mSession->i_directoryQueryInfoInternal(strPath, fFollowSymlinks, objData, &guestRc);
220 if (RT_SUCCESS(rc))
221 {
222 return VWRN_ALREADY_EXISTS;
223 }
224 else
225 {
226 switch (rc)
227 {
228 case VERR_GSTCTL_GUEST_ERROR:
229 {
230 switch (guestRc)
231 {
232 case VERR_FILE_NOT_FOUND:
233 case VERR_PATH_NOT_FOUND:
234 rc = mSession->i_directoryCreateInternal(strPath.c_str(), uMode, enmDirecotryCreateFlags, &guestRc);
235 break;
236 default:
237 break;
238 }
239 break;
240 }
241
242 default:
243 break;
244 }
245 }
246
247 if (RT_FAILURE(rc))
248 {
249 if (rc == VERR_GSTCTL_GUEST_ERROR)
250 {
251 setProgressErrorMsg(VBOX_E_IPRT_ERROR, GuestProcess::i_guestErrorToString(guestRc));
252 }
253 else
254 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
255 Utf8StrFmt(GuestSession::tr("Error creating directory on the guest: %Rrc"), strPath.c_str(), rc));
256 }
257
258 LogFlowFuncLeaveRC(rc);
259 return rc;
260}
261
262/**
263 * Copies a file from the guest to the host, extended version.
264 *
265 * @return VBox status code.
266 * @param strSource Full path of source file on the guest to copy.
267 * @param strDest Full destination path and file name (host style) to copy file to.
268 * @param enmFileCopyFlags File copy flags. Currently not used.
269 * @param pFile Destination file handle to use for accessing the host file.
270 * The caller is responsible of opening / closing the file accordingly.
271 * @param cbOffset Offset (in bytes) where to start copying the source file.
272 * Currently unused, must be 0.
273 * @param cbSize Size (in bytes) to copy from the source file.
274 * Currently unused, must be 0.
275 */
276int GuestSessionTask::fileCopyFromEx(const Utf8Str &strSource, const Utf8Str &strDest, FileCopyFlag_T enmFileCopyFlags,
277 PRTFILE pFile, uint64_t cbOffset, uint64_t cbSize)
278{
279 RT_NOREF(enmFileCopyFlags, cbOffset, cbSize);
280
281 AssertReturn(cbOffset == 0, VERR_NOT_IMPLEMENTED);
282 AssertReturn(cbSize == 0, VERR_NOT_IMPLEMENTED);
283
284 RTMSINTERVAL msTimeout = 30 * 1000; /** @todo 30s timeout for all actions. Make this configurable? */
285
286 /*
287 * Note: There will be races between querying file size + reading the guest file's
288 * content because we currently *do not* lock down the guest file when doing the
289 * actual operations.
290 ** @todo Use the IGuestFile API for locking down the file on the guest!
291 */
292 GuestFsObjData objData;
293 int rcGuest = VERR_IPE_UNINITIALIZED_STATUS;
294 int rc = mSession->i_fileQueryInfoInternal(strSource, false /*fFollowSymlinks*/, objData, &rcGuest);
295 if (RT_FAILURE(rc))
296 {
297 switch (rc)
298 {
299 case VERR_GSTCTL_GUEST_ERROR:
300 setProgressErrorMsg(VBOX_E_IPRT_ERROR, GuestProcess::i_guestErrorToString(rcGuest));
301 break;
302
303 default:
304 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
305 Utf8StrFmt(GuestSession::tr("Querying guest file information for \"%s\" failed: %Rrc"),
306 strSource.c_str(), rc));
307 break;
308 }
309 }
310 else if (objData.mType != FsObjType_File) /* Only single files are supported at the moment. */
311 {
312 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
313 Utf8StrFmt(GuestSession::tr("Object \"%s\" on the guest is not a file"), strSource.c_str()));
314 rc = VERR_NOT_A_FILE;
315 }
316
317 if (RT_FAILURE(rc))
318 return rc;
319
320 GuestProcessStartupInfo procInfo;
321 procInfo.mName = Utf8StrFmt(GuestSession::tr("Copying file \"%s\" from guest to the host to \"%s\" (%RI64 bytes)"),
322 strSource.c_str(), strDest.c_str(), objData.mObjectSize);
323 procInfo.mExecutable = Utf8Str(VBOXSERVICE_TOOL_CAT);
324 procInfo.mFlags = ProcessCreateFlag_Hidden | ProcessCreateFlag_WaitForStdOut;
325
326 /* Set arguments.*/
327 procInfo.mArguments.push_back(procInfo.mExecutable); /* Set argv0. */
328 procInfo.mArguments.push_back(strSource); /* Which file to output? */
329
330 /* Startup process. */
331 ComObjPtr<GuestProcess> pProcess;
332 rc = mSession->i_processCreateExInternal(procInfo, pProcess);
333 if (RT_SUCCESS(rc))
334 rc = pProcess->i_startProcess(msTimeout, &rcGuest);
335
336 if (RT_FAILURE(rc))
337 {
338 switch (rc)
339 {
340 case VERR_GSTCTL_GUEST_ERROR:
341 setProgressErrorMsg(VBOX_E_IPRT_ERROR, GuestProcess::i_guestErrorToString(rcGuest));
342 break;
343
344 default:
345 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
346 Utf8StrFmt(GuestSession::tr(
347 "Error while creating guest process for copying file \"%s\" from guest to host: %Rrc"),
348 strSource.c_str(), rc));
349 break;
350 }
351
352 return rc;
353 }
354
355 ProcessWaitResult_T waitRes;
356 BYTE byBuf[_64K];
357
358 BOOL fCanceled = FALSE;
359 uint64_t cbWrittenTotal = 0;
360 uint64_t cbToRead = objData.mObjectSize;
361
362 for (;;)
363 {
364 rc = pProcess->i_waitFor(ProcessWaitForFlag_StdOut, msTimeout, waitRes, &rcGuest);
365 if (RT_FAILURE(rc))
366 {
367 switch (rc)
368 {
369 case VERR_GSTCTL_GUEST_ERROR:
370 setProgressErrorMsg(VBOX_E_IPRT_ERROR, GuestProcess::i_guestErrorToString(rcGuest));
371 break;
372
373 default:
374 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
375 Utf8StrFmt(GuestSession::tr("Error while creating guest process for copying file \"%s\" from guest to host: %Rrc"),
376 strSource.c_str(), rc));
377 break;
378 }
379
380 break;
381 }
382
383 if ( waitRes == ProcessWaitResult_StdOut
384 || waitRes == ProcessWaitResult_WaitFlagNotSupported)
385 {
386 /* If the guest does not support waiting for stdin, we now yield in
387 * order to reduce the CPU load due to busy waiting. */
388 if (waitRes == ProcessWaitResult_WaitFlagNotSupported)
389 RTThreadYield(); /* Optional, don't check rc. */
390
391 uint32_t cbRead = 0; /* readData can return with VWRN_GSTCTL_OBJECTSTATE_CHANGED. */
392 rc = pProcess->i_readData(OUTPUT_HANDLE_ID_STDOUT, sizeof(byBuf),
393 msTimeout, byBuf, sizeof(byBuf),
394 &cbRead, &rcGuest);
395 if (RT_FAILURE(rc))
396 {
397 switch (rc)
398 {
399 case VERR_GSTCTL_GUEST_ERROR:
400 setProgressErrorMsg(VBOX_E_IPRT_ERROR, GuestProcess::i_guestErrorToString(rcGuest));
401 break;
402
403 default:
404 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
405 Utf8StrFmt(GuestSession::tr("Reading from guest file \"%s\" (offset %RU64) failed: %Rrc"),
406 strSource.c_str(), cbWrittenTotal, rc));
407 break;
408 }
409
410 break;
411 }
412
413 if (cbRead)
414 {
415 rc = RTFileWrite(*pFile, byBuf, cbRead, NULL /* No partial writes */);
416 if (RT_FAILURE(rc))
417 {
418 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
419 Utf8StrFmt(GuestSession::tr("Writing to host file \"%s\" (%RU64 bytes left) failed: %Rrc"),
420 strDest.c_str(), cbToRead, rc));
421 break;
422 }
423
424 /* Only subtract bytes reported written by the guest. */
425 Assert(cbToRead >= cbRead);
426 cbToRead -= cbRead;
427
428 /* Update total bytes written to the guest. */
429 cbWrittenTotal += cbRead;
430 Assert(cbWrittenTotal <= (uint64_t)objData.mObjectSize);
431
432 /* Did the user cancel the operation above? */
433 if ( SUCCEEDED(mProgress->COMGETTER(Canceled(&fCanceled)))
434 && fCanceled)
435 break;
436
437 rc = setProgress((ULONG)(cbWrittenTotal / ((uint64_t)objData.mObjectSize / 100.0)));
438 if (RT_FAILURE(rc))
439 break;
440 }
441 }
442 else
443 break;
444
445 } /* for */
446
447 LogFlowThisFunc(("rc=%Rrc, rcGuest=%Rrc, waitRes=%ld, cbWrittenTotal=%RU64, cbSize=%RI64, cbToRead=%RU64\n",
448 rc, rcGuest, waitRes, cbWrittenTotal, objData.mObjectSize, cbToRead));
449
450 /*
451 * Wait on termination of guest process until it completed all operations.
452 */
453 if ( !fCanceled
454 || RT_SUCCESS(rc))
455 {
456 rc = pProcess->i_waitFor(ProcessWaitForFlag_Terminate, msTimeout, waitRes, &rcGuest);
457 if ( RT_FAILURE(rc)
458 || waitRes != ProcessWaitResult_Terminate)
459 {
460 if (RT_FAILURE(rc))
461 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
462 Utf8StrFmt(
463 GuestSession::tr("Waiting on termination for copying file \"%s\" from guest failed: %Rrc"),
464 strSource.c_str(), rc));
465 else
466 {
467 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
468 Utf8StrFmt(GuestSession::tr(
469 "Waiting on termination for copying file \"%s\" from guest failed with wait result %ld"),
470 strSource.c_str(), waitRes));
471 rc = VERR_GENERAL_FAILURE; /* Fudge. */
472 }
473 }
474 }
475
476 if (RT_FAILURE(rc))
477 return rc;
478
479 /** @todo this code sequence is duplicated in CopyTo */
480 ProcessStatus_T procStatus = ProcessStatus_TerminatedAbnormally;
481 HRESULT hrc = pProcess->COMGETTER(Status(&procStatus));
482 if (!SUCCEEDED(hrc))
483 procStatus = ProcessStatus_TerminatedAbnormally;
484
485 LONG exitCode = 42424242;
486 hrc = pProcess->COMGETTER(ExitCode(&exitCode));
487 if (!SUCCEEDED(hrc))
488 exitCode = 42424242;
489
490 if ( procStatus != ProcessStatus_TerminatedNormally
491 || exitCode != 0)
492 {
493 LogFlowThisFunc(("procStatus=%d, exitCode=%d\n", procStatus, exitCode));
494 if (procStatus == ProcessStatus_TerminatedNormally)
495 rc = GuestProcessTool::i_exitCodeToRc(procInfo, exitCode);
496 else
497 rc = VERR_GENERAL_FAILURE;
498 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
499 Utf8StrFmt(GuestSession::tr("Copying file \"%s\" to host failed: %Rrc"),
500 strSource.c_str(), rc));
501 }
502 /*
503 * Even if we succeeded until here make sure to check whether we really transfered
504 * everything.
505 */
506 else if ( objData.mObjectSize > 0
507 && cbWrittenTotal == 0)
508 {
509 /* If nothing was transfered but the file size was > 0 then "vbox_cat" wasn't able to write
510 * to the destination -> access denied. */
511 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
512 Utf8StrFmt(GuestSession::tr("Writing guest file \"%s\" to host to \"%s\" failed: Access denied"),
513 strSource.c_str(), strDest.c_str()));
514 rc = VERR_ACCESS_DENIED;
515 }
516 else if (cbWrittenTotal < (uint64_t)objData.mObjectSize)
517 {
518 /* If we did not copy all let the user know. */
519 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
520 Utf8StrFmt(GuestSession::tr("Copying guest file \"%s\" to host to \"%s\" failed (%RU64/%RI64 bytes transfered)"),
521 strSource.c_str(), strDest.c_str(), cbWrittenTotal, objData.mObjectSize));
522 rc = VERR_INTERRUPTED;
523 }
524
525 return rc;
526}
527
528/**
529 * Copies a file from the guest to the host.
530 *
531 * @return VBox status code.
532 * @param strSource Full path of source file on the guest to copy.
533 * @param strDest Full destination path and file name (host style) to copy file to.
534 * @param enmFileCopyFlags File copy flags.
535 */
536int GuestSessionTask::fileCopyFrom(const Utf8Str &strSource, const Utf8Str &strDest, FileCopyFlag_T enmFileCopyFlags)
537{
538 RTFILE hFile;
539 int rc = RTFileOpen(&hFile, strDest.c_str(),
540 RTFILE_O_WRITE | RTFILE_O_OPEN_CREATE | RTFILE_O_DENY_WRITE); /** @todo Use the correct open modes! */
541 if (RT_FAILURE(rc))
542 {
543 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
544 Utf8StrFmt(GuestSession::tr("Opening/creating destination file on host \"%s\" failed: %Rrc"),
545 strDest.c_str(), rc));
546 return rc;
547 }
548
549 rc = fileCopyFromEx(strSource, strDest, enmFileCopyFlags, &hFile, 0 /* Offset, unused */, 0 /* Size, unused */);
550
551 int rc2 = RTFileClose(hFile);
552 AssertRC(rc2);
553
554 return rc;
555}
556
557/**
558 * Copies a file from the host to the guest, extended version.
559 *
560 * @return VBox status code.
561 * @param strSource Full path of source file on the host to copy.
562 * @param strDest Full destination path and file name (guest style) to copy file to.
563 * @param enmFileCopyFlags File copy flags.
564 * @param pFile Source file handle to use for accessing the host file.
565 * The caller is responsible of opening / closing the file accordingly.
566 * @param cbOffset Offset (in bytes) where to start copying the source file.
567 * @param cbSize Size (in bytes) to copy from the source file.
568 */
569int GuestSessionTask::fileCopyToEx(const Utf8Str &strSource, const Utf8Str &strDest, FileCopyFlag_T enmFileCopyFlags,
570 PRTFILE pFile, uint64_t cbOffset, uint64_t cbSize)
571{
572 /** @todo Implement sparse file support? */
573
574 if ( enmFileCopyFlags & FileCopyFlag_NoReplace
575 || enmFileCopyFlags & FileCopyFlag_FollowLinks
576 || enmFileCopyFlags & FileCopyFlag_Update)
577 {
578 return VERR_NOT_IMPLEMENTED;
579 }
580
581 RTMSINTERVAL msTimeout = 30 * 1000; /** @todo 30s timeout for all actions. Make this configurable? */
582
583 /*
584 * Start the actual copying process by cat'ing the source file to the
585 * destination file on the guest.
586 */
587 GuestProcessStartupInfo procInfo;
588 procInfo.mExecutable = Utf8Str(VBOXSERVICE_TOOL_CAT);
589 procInfo.mFlags = ProcessCreateFlag_Hidden;
590
591 /* Set arguments.*/
592 procInfo.mArguments.push_back(procInfo.mExecutable); /* Set argv0. */
593 procInfo.mArguments.push_back(Utf8StrFmt("--output=%s", strDest.c_str()));
594
595 /* Startup process. */
596 ComObjPtr<GuestProcess> pProcess;
597 int rc = mSession->i_processCreateExInternal(procInfo, pProcess);
598
599 int rcGuest = VERR_IPE_UNINITIALIZED_STATUS;
600 if (RT_SUCCESS(rc))
601 {
602 Assert(!pProcess.isNull());
603 rc = pProcess->i_startProcess(msTimeout, &rcGuest);
604 }
605 if (RT_FAILURE(rc))
606 {
607 switch (rc)
608 {
609 case VERR_GSTCTL_GUEST_ERROR:
610 setProgressErrorMsg(VBOX_E_IPRT_ERROR, GuestProcess::i_guestErrorToString(rcGuest));
611 break;
612
613 default:
614 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
615 Utf8StrFmt(GuestSession::tr("Error while creating guest process for copying file \"%s\" from guest to host: %Rrc"),
616 strSource.c_str(), rc));
617 break;
618 }
619 return rc;
620 }
621
622 ProcessWaitResult_T waitRes;
623 BYTE byBuf[_64K];
624
625 BOOL fCanceled = FALSE;
626 uint64_t cbWrittenTotal = 0;
627 uint64_t cbToRead = cbSize;
628
629 for (;;)
630 {
631 rc = pProcess->i_waitFor(ProcessWaitForFlag_StdIn, msTimeout, waitRes, &rcGuest);
632 if ( RT_FAILURE(rc)
633 || ( waitRes != ProcessWaitResult_StdIn
634 && waitRes != ProcessWaitResult_WaitFlagNotSupported))
635 {
636 break;
637 }
638
639 /* If the guest does not support waiting for stdin, we now yield in
640 * order to reduce the CPU load due to busy waiting. */
641 if (waitRes == ProcessWaitResult_WaitFlagNotSupported)
642 RTThreadYield(); /* Optional, don't check rc. */
643
644 size_t cbRead = 0;
645 if (cbSize) /* If we have nothing to write, take a shortcut. */
646 {
647 /** @todo Not very efficient, but works for now. */
648 rc = RTFileSeek(*pFile, cbOffset + cbWrittenTotal,
649 RTFILE_SEEK_BEGIN, NULL /* poffActual */);
650 if (RT_SUCCESS(rc))
651 {
652 rc = RTFileRead(*pFile, (uint8_t*)byBuf,
653 RT_MIN((size_t)cbToRead, sizeof(byBuf)), &cbRead);
654 /*
655 * Some other error occured? There might be a chance that RTFileRead
656 * could not resolve/map the native error code to an IPRT code, so just
657 * print a generic error.
658 */
659 if (RT_FAILURE(rc))
660 {
661 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
662 Utf8StrFmt(GuestSession::tr("Could not read from host file \"%s\" (%Rrc)"),
663 strSource.c_str(), rc));
664 break;
665 }
666 }
667 else
668 {
669 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
670 Utf8StrFmt(GuestSession::tr("Seeking host file \"%s\" to offset %RU64 failed: %Rrc"),
671 strSource.c_str(), cbWrittenTotal, rc));
672 break;
673 }
674 }
675
676 uint32_t fFlags = ProcessInputFlag_None;
677
678 /* Did we reach the end of the content we want to transfer (last chunk)? */
679 if ( (cbRead < sizeof(byBuf))
680 /* Did we reach the last block which is exactly _64K? */
681 || (cbToRead - cbRead == 0)
682 /* ... or does the user want to cancel? */
683 || ( !mProgress.isNull()
684 && SUCCEEDED(mProgress->COMGETTER(Canceled(&fCanceled)))
685 && fCanceled)
686 )
687 {
688 LogFlowThisFunc(("Writing last chunk cbRead=%RU64\n", cbRead));
689 fFlags |= ProcessInputFlag_EndOfFile;
690 }
691
692 uint32_t cbWritten;
693 Assert(sizeof(byBuf) >= cbRead);
694 rc = pProcess->i_writeData(0 /* StdIn */, fFlags, byBuf, cbRead, msTimeout, &cbWritten, &rcGuest);
695 if (RT_FAILURE(rc))
696 {
697 switch (rc)
698 {
699 case VERR_GSTCTL_GUEST_ERROR:
700 setProgressErrorMsg(VBOX_E_IPRT_ERROR, GuestProcess::i_guestErrorToString(rcGuest));
701 break;
702
703 default:
704 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
705 Utf8StrFmt(GuestSession::tr("Writing to guest file \"%s\" (offset %RU64) failed: %Rrc"),
706 strDest.c_str(), cbWrittenTotal, rc));
707 break;
708 }
709
710 break;
711 }
712
713 /* Only subtract bytes reported written by the guest. */
714 Assert(cbToRead >= cbWritten);
715 cbToRead -= cbWritten;
716
717 /* Update total bytes written to the guest. */
718 cbWrittenTotal += cbWritten;
719 Assert(cbWrittenTotal <= cbSize);
720
721 LogFlowThisFunc(("rc=%Rrc, cbWritten=%RU32, cbToRead=%RU64, cbWrittenTotal=%RU64, cbFileSize=%RU64\n",
722 rc, cbWritten, cbToRead, cbWrittenTotal, cbSize));
723
724 /* Did the user cancel the operation above? */
725 if (fCanceled)
726 break;
727
728 /* Update the progress.
729 * Watch out for division by zero. */
730 cbSize > 0
731 ? rc = setProgress((ULONG)(cbWrittenTotal * 100 / cbSize))
732 : rc = setProgress(100);
733 if (RT_FAILURE(rc))
734 break;
735
736 /* End of file reached? */
737 if (!cbToRead)
738 break;
739 } /* for */
740
741 LogFlowThisFunc(("Copy loop ended with rc=%Rrc, cbToRead=%RU64, cbWrittenTotal=%RU64, cbFileSize=%RU64\n",
742 rc, cbToRead, cbWrittenTotal, cbSize));
743
744 /*
745 * Wait on termination of guest process until it completed all operations.
746 */
747 if ( !fCanceled
748 || RT_SUCCESS(rc))
749 {
750 rc = pProcess->i_waitFor(ProcessWaitForFlag_Terminate, msTimeout, waitRes, &rcGuest);
751 if ( RT_FAILURE(rc)
752 || waitRes != ProcessWaitResult_Terminate)
753 {
754 if (RT_FAILURE(rc))
755 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
756 Utf8StrFmt(
757 GuestSession::tr("Waiting on termination for copying file \"%s\" to guest failed: %Rrc"),
758 strSource.c_str(), rc));
759 else
760 {
761 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
762 Utf8StrFmt(GuestSession::tr(
763 "Waiting on termination for copying file \"%s\" to guest failed with wait result %ld"),
764 strSource.c_str(), waitRes));
765 rc = VERR_GENERAL_FAILURE; /* Fudge. */
766 }
767 }
768 }
769
770 if (RT_SUCCESS(rc))
771 {
772 /*
773 * Newer VBoxService toolbox versions report what went wrong via exit code.
774 * So handle this first.
775 */
776 /** @todo This code sequence is duplicated in CopyFrom... */
777 ProcessStatus_T procStatus = ProcessStatus_TerminatedAbnormally;
778 HRESULT hrc = pProcess->COMGETTER(Status(&procStatus));
779 if (!SUCCEEDED(hrc))
780 procStatus = ProcessStatus_TerminatedAbnormally;
781
782 LONG exitCode = 42424242;
783 hrc = pProcess->COMGETTER(ExitCode(&exitCode));
784 if (!SUCCEEDED(hrc))
785 exitCode = 42424242;
786
787 if ( procStatus != ProcessStatus_TerminatedNormally
788 || exitCode != 0)
789 {
790 LogFlowThisFunc(("procStatus=%d, exitCode=%d\n", procStatus, exitCode));
791 if (procStatus == ProcessStatus_TerminatedNormally)
792 rc = GuestProcessTool::i_exitCodeToRc(procInfo, exitCode);
793 else
794 rc = VERR_GENERAL_FAILURE;
795 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
796 Utf8StrFmt(GuestSession::tr("Copying file \"%s\" to guest failed: %Rrc"),
797 strSource.c_str(), rc));
798 }
799 /*
800 * Even if we succeeded until here make sure to check whether we really transfered
801 * everything.
802 */
803 else if ( cbSize > 0
804 && cbWrittenTotal == 0)
805 {
806 /* If nothing was transfered but the file size was > 0 then "vbox_cat" wasn't able to write
807 * to the destination -> access denied. */
808 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
809 Utf8StrFmt(GuestSession::tr("Access denied when copying file \"%s\" to guest \"%s\""),
810 strSource.c_str(), strDest.c_str()));
811 rc = VERR_ACCESS_DENIED;
812 }
813 else if (cbWrittenTotal < cbSize)
814 {
815 /* If we did not copy all let the user know. */
816 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
817 Utf8StrFmt(GuestSession::tr("Copying file \"%s\" to guest failed (%RU64/%RU64 bytes transfered)"),
818 strSource.c_str(), cbWrittenTotal, cbSize));
819 rc = VERR_INTERRUPTED;
820 }
821 }
822
823 return rc;
824}
825
826/**
827 * Copies a file from the host to the guest.
828 *
829 * @return VBox status code.
830 * @param strSource Full path of source file on the host to copy.
831 * @param strDest Full destination path and file name (guest style) to copy file to.
832 * @param enmFileCopyFlags File copy flags.
833 */
834int GuestSessionTask::fileCopyTo(const Utf8Str &strSource, const Utf8Str &strDest, FileCopyFlag_T enmFileCopyFlags)
835{
836 int rc;
837
838 /* Does our source file exist? */
839 if (!RTFileExists(strSource.c_str()))
840 {
841 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
842 Utf8StrFmt(GuestSession::tr("Host file \"%s\" does not exist or is not a file"),
843 strSource.c_str()));
844 rc = VERR_FILE_NOT_FOUND;
845 }
846 else
847 {
848 RTFILE hFile;
849 rc = RTFileOpen(&hFile, strSource.c_str(),
850 RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_WRITE);
851 if (RT_FAILURE(rc))
852 {
853 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
854 Utf8StrFmt(GuestSession::tr("Could not open host file \"%s\" for reading: %Rrc"),
855 strSource.c_str(), rc));
856 }
857 else
858 {
859 uint64_t cbSize;
860 rc = RTFileGetSize(hFile, &cbSize);
861 if (RT_FAILURE(rc))
862 {
863 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
864 Utf8StrFmt(GuestSession::tr("Could not query host file size of \"%s\": %Rrc"),
865 strSource.c_str(), rc));
866 }
867 else
868 rc = fileCopyToEx(strSource, strDest, enmFileCopyFlags, &hFile, 0 /* Offset */, cbSize);
869
870 RTFileClose(hFile);
871 }
872 }
873
874 return rc;
875}
876
877/**
878 * Translates a source path to a destination path (can be both sides,
879 * either host or guest). The source root is needed to determine the start
880 * of the relative source path which also needs to present in the destination
881 * path.
882 *
883 * @return IPRT status code.
884 * @param strSourceRoot Source root path. No trailing directory slash!
885 * @param strSource Actual source to transform. Must begin with
886 * the source root path!
887 * @param strDest Destination path.
888 * @param strOut where to store the output path.
889 */
890int GuestSessionTask::pathConstructOnGuest(const Utf8Str &strSourceRoot, const Utf8Str &strSource,
891 const Utf8Str &strDest, Utf8Str &strOut)
892{
893 RT_NOREF(strSourceRoot, strSource, strDest, strOut);
894 return VINF_SUCCESS;
895}
896
897SessionTaskOpen::SessionTaskOpen(GuestSession *pSession,
898 uint32_t uFlags,
899 uint32_t uTimeoutMS)
900 : GuestSessionTask(pSession),
901 mFlags(uFlags),
902 mTimeoutMS(uTimeoutMS)
903{
904 m_strTaskName = "gctlSesOpen";
905}
906
907SessionTaskOpen::~SessionTaskOpen(void)
908{
909
910}
911
912int SessionTaskOpen::Run(void)
913{
914 LogFlowThisFuncEnter();
915
916 AutoCaller autoCaller(mSession);
917 if (FAILED(autoCaller.rc())) return autoCaller.rc();
918
919 int vrc = mSession->i_startSessionInternal(NULL /*pvrcGuest*/);
920 /* Nothing to do here anymore. */
921
922 LogFlowFuncLeaveRC(vrc);
923 return vrc;
924}
925
926SessionTaskCopyDirFrom::SessionTaskCopyDirFrom(GuestSession *pSession, const Utf8Str &strSource, const Utf8Str &strDest, const Utf8Str &strFilter,
927 DirectoryCopyFlag_T enmDirCopyFlags)
928 : GuestSessionTask(pSession)
929 , mSource(strSource)
930 , mDest(strDest)
931 , mFilter(strFilter)
932 , mDirCopyFlags(enmDirCopyFlags)
933{
934 m_strTaskName = "gctlCpyDirFrm";
935}
936
937SessionTaskCopyDirFrom::~SessionTaskCopyDirFrom(void)
938{
939
940}
941
942/**
943 * Copys a directory (tree) from guest to the host.
944 *
945 * @return IPRT status code.
946 * @param strSource Source directory on the guest to copy to the host.
947 * @param strFilter DOS-style wildcard filter (?, *). Optional.
948 * @param strDest Destination directory on the host.
949 * @param fRecursive Whether to recursively copy the directory contents or not.
950 * @param fFollowSymlinks Whether to follow symlinks or not.
951 * @param strSubDir Current sub directory to handle. Needs to NULL and only
952 * is needed for recursion.
953 */
954int SessionTaskCopyDirFrom::directoryCopyToHost(const Utf8Str &strSource, const Utf8Str &strFilter,
955 const Utf8Str &strDest, bool fRecursive, bool fFollowSymlinks,
956 const Utf8Str &strSubDir /* For recursion. */)
957{
958 Utf8Str strSrcDir = strSource;
959 Utf8Str strDstDir = strDest;
960 Utf8Str strSrcSubDir = strSubDir;
961
962 /* Validation and sanity. */
963 if ( !strSrcDir.endsWith("/")
964 && !strSrcDir.endsWith("\\"))
965 strSrcDir += "/";
966
967 if ( !strDstDir.endsWith("/")
968 && !strDstDir.endsWith("\\"))
969 strDstDir+= "/";
970
971 if ( strSrcSubDir.isNotEmpty() /* Optional, for recursion. */
972 && !strSrcSubDir.endsWith("/")
973 && !strSrcSubDir.endsWith("\\"))
974 strSrcSubDir += "/";
975
976 Utf8Str strSrcCur = strSrcDir + strSrcSubDir;
977
978 LogFlowFunc(("Entering '%s'\n", strSrcCur.c_str()));
979
980 int rc;
981
982 if (strSrcSubDir.isNotEmpty())
983 {
984 const uint32_t fMode = 0700; /** @todo */
985
986 rc = RTDirCreate(Utf8Str(strDstDir + strSrcSubDir).c_str(), fMode, 0);
987 if (RT_FAILURE(rc))
988 return rc;
989 }
990
991 GuestDirectoryOpenInfo dirOpenInfo;
992 dirOpenInfo.mFilter = strFilter;
993 dirOpenInfo.mPath = strSrcCur;
994 dirOpenInfo.mFlags = 0; /** @todo Handle flags? */
995
996 ComObjPtr <GuestDirectory> pDir; int rcGuest;
997 rc = mSession->i_directoryOpenInternal(dirOpenInfo, pDir, &rcGuest);
998 if (RT_FAILURE(rc))
999 {
1000 switch (rc)
1001 {
1002 case VERR_INVALID_PARAMETER:
1003 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1004 Utf8StrFmt(GuestSession::tr("Opening directory \"%s\" failed: Invalid parameter"), dirOpenInfo.mPath.c_str()));
1005 break;
1006
1007 case VERR_GSTCTL_GUEST_ERROR:
1008 setProgressErrorMsg(VBOX_E_IPRT_ERROR, GuestProcess::i_guestErrorToString(rcGuest));
1009 break;
1010
1011 default:
1012 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1013 Utf8StrFmt(GuestSession::tr("Opening directory \"%s\" failed: %Rrc"), dirOpenInfo.mPath.c_str(), rc));
1014 break;
1015 }
1016
1017 return rc;
1018 }
1019
1020 ComObjPtr<GuestFsObjInfo> fsObjInfo;
1021 while (RT_SUCCESS(rc = pDir->i_readInternal(fsObjInfo, &rcGuest)))
1022 {
1023 FsObjType_T enmObjType = FsObjType_Unknown; /* Shut up MSC. */
1024 HRESULT hr2 = fsObjInfo->COMGETTER(Type)(&enmObjType);
1025 AssertComRC(hr2);
1026
1027 com::Bstr bstrName;
1028 hr2 = fsObjInfo->COMGETTER(Name)(bstrName.asOutParam());
1029 AssertComRC(hr2);
1030
1031 Utf8Str strName(bstrName);
1032
1033 LogFlowThisFunc(("strName=%ls\n", strName.c_str()));
1034
1035 switch (enmObjType)
1036 {
1037 case FsObjType_Directory:
1038 {
1039 bool fSkip = false;
1040
1041 if ( strName.equals(".")
1042 || strName.equals(".."))
1043 {
1044 fSkip = true;
1045 }
1046
1047 if ( strFilter.isNotEmpty()
1048 && !RTStrSimplePatternMatch(strFilter.c_str(), strName.c_str()))
1049 fSkip = true;
1050
1051 if ( fRecursive
1052 && !fSkip)
1053 rc = directoryCopyToHost(strSrcDir, strFilter, strDstDir, fRecursive, fFollowSymlinks,
1054 strSrcSubDir + strName);
1055 break;
1056 }
1057
1058 case FsObjType_Symlink:
1059 {
1060 if (fFollowSymlinks)
1061 { /* Fall through to next case is intentional. */ }
1062 else
1063 break;
1064 RT_FALL_THRU();
1065 }
1066
1067 case FsObjType_File:
1068 {
1069 if ( strFilter.isNotEmpty()
1070 && !RTStrSimplePatternMatch(strFilter.c_str(), strName.c_str()))
1071 {
1072 break; /* Filter does not match. */
1073 }
1074
1075 if (RT_SUCCESS(rc))
1076 {
1077 Utf8Str strSrcFile = strSrcDir + strSrcSubDir + strName;
1078 Utf8Str strDstFile = strDstDir + strSrcSubDir + strName;
1079 rc = fileCopyFrom(strSrcFile, strDstFile, FileCopyFlag_None);
1080 }
1081 break;
1082 }
1083
1084 default:
1085 break;
1086 }
1087 }
1088
1089 if (rc == VERR_NO_MORE_FILES) /* Reading done? */
1090 rc = VINF_SUCCESS;
1091
1092 pDir->i_closeInternal(&rcGuest);
1093
1094 LogFlowFunc(("Leaving '%s', rc=%Rrc\n", strSrcCur.c_str(), rc));
1095 return rc;
1096}
1097
1098int SessionTaskCopyDirFrom::Run(void)
1099{
1100 LogFlowThisFuncEnter();
1101
1102 AutoCaller autoCaller(mSession);
1103 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1104
1105 const bool fRecursive = true; /** @todo Make this configurable. */
1106 const bool fFollowSymlinks = true; /** @todo Make this configurable. */
1107 const uint32_t fDirMode = 0700; /* Play safe by default. */
1108
1109 int rc = VINF_SUCCESS;
1110
1111 /* Create the root target directory on the host.
1112 * The target directory might already exist on the host (based on mDirCopyFlags). */
1113 const bool fExists = RTDirExists(mDest.c_str());
1114 if ( fExists
1115 && !(mDirCopyFlags & DirectoryCopyFlag_CopyIntoExisting))
1116 {
1117 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1118 Utf8StrFmt(GuestSession::tr("Destination directory \"%s\" exists when it must not"), mDest.c_str()));
1119 rc = VERR_ALREADY_EXISTS;
1120 }
1121 else if (!fExists)
1122 {
1123 rc = RTDirCreate(mDest.c_str(), fDirMode, 0);
1124 if (RT_FAILURE(rc))
1125 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1126 Utf8StrFmt(GuestSession::tr("Error creating destination directory \"%s\", rc=%Rrc"),
1127 mDest.c_str(), rc));
1128 }
1129
1130 if (RT_FAILURE(rc))
1131 return rc;
1132
1133 RTDIR hDir;
1134 rc = RTDirOpen(&hDir, mDest.c_str());
1135 if (RT_FAILURE(rc))
1136 {
1137 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1138 Utf8StrFmt(GuestSession::tr("Error opening destination directory \"%s\", rc=%Rrc"),
1139 mDest.c_str(), rc));
1140 return rc;
1141 }
1142
1143 /* At this point the directory on the host was created and (hopefully) is ready
1144 * to receive further content. */
1145 rc = directoryCopyToHost(mSource, mFilter, mDest, fRecursive, fFollowSymlinks,
1146 "" /* strSubDir; for recursion */);
1147 if (RT_SUCCESS(rc))
1148 rc = setProgressSuccess();
1149
1150 RTDirClose(hDir);
1151
1152 LogFlowFuncLeaveRC(rc);
1153 return rc;
1154}
1155
1156SessionTaskCopyDirTo::SessionTaskCopyDirTo(GuestSession *pSession,
1157 const Utf8Str &strSource, const Utf8Str &strDest, const Utf8Str &strFilter,
1158 DirectoryCopyFlag_T enmDirCopyFlags)
1159 : GuestSessionTask(pSession)
1160 , mSource(strSource)
1161 , mDest(strDest)
1162 , mFilter(strFilter)
1163 , mDirCopyFlags(enmDirCopyFlags)
1164{
1165 m_strTaskName = "gctlCpyDirTo";
1166}
1167
1168SessionTaskCopyDirTo::~SessionTaskCopyDirTo(void)
1169{
1170
1171}
1172
1173/**
1174 * Copys a directory (tree) from host to the guest.
1175 *
1176 * @return IPRT status code.
1177 * @param strSource Source directory on the host to copy to the guest.
1178 * @param strFilter DOS-style wildcard filter (?, *). Optional.
1179 * @param strDest Destination directory on the guest.
1180 * @param fRecursive Whether to recursively copy the directory contents or not.
1181 * @param fFollowSymlinks Whether to follow symlinks or not.
1182 * @param strSubDir Current sub directory to handle. Needs to NULL and only
1183 * is needed for recursion.
1184 */
1185int SessionTaskCopyDirTo::directoryCopyToGuest(const Utf8Str &strSource, const Utf8Str &strFilter,
1186 const Utf8Str &strDest, bool fRecursive, bool fFollowSymlinks,
1187 const Utf8Str &strSubDir /* For recursion. */)
1188{
1189 Utf8Str strSrcDir = strSource;
1190 Utf8Str strDstDir = strDest;
1191 Utf8Str strSrcSubDir = strSubDir;
1192
1193 /* Validation and sanity. */
1194 if ( !strSrcDir.endsWith("/")
1195 && !strSrcDir.endsWith("\\"))
1196 strSrcDir += "/";
1197
1198 if ( !strDstDir.endsWith("/")
1199 && !strDstDir.endsWith("\\"))
1200 strDstDir+= "/";
1201
1202 if ( strSrcSubDir.isNotEmpty() /* Optional, for recursion. */
1203 && !strSrcSubDir.endsWith("/")
1204 && !strSrcSubDir.endsWith("\\"))
1205 strSrcSubDir += "/";
1206
1207 Utf8Str strSrcCur = strSrcDir + strSrcSubDir;
1208
1209 LogFlowFunc(("Entering '%s'\n", strSrcCur.c_str()));
1210
1211 int rc;
1212
1213 if (strSrcSubDir.isNotEmpty())
1214 {
1215 const uint32_t uMode = 0700; /** @todo */
1216 rc = directoryCreate(strDstDir + strSrcSubDir, DirectoryCreateFlag_Parents, uMode, fFollowSymlinks);
1217 if (RT_FAILURE(rc))
1218 return rc;
1219 }
1220
1221 /*
1222 * Open directory without a filter - RTDirOpenFiltered unfortunately
1223 * cannot handle sub directories so we have to do the filtering ourselves.
1224 */
1225 RTDIR hDir;
1226 rc = RTDirOpen(&hDir, strSrcCur.c_str());
1227 if (RT_SUCCESS(rc))
1228 {
1229 /*
1230 * Enumerate the directory tree.
1231 */
1232 size_t cbDirEntry = 0;
1233 PRTDIRENTRYEX pDirEntry = NULL;
1234 while (RT_SUCCESS(rc))
1235 {
1236 rc = RTDirReadExA(hDir, &pDirEntry, &cbDirEntry, RTFSOBJATTRADD_NOTHING, RTPATH_F_ON_LINK);
1237 if (RT_FAILURE(rc))
1238 {
1239 if (rc == VERR_NO_MORE_FILES)
1240 rc = VINF_SUCCESS;
1241 break;
1242 }
1243
1244#ifdef LOG_ENABLED
1245 Utf8Str strDbgCurEntry = strSrcCur + Utf8Str(pDirEntry->szName);
1246 LogFlowFunc(("Handling '%s' (fMode=0x%x)\n", strDbgCurEntry.c_str(), pDirEntry->Info.Attr.fMode & RTFS_TYPE_MASK));
1247#endif
1248 switch (pDirEntry->Info.Attr.fMode & RTFS_TYPE_MASK)
1249 {
1250 case RTFS_TYPE_DIRECTORY:
1251 {
1252 /* Skip "." and ".." entries. */
1253 if (RTDirEntryExIsStdDotLink(pDirEntry))
1254 break;
1255
1256 bool fSkip = false;
1257
1258 if ( strFilter.isNotEmpty()
1259 && !RTStrSimplePatternMatch(strFilter.c_str(), pDirEntry->szName))
1260 fSkip = true;
1261
1262 if ( fRecursive
1263 && !fSkip)
1264 rc = directoryCopyToGuest(strSrcDir, strFilter, strDstDir, fRecursive, fFollowSymlinks,
1265 strSrcSubDir + Utf8Str(pDirEntry->szName));
1266 break;
1267 }
1268
1269 case RTFS_TYPE_SYMLINK:
1270 if (fFollowSymlinks)
1271 { /* Fall through to next case is intentional. */ }
1272 else
1273 break;
1274 RT_FALL_THRU();
1275
1276 case RTFS_TYPE_FILE:
1277 {
1278 if ( strFilter.isNotEmpty()
1279 && !RTStrSimplePatternMatch(strFilter.c_str(), pDirEntry->szName))
1280 {
1281 break; /* Filter does not match. */
1282 }
1283
1284 if (RT_SUCCESS(rc))
1285 {
1286 Utf8Str strSrcFile = strSrcDir + strSrcSubDir + Utf8Str(pDirEntry->szName);
1287 Utf8Str strDstFile = strDstDir + strSrcSubDir + Utf8Str(pDirEntry->szName);
1288 rc = fileCopyTo(strSrcFile, strDstFile, FileCopyFlag_None);
1289 }
1290 break;
1291 }
1292
1293 default:
1294 break;
1295 }
1296 if (RT_FAILURE(rc))
1297 break;
1298 }
1299
1300 RTDirReadExAFree(&pDirEntry, &cbDirEntry);
1301 RTDirClose(hDir);
1302 }
1303
1304 LogFlowFunc(("Leaving '%s', rc=%Rrc\n", strSrcCur.c_str(), rc));
1305 return rc;
1306}
1307
1308int SessionTaskCopyDirTo::Run(void)
1309{
1310 LogFlowThisFuncEnter();
1311
1312 AutoCaller autoCaller(mSession);
1313 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1314
1315 const bool fRecursive = true; /** @todo Make this configurable. */
1316 const bool fFollowSymlinks = true; /** @todo Make this configurable. */
1317 const uint32_t uDirMode = 0700; /* Play safe by default. */
1318
1319 /* Create the root target directory on the guest.
1320 * The target directory might already exist on the guest (based on mDirCopyFlags). */
1321 int rc = directoryCreate(mDest, DirectoryCreateFlag_None, uDirMode, fFollowSymlinks);
1322 if ( rc == VWRN_ALREADY_EXISTS
1323 && !(mDirCopyFlags & DirectoryCopyFlag_CopyIntoExisting))
1324 {
1325 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1326 Utf8StrFmt(GuestSession::tr("Destination directory \"%s\" exists when it must not"), mDest.c_str()));
1327 }
1328
1329 if (RT_FAILURE(rc))
1330 return rc;
1331
1332 /* At this point the directory on the guest was created and (hopefully) is ready
1333 * to receive further content. */
1334 rc = directoryCopyToGuest(mSource, mFilter, mDest, fRecursive, fFollowSymlinks,
1335 "" /* strSubDir; for recursion */);
1336 if (RT_SUCCESS(rc))
1337 rc = setProgressSuccess();
1338
1339 LogFlowFuncLeaveRC(rc);
1340 return rc;
1341}
1342
1343SessionTaskCopyFileTo::SessionTaskCopyFileTo(GuestSession *pSession,
1344 const Utf8Str &strSource, const Utf8Str &strDest, FileCopyFlag_T enmFileCopyFlags)
1345 : GuestSessionTask(pSession)
1346 , mSource(strSource)
1347 , mSourceFile(NULL)
1348 , mSourceOffset(0)
1349 , mSourceSize(0)
1350 , mDest(strDest)
1351 , mFileCopyFlags(enmFileCopyFlags)
1352{
1353 m_strTaskName = "gctlCpyFileTo";
1354}
1355
1356SessionTaskCopyFileTo::SessionTaskCopyFileTo(GuestSession *pSession,
1357 PRTFILE pSourceFile, size_t cbSourceOffset, uint64_t cbSourceSize,
1358 const Utf8Str &strDest, FileCopyFlag_T enmFileCopyFlags)
1359 : GuestSessionTask(pSession)
1360 , mSourceFile(pSourceFile)
1361 , mSourceOffset(cbSourceOffset)
1362 , mSourceSize(cbSourceSize)
1363 , mDest(strDest)
1364 , mFileCopyFlags(enmFileCopyFlags)
1365{
1366 m_strTaskName = "gctlCpyFileToH";
1367}
1368
1369SessionTaskCopyFileTo::~SessionTaskCopyFileTo(void)
1370{
1371
1372}
1373
1374int SessionTaskCopyFileTo::Run(void)
1375{
1376 LogFlowThisFuncEnter();
1377
1378 AutoCaller autoCaller(mSession);
1379 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1380
1381 if (mSource.isEmpty())
1382 {
1383 setProgressErrorMsg(VBOX_E_IPRT_ERROR, Utf8StrFmt(GuestSession::tr("No source file specified")));
1384 return VERR_INVALID_PARAMETER;
1385 }
1386
1387 if (mDest.isEmpty())
1388 {
1389 setProgressErrorMsg(VBOX_E_IPRT_ERROR, Utf8StrFmt(GuestSession::tr("No destintation file specified")));
1390 return VERR_INVALID_PARAMETER;
1391 }
1392
1393 const char *pszFileName = RTPathFilename(mSource.c_str());
1394
1395 if ( !pszFileName
1396 || !RTFileExists(pszFileName))
1397 {
1398 setProgressErrorMsg(VBOX_E_IPRT_ERROR, Utf8StrFmt(GuestSession::tr("Source file not valid or does not exist")));
1399 return VERR_FILE_NOT_FOUND;
1400 }
1401
1402 if (mFileCopyFlags)
1403 {
1404 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1405 Utf8StrFmt(GuestSession::tr("Copy flags (%#x) not implemented yet"),
1406 mFileCopyFlags));
1407 return VERR_NOT_IMPLEMENTED;
1408 }
1409
1410 /** @todo Try to lock the destination directory on the guest here first? */
1411
1412 int rc = VINF_SUCCESS;
1413
1414 /*
1415 * Query information about our destination first.
1416 */
1417 if ( mDest.endsWith("/")
1418 || mDest.endsWith("\\"))
1419 {
1420 int rcGuest;
1421 GuestFsObjData objData;
1422 rc = mSession->i_fsQueryInfoInternal(mDest, true /* fFollowSymlinks */, objData, &rcGuest);
1423 if (RT_SUCCESS(rc))
1424 {
1425 if (objData.mType != FsObjType_Directory)
1426 {
1427 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1428 Utf8StrFmt(GuestSession::tr("Path \"%s\" is not a directory on guest"), mDest.c_str()));
1429 rc = VERR_NOT_A_DIRECTORY;
1430 }
1431 else
1432 {
1433 AssertPtr(pszFileName);
1434 mDest += pszFileName;
1435 }
1436 }
1437 else
1438 {
1439 switch (rc)
1440 {
1441 case VERR_GSTCTL_GUEST_ERROR:
1442 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1443 GuestProcess::i_guestErrorToString(rcGuest));
1444 break;
1445
1446 default:
1447 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1448 Utf8StrFmt(GuestSession::tr("Unable to query information for directory \"%s\" on the guest: %Rrc"),
1449 mDest.c_str(), rc));
1450 break;
1451 }
1452 }
1453 }
1454
1455 if (RT_SUCCESS(rc))
1456 {
1457 if (mSourceFile) /* Use existing file handle. */
1458 rc = fileCopyToEx(mSource, mDest, (FileCopyFlag_T)mFileCopyFlags, mSourceFile, mSourceOffset, mSourceSize);
1459 else
1460 rc = fileCopyTo(mSource, mDest, (FileCopyFlag_T)mFileCopyFlags);
1461
1462 if (RT_SUCCESS(rc))
1463 rc = setProgressSuccess();
1464 }
1465
1466 LogFlowFuncLeaveRC(rc);
1467 return rc;
1468}
1469
1470SessionTaskCopyFileFrom::SessionTaskCopyFileFrom(GuestSession *pSession,
1471 const Utf8Str &strSource, const Utf8Str &strDest, FileCopyFlag_T enmFileCopyFlags)
1472 : GuestSessionTask(pSession)
1473 , mSource(strSource)
1474 , mDest(strDest)
1475 , mFileCopyFlags(enmFileCopyFlags)
1476{
1477 m_strTaskName = "gctlCpyFileFrm";
1478}
1479
1480SessionTaskCopyFileFrom::~SessionTaskCopyFileFrom(void)
1481{
1482
1483}
1484
1485int SessionTaskCopyFileFrom::Run(void)
1486{
1487 LogFlowThisFuncEnter();
1488
1489 AutoCaller autoCaller(mSession);
1490 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1491
1492 int rc = fileCopyFrom(mSource, mDest, mFileCopyFlags);
1493 if (RT_SUCCESS(rc))
1494 rc = setProgressSuccess();
1495
1496 LogFlowFuncLeaveRC(rc);
1497 return rc;
1498}
1499
1500SessionTaskUpdateAdditions::SessionTaskUpdateAdditions(GuestSession *pSession,
1501 const Utf8Str &strSource,
1502 const ProcessArguments &aArguments,
1503 uint32_t uFlags)
1504 : GuestSessionTask(pSession)
1505{
1506 mSource = strSource;
1507 mArguments = aArguments;
1508 mFlags = uFlags;
1509 m_strTaskName = "gctlUpGA";
1510}
1511
1512SessionTaskUpdateAdditions::~SessionTaskUpdateAdditions(void)
1513{
1514
1515}
1516
1517int SessionTaskUpdateAdditions::addProcessArguments(ProcessArguments &aArgumentsDest, const ProcessArguments &aArgumentsSource)
1518{
1519 int rc = VINF_SUCCESS;
1520
1521 try
1522 {
1523 /* Filter out arguments which already are in the destination to
1524 * not end up having them specified twice. Not the fastest method on the
1525 * planet but does the job. */
1526 ProcessArguments::const_iterator itSource = aArgumentsSource.begin();
1527 while (itSource != aArgumentsSource.end())
1528 {
1529 bool fFound = false;
1530 ProcessArguments::iterator itDest = aArgumentsDest.begin();
1531 while (itDest != aArgumentsDest.end())
1532 {
1533 if ((*itDest).equalsIgnoreCase((*itSource)))
1534 {
1535 fFound = true;
1536 break;
1537 }
1538 ++itDest;
1539 }
1540
1541 if (!fFound)
1542 aArgumentsDest.push_back((*itSource));
1543
1544 ++itSource;
1545 }
1546 }
1547 catch(std::bad_alloc &)
1548 {
1549 return VERR_NO_MEMORY;
1550 }
1551
1552 return rc;
1553}
1554
1555int SessionTaskUpdateAdditions::copyFileToGuest(GuestSession *pSession, PRTISOFSFILE pISO,
1556 Utf8Str const &strFileSource, const Utf8Str &strFileDest,
1557 bool fOptional, uint32_t *pcbSize)
1558{
1559 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1560 AssertPtrReturn(pISO, VERR_INVALID_POINTER);
1561 /* pcbSize is optional. */
1562
1563 uint32_t cbOffset;
1564 size_t cbSize;
1565
1566 int rc = RTIsoFsGetFileInfo(pISO, strFileSource.c_str(), &cbOffset, &cbSize);
1567 if (RT_FAILURE(rc))
1568 {
1569 if (fOptional)
1570 return VINF_SUCCESS;
1571
1572 return rc;
1573 }
1574
1575 Assert(cbOffset);
1576 Assert(cbSize);
1577 rc = RTFileSeek(pISO->file, cbOffset, RTFILE_SEEK_BEGIN, NULL);
1578
1579 HRESULT hr = S_OK;
1580 /* Copy over the Guest Additions file to the guest. */
1581 if (RT_SUCCESS(rc))
1582 {
1583 LogRel(("Copying Guest Additions installer file \"%s\" to \"%s\" on guest ...\n",
1584 strFileSource.c_str(), strFileDest.c_str()));
1585
1586 if (RT_SUCCESS(rc))
1587 {
1588 SessionTaskCopyFileTo *pTask = NULL;
1589 ComObjPtr<Progress> pProgressCopyTo;
1590 try
1591 {
1592 try
1593 {
1594 pTask = new SessionTaskCopyFileTo(pSession /* GuestSession */,
1595 &pISO->file, cbOffset, cbSize,
1596 strFileDest, FileCopyFlag_None);
1597 }
1598 catch(...)
1599 {
1600 hr = setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1601 GuestSession::tr("Failed to create SessionTaskCopyTo object "));
1602 throw;
1603 }
1604
1605 hr = pTask->Init(Utf8StrFmt(GuestSession::tr("Copying Guest Additions installer file \"%s\" to \"%s\" on guest"),
1606 mSource.c_str(), strFileDest.c_str()));
1607 if (FAILED(hr))
1608 {
1609 delete pTask;
1610 hr = setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1611 GuestSession::tr("Creating progress object for SessionTaskCopyTo object failed"));
1612 throw hr;
1613 }
1614
1615 hr = pTask->createThreadWithType(RTTHREADTYPE_MAIN_HEAVY_WORKER);
1616
1617 if (SUCCEEDED(hr))
1618 {
1619 /* Return progress to the caller. */
1620 pProgressCopyTo = pTask->GetProgressObject();
1621 }
1622 else
1623 hr = setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1624 GuestSession::tr("Starting thread for updating additions failed "));
1625 }
1626 catch(std::bad_alloc &)
1627 {
1628 hr = E_OUTOFMEMORY;
1629 }
1630 catch(HRESULT eHR)
1631 {
1632 hr = eHR;
1633 LogFlowThisFunc(("Exception was caught in the function \n"));
1634 }
1635
1636 if (SUCCEEDED(hr))
1637 {
1638 BOOL fCanceled = FALSE;
1639 hr = pProgressCopyTo->WaitForCompletion(-1);
1640 if ( SUCCEEDED(pProgressCopyTo->COMGETTER(Canceled)(&fCanceled))
1641 && fCanceled)
1642 {
1643 rc = VERR_GENERAL_FAILURE; /* Fudge. */
1644 }
1645 else if (FAILED(hr))
1646 {
1647 Assert(FAILED(hr));
1648 rc = VERR_GENERAL_FAILURE; /* Fudge. */
1649 }
1650 }
1651 }
1652 }
1653
1654 /** @todo Note: Since there is no file locking involved at the moment, there can be modifications
1655 * between finished copying, the verification and the actual execution. */
1656
1657 /* Determine where the installer image ended up and if it has the correct size. */
1658 if (RT_SUCCESS(rc))
1659 {
1660 LogRel(("Verifying Guest Additions installer file \"%s\" ...\n",
1661 strFileDest.c_str()));
1662
1663 GuestFsObjData objData;
1664 int64_t cbSizeOnGuest;
1665 int rcGuest = VERR_IPE_UNINITIALIZED_STATUS;
1666 rc = pSession->i_fileQuerySizeInternal(strFileDest, false /*fFollowSymlinks*/, &cbSizeOnGuest, &rcGuest);
1667 if ( RT_SUCCESS(rc)
1668 && cbSize == (uint64_t)cbSizeOnGuest)
1669 {
1670 LogFlowThisFunc(("Guest Additions installer file \"%s\" successfully verified\n",
1671 strFileDest.c_str()));
1672 }
1673 else
1674 {
1675 if (RT_SUCCESS(rc)) /* Size does not match. */
1676 {
1677 LogRel(("Size of Guest Additions installer file \"%s\" does not match: %RI64 bytes copied, %RU64 bytes expected\n",
1678 strFileDest.c_str(), cbSizeOnGuest, cbSize));
1679 rc = VERR_BROKEN_PIPE; /** @todo Find a better error. */
1680 }
1681 else
1682 {
1683 switch (rc)
1684 {
1685 case VERR_GSTCTL_GUEST_ERROR:
1686 setProgressErrorMsg(VBOX_E_IPRT_ERROR, GuestProcess::i_guestErrorToString(rcGuest));
1687 break;
1688
1689 default:
1690 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1691 Utf8StrFmt(GuestSession::tr("Error while querying size for file \"%s\": %Rrc"),
1692 strFileDest.c_str(), rc));
1693 break;
1694 }
1695 }
1696 }
1697
1698 if (RT_SUCCESS(rc))
1699 {
1700 if (pcbSize)
1701 *pcbSize = (uint32_t)cbSizeOnGuest;
1702 }
1703 }
1704
1705 return rc;
1706}
1707
1708int SessionTaskUpdateAdditions::runFileOnGuest(GuestSession *pSession, GuestProcessStartupInfo &procInfo)
1709{
1710 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1711
1712 LogRel(("Running %s ...\n", procInfo.mName.c_str()));
1713
1714 GuestProcessTool procTool;
1715 int rcGuest = VERR_IPE_UNINITIALIZED_STATUS;
1716 int vrc = procTool.Init(pSession, procInfo, false /* Async */, &rcGuest);
1717 if (RT_SUCCESS(vrc))
1718 {
1719 if (RT_SUCCESS(rcGuest))
1720 vrc = procTool.i_wait(GUESTPROCESSTOOL_FLAG_NONE, &rcGuest);
1721 if (RT_SUCCESS(vrc))
1722 vrc = procTool.i_terminatedOk();
1723 }
1724
1725 if (RT_FAILURE(vrc))
1726 {
1727 switch (vrc)
1728 {
1729 case VWRN_GSTCTL_PROCESS_EXIT_CODE:
1730 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1731 Utf8StrFmt(GuestSession::tr("Running update file \"%s\" on guest failed: %Rrc"),
1732 procInfo.mExecutable.c_str(), procTool.i_getRc()));
1733 break;
1734
1735 case VERR_GSTCTL_GUEST_ERROR:
1736 setProgressErrorMsg(VBOX_E_IPRT_ERROR, GuestProcess::i_guestErrorToString(rcGuest));
1737 break;
1738
1739 case VERR_INVALID_STATE: /** @todo Special guest control rc needed! */
1740 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1741 Utf8StrFmt(GuestSession::tr("Update file \"%s\" reported invalid running state"),
1742 procInfo.mExecutable.c_str()));
1743 break;
1744
1745 default:
1746 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1747 Utf8StrFmt(GuestSession::tr("Error while running update file \"%s\" on guest: %Rrc"),
1748 procInfo.mExecutable.c_str(), vrc));
1749 break;
1750 }
1751 }
1752
1753 return vrc;
1754}
1755
1756int SessionTaskUpdateAdditions::Run(void)
1757{
1758 LogFlowThisFuncEnter();
1759
1760 ComObjPtr<GuestSession> pSession = mSession;
1761 Assert(!pSession.isNull());
1762
1763 AutoCaller autoCaller(pSession);
1764 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1765
1766 int rc = setProgress(10);
1767 if (RT_FAILURE(rc))
1768 return rc;
1769
1770 HRESULT hr = S_OK;
1771
1772 LogRel(("Automatic update of Guest Additions started, using \"%s\"\n", mSource.c_str()));
1773
1774 ComObjPtr<Guest> pGuest(mSession->i_getParent());
1775#if 0
1776 /*
1777 * Wait for the guest being ready within 30 seconds.
1778 */
1779 AdditionsRunLevelType_T addsRunLevel;
1780 uint64_t tsStart = RTTimeSystemMilliTS();
1781 while ( SUCCEEDED(hr = pGuest->COMGETTER(AdditionsRunLevel)(&addsRunLevel))
1782 && ( addsRunLevel != AdditionsRunLevelType_Userland
1783 && addsRunLevel != AdditionsRunLevelType_Desktop))
1784 {
1785 if ((RTTimeSystemMilliTS() - tsStart) > 30 * 1000)
1786 {
1787 rc = VERR_TIMEOUT;
1788 break;
1789 }
1790
1791 RTThreadSleep(100); /* Wait a bit. */
1792 }
1793
1794 if (FAILED(hr)) rc = VERR_TIMEOUT;
1795 if (rc == VERR_TIMEOUT)
1796 hr = setProgressErrorMsg(VBOX_E_NOT_SUPPORTED,
1797 Utf8StrFmt(GuestSession::tr("Guest Additions were not ready within time, giving up")));
1798#else
1799 /*
1800 * For use with the GUI we don't want to wait, just return so that the manual .ISO mounting
1801 * can continue.
1802 */
1803 AdditionsRunLevelType_T addsRunLevel;
1804 if ( FAILED(hr = pGuest->COMGETTER(AdditionsRunLevel)(&addsRunLevel))
1805 || ( addsRunLevel != AdditionsRunLevelType_Userland
1806 && addsRunLevel != AdditionsRunLevelType_Desktop))
1807 {
1808 if (addsRunLevel == AdditionsRunLevelType_System)
1809 hr = setProgressErrorMsg(VBOX_E_NOT_SUPPORTED,
1810 Utf8StrFmt(GuestSession::tr("Guest Additions are installed but not fully loaded yet, aborting automatic update")));
1811 else
1812 hr = setProgressErrorMsg(VBOX_E_NOT_SUPPORTED,
1813 Utf8StrFmt(GuestSession::tr("Guest Additions not installed or ready, aborting automatic update")));
1814 rc = VERR_NOT_SUPPORTED;
1815 }
1816#endif
1817
1818 if (RT_SUCCESS(rc))
1819 {
1820 /*
1821 * Determine if we are able to update automatically. This only works
1822 * if there are recent Guest Additions installed already.
1823 */
1824 Utf8Str strAddsVer;
1825 rc = getGuestProperty(pGuest, "/VirtualBox/GuestAdd/Version", strAddsVer);
1826 if ( RT_SUCCESS(rc)
1827 && RTStrVersionCompare(strAddsVer.c_str(), "4.1") < 0)
1828 {
1829 hr = setProgressErrorMsg(VBOX_E_NOT_SUPPORTED,
1830 Utf8StrFmt(GuestSession::tr("Guest has too old Guest Additions (%s) installed for automatic updating, please update manually"),
1831 strAddsVer.c_str()));
1832 rc = VERR_NOT_SUPPORTED;
1833 }
1834 }
1835
1836 Utf8Str strOSVer;
1837 eOSType osType = eOSType_Unknown;
1838 if (RT_SUCCESS(rc))
1839 {
1840 /*
1841 * Determine guest OS type and the required installer image.
1842 */
1843 Utf8Str strOSType;
1844 rc = getGuestProperty(pGuest, "/VirtualBox/GuestInfo/OS/Product", strOSType);
1845 if (RT_SUCCESS(rc))
1846 {
1847 if ( strOSType.contains("Microsoft", Utf8Str::CaseInsensitive)
1848 || strOSType.contains("Windows", Utf8Str::CaseInsensitive))
1849 {
1850 osType = eOSType_Windows;
1851
1852 /*
1853 * Determine guest OS version.
1854 */
1855 rc = getGuestProperty(pGuest, "/VirtualBox/GuestInfo/OS/Release", strOSVer);
1856 if (RT_FAILURE(rc))
1857 {
1858 hr = setProgressErrorMsg(VBOX_E_NOT_SUPPORTED,
1859 Utf8StrFmt(GuestSession::tr("Unable to detected guest OS version, please update manually")));
1860 rc = VERR_NOT_SUPPORTED;
1861 }
1862
1863 /* Because Windows 2000 + XP and is bitching with WHQL popups even if we have signed drivers we
1864 * can't do automated updates here. */
1865 /* Windows XP 64-bit (5.2) is a Windows 2003 Server actually, so skip this here. */
1866 if ( RT_SUCCESS(rc)
1867 && RTStrVersionCompare(strOSVer.c_str(), "5.0") >= 0)
1868 {
1869 if ( strOSVer.startsWith("5.0") /* Exclude the build number. */
1870 || strOSVer.startsWith("5.1") /* Exclude the build number. */)
1871 {
1872 /* If we don't have AdditionsUpdateFlag_WaitForUpdateStartOnly set we can't continue
1873 * because the Windows Guest Additions installer will fail because of WHQL popups. If the
1874 * flag is set this update routine ends successfully as soon as the installer was started
1875 * (and the user has to deal with it in the guest). */
1876 if (!(mFlags & AdditionsUpdateFlag_WaitForUpdateStartOnly))
1877 {
1878 hr = setProgressErrorMsg(VBOX_E_NOT_SUPPORTED,
1879 Utf8StrFmt(GuestSession::tr("Windows 2000 and XP are not supported for automatic updating due to WHQL interaction, please update manually")));
1880 rc = VERR_NOT_SUPPORTED;
1881 }
1882 }
1883 }
1884 else
1885 {
1886 hr = setProgressErrorMsg(VBOX_E_NOT_SUPPORTED,
1887 Utf8StrFmt(GuestSession::tr("%s (%s) not supported for automatic updating, please update manually"),
1888 strOSType.c_str(), strOSVer.c_str()));
1889 rc = VERR_NOT_SUPPORTED;
1890 }
1891 }
1892 else if (strOSType.contains("Solaris", Utf8Str::CaseInsensitive))
1893 {
1894 osType = eOSType_Solaris;
1895 }
1896 else /* Everything else hopefully means Linux :-). */
1897 osType = eOSType_Linux;
1898
1899#if 1 /* Only Windows is supported (and tested) at the moment. */
1900 if ( RT_SUCCESS(rc)
1901 && osType != eOSType_Windows)
1902 {
1903 hr = setProgressErrorMsg(VBOX_E_NOT_SUPPORTED,
1904 Utf8StrFmt(GuestSession::tr("Detected guest OS (%s) does not support automatic Guest Additions updating, please update manually"),
1905 strOSType.c_str()));
1906 rc = VERR_NOT_SUPPORTED;
1907 }
1908#endif
1909 }
1910 }
1911
1912 RTISOFSFILE iso;
1913 if (RT_SUCCESS(rc))
1914 {
1915 /*
1916 * Try to open the .ISO file to extract all needed files.
1917 */
1918 rc = RTIsoFsOpen(&iso, mSource.c_str());
1919 if (RT_FAILURE(rc))
1920 {
1921 hr = setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1922 Utf8StrFmt(GuestSession::tr("Unable to open Guest Additions .ISO file \"%s\": %Rrc"),
1923 mSource.c_str(), rc));
1924 }
1925 else
1926 {
1927 /* Set default installation directories. */
1928 Utf8Str strUpdateDir = "/tmp/";
1929 if (osType == eOSType_Windows)
1930 strUpdateDir = "C:\\Temp\\";
1931
1932 rc = setProgress(5);
1933
1934 /* Try looking up the Guest Additions installation directory. */
1935 if (RT_SUCCESS(rc))
1936 {
1937 /* Try getting the installed Guest Additions version to know whether we
1938 * can install our temporary Guest Addition data into the original installation
1939 * directory.
1940 *
1941 * Because versions prior to 4.2 had bugs wrt spaces in paths we have to choose
1942 * a different location then.
1943 */
1944 bool fUseInstallDir = false;
1945
1946 Utf8Str strAddsVer;
1947 rc = getGuestProperty(pGuest, "/VirtualBox/GuestAdd/Version", strAddsVer);
1948 if ( RT_SUCCESS(rc)
1949 && RTStrVersionCompare(strAddsVer.c_str(), "4.2r80329") > 0)
1950 {
1951 fUseInstallDir = true;
1952 }
1953
1954 if (fUseInstallDir)
1955 {
1956 if (RT_SUCCESS(rc))
1957 rc = getGuestProperty(pGuest, "/VirtualBox/GuestAdd/InstallDir", strUpdateDir);
1958 if (RT_SUCCESS(rc))
1959 {
1960 if (osType == eOSType_Windows)
1961 {
1962 strUpdateDir.findReplace('/', '\\');
1963 strUpdateDir.append("\\Update\\");
1964 }
1965 else
1966 strUpdateDir.append("/update/");
1967 }
1968 }
1969 }
1970
1971 if (RT_SUCCESS(rc))
1972 LogRel(("Guest Additions update directory is: %s\n",
1973 strUpdateDir.c_str()));
1974
1975 /* Create the installation directory. */
1976 int rcGuest = VERR_IPE_UNINITIALIZED_STATUS;
1977 rc = pSession->i_directoryCreateInternal(strUpdateDir, 755 /* Mode */, DirectoryCreateFlag_Parents, &rcGuest);
1978 if (RT_FAILURE(rc))
1979 {
1980 switch (rc)
1981 {
1982 case VERR_GSTCTL_GUEST_ERROR:
1983 hr = setProgressErrorMsg(VBOX_E_IPRT_ERROR, GuestProcess::i_guestErrorToString(rcGuest));
1984 break;
1985
1986 default:
1987 hr = setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1988 Utf8StrFmt(GuestSession::tr("Error creating installation directory \"%s\" on the guest: %Rrc"),
1989 strUpdateDir.c_str(), rc));
1990 break;
1991 }
1992 }
1993 if (RT_SUCCESS(rc))
1994 rc = setProgress(10);
1995
1996 if (RT_SUCCESS(rc))
1997 {
1998 /* Prepare the file(s) we want to copy over to the guest and
1999 * (maybe) want to run. */
2000 switch (osType)
2001 {
2002 case eOSType_Windows:
2003 {
2004 /* Do we need to install our certificates? We do this for W2K and up. */
2005 bool fInstallCert = false;
2006
2007 /* Only Windows 2000 and up need certificates to be installed. */
2008 if (RTStrVersionCompare(strOSVer.c_str(), "5.0") >= 0)
2009 {
2010 fInstallCert = true;
2011 LogRel(("Certificates for auto updating WHQL drivers will be installed\n"));
2012 }
2013 else
2014 LogRel(("Skipping installation of certificates for WHQL drivers\n"));
2015
2016 if (fInstallCert)
2017 {
2018 static struct { const char *pszDst, *pszIso; } const s_aCertFiles[] =
2019 {
2020 { "vbox.cer", "CERT/VBOX.CER" },
2021 { "vbox-sha1.cer", "CERT/VBOX_SHA1.CER" },
2022 { "vbox-sha256.cer", "CERT/VBOX_SHA256.CER" },
2023 { "vbox-sha256-r3.cer", "CERT/VBOX_SHA256_R3.CER" },
2024 { "oracle-vbox.cer", "CERT/ORACLE_VBOX.CER" },
2025 };
2026 uint32_t fCopyCertUtil = UPDATEFILE_FLAG_COPY_FROM_ISO;
2027 for (uint32_t i = 0; i < RT_ELEMENTS(s_aCertFiles); i++)
2028 {
2029 /* Skip if not present on the ISO. */
2030 uint32_t offIgn;
2031 size_t cbIgn;
2032 rc = RTIsoFsGetFileInfo(&iso, s_aCertFiles[i].pszIso, &offIgn, &cbIgn);
2033 if (RT_FAILURE(rc))
2034 continue;
2035
2036 /* Copy the certificate certificate. */
2037 Utf8Str const strDstCert(strUpdateDir + s_aCertFiles[i].pszDst);
2038 mFiles.push_back(InstallerFile(s_aCertFiles[i].pszIso,
2039 strDstCert,
2040 UPDATEFILE_FLAG_COPY_FROM_ISO | UPDATEFILE_FLAG_OPTIONAL));
2041
2042 /* Out certificate installation utility. */
2043 /* First pass: Copy over the file (first time only) + execute it to remove any
2044 * existing VBox certificates. */
2045 GuestProcessStartupInfo siCertUtilRem;
2046 siCertUtilRem.mName = "VirtualBox Certificate Utility, removing old VirtualBox certificates";
2047 siCertUtilRem.mArguments.push_back(Utf8Str("remove-trusted-publisher"));
2048 siCertUtilRem.mArguments.push_back(Utf8Str("--root")); /* Add root certificate as well. */
2049 siCertUtilRem.mArguments.push_back(strDstCert);
2050 siCertUtilRem.mArguments.push_back(strDstCert);
2051 mFiles.push_back(InstallerFile("CERT/VBOXCERTUTIL.EXE",
2052 strUpdateDir + "VBoxCertUtil.exe",
2053 fCopyCertUtil | UPDATEFILE_FLAG_EXECUTE | UPDATEFILE_FLAG_OPTIONAL,
2054 siCertUtilRem));
2055 fCopyCertUtil = 0;
2056 /* Second pass: Only execute (but don't copy) again, this time installng the
2057 * recent certificates just copied over. */
2058 GuestProcessStartupInfo siCertUtilAdd;
2059 siCertUtilAdd.mName = "VirtualBox Certificate Utility, installing VirtualBox certificates";
2060 siCertUtilAdd.mArguments.push_back(Utf8Str("add-trusted-publisher"));
2061 siCertUtilAdd.mArguments.push_back(Utf8Str("--root")); /* Add root certificate as well. */
2062 siCertUtilAdd.mArguments.push_back(strDstCert);
2063 siCertUtilAdd.mArguments.push_back(strDstCert);
2064 mFiles.push_back(InstallerFile("CERT/VBOXCERTUTIL.EXE",
2065 strUpdateDir + "VBoxCertUtil.exe",
2066 UPDATEFILE_FLAG_EXECUTE | UPDATEFILE_FLAG_OPTIONAL,
2067 siCertUtilAdd));
2068 }
2069 }
2070 /* The installers in different flavors, as we don't know (and can't assume)
2071 * the guest's bitness. */
2072 mFiles.push_back(InstallerFile("VBOXWINDOWSADDITIONS_X86.EXE",
2073 strUpdateDir + "VBoxWindowsAdditions-x86.exe",
2074 UPDATEFILE_FLAG_COPY_FROM_ISO));
2075 mFiles.push_back(InstallerFile("VBOXWINDOWSADDITIONS_AMD64.EXE",
2076 strUpdateDir + "VBoxWindowsAdditions-amd64.exe",
2077 UPDATEFILE_FLAG_COPY_FROM_ISO));
2078 /* The stub loader which decides which flavor to run. */
2079 GuestProcessStartupInfo siInstaller;
2080 siInstaller.mName = "VirtualBox Windows Guest Additions Installer";
2081 /* Set a running timeout of 5 minutes -- the Windows Guest Additions
2082 * setup can take quite a while, so be on the safe side. */
2083 siInstaller.mTimeoutMS = 5 * 60 * 1000;
2084 siInstaller.mArguments.push_back(Utf8Str("/S")); /* We want to install in silent mode. */
2085 siInstaller.mArguments.push_back(Utf8Str("/l")); /* ... and logging enabled. */
2086 /* Don't quit VBoxService during upgrade because it still is used for this
2087 * piece of code we're in right now (that is, here!) ... */
2088 siInstaller.mArguments.push_back(Utf8Str("/no_vboxservice_exit"));
2089 /* Tell the installer to report its current installation status
2090 * using a running VBoxTray instance via balloon messages in the
2091 * Windows taskbar. */
2092 siInstaller.mArguments.push_back(Utf8Str("/post_installstatus"));
2093 /* Add optional installer command line arguments from the API to the
2094 * installer's startup info. */
2095 rc = addProcessArguments(siInstaller.mArguments, mArguments);
2096 AssertRC(rc);
2097 /* If the caller does not want to wait for out guest update process to end,
2098 * complete the progress object now so that the caller can do other work. */
2099 if (mFlags & AdditionsUpdateFlag_WaitForUpdateStartOnly)
2100 siInstaller.mFlags |= ProcessCreateFlag_WaitForProcessStartOnly;
2101 mFiles.push_back(InstallerFile("VBOXWINDOWSADDITIONS.EXE",
2102 strUpdateDir + "VBoxWindowsAdditions.exe",
2103 UPDATEFILE_FLAG_COPY_FROM_ISO | UPDATEFILE_FLAG_EXECUTE, siInstaller));
2104 break;
2105 }
2106 case eOSType_Linux:
2107 /** @todo Add Linux support. */
2108 break;
2109 case eOSType_Solaris:
2110 /** @todo Add Solaris support. */
2111 break;
2112 default:
2113 AssertReleaseMsgFailed(("Unsupported guest type: %d\n", osType));
2114 break;
2115 }
2116 }
2117
2118 if (RT_SUCCESS(rc))
2119 {
2120 /* We want to spend 40% total for all copying operations. So roughly
2121 * calculate the specific percentage step of each copied file. */
2122 uint8_t uOffset = 20; /* Start at 20%. */
2123 uint8_t uStep = 40 / (uint8_t)mFiles.size(); Assert(mFiles.size() <= 10);
2124
2125 LogRel(("Copying over Guest Additions update files to the guest ...\n"));
2126
2127 std::vector<InstallerFile>::const_iterator itFiles = mFiles.begin();
2128 while (itFiles != mFiles.end())
2129 {
2130 if (itFiles->fFlags & UPDATEFILE_FLAG_COPY_FROM_ISO)
2131 {
2132 bool fOptional = false;
2133 if (itFiles->fFlags & UPDATEFILE_FLAG_OPTIONAL)
2134 fOptional = true;
2135 rc = copyFileToGuest(pSession, &iso, itFiles->strSource, itFiles->strDest,
2136 fOptional, NULL /* cbSize */);
2137 if (RT_FAILURE(rc))
2138 {
2139 hr = setProgressErrorMsg(VBOX_E_IPRT_ERROR,
2140 Utf8StrFmt(GuestSession::tr("Error while copying file \"%s\" to \"%s\" on the guest: %Rrc"),
2141 itFiles->strSource.c_str(), itFiles->strDest.c_str(), rc));
2142 break;
2143 }
2144 }
2145
2146 rc = setProgress(uOffset);
2147 if (RT_FAILURE(rc))
2148 break;
2149 uOffset += uStep;
2150
2151 ++itFiles;
2152 }
2153 }
2154
2155 /* Done copying, close .ISO file. */
2156 RTIsoFsClose(&iso);
2157
2158 if (RT_SUCCESS(rc))
2159 {
2160 /* We want to spend 35% total for all copying operations. So roughly
2161 * calculate the specific percentage step of each copied file. */
2162 uint8_t uOffset = 60; /* Start at 60%. */
2163 uint8_t uStep = 35 / (uint8_t)mFiles.size(); Assert(mFiles.size() <= 10);
2164
2165 LogRel(("Executing Guest Additions update files ...\n"));
2166
2167 std::vector<InstallerFile>::iterator itFiles = mFiles.begin();
2168 while (itFiles != mFiles.end())
2169 {
2170 if (itFiles->fFlags & UPDATEFILE_FLAG_EXECUTE)
2171 {
2172 rc = runFileOnGuest(pSession, itFiles->mProcInfo);
2173 if (RT_FAILURE(rc))
2174 break;
2175 }
2176
2177 rc = setProgress(uOffset);
2178 if (RT_FAILURE(rc))
2179 break;
2180 uOffset += uStep;
2181
2182 ++itFiles;
2183 }
2184 }
2185
2186 if (RT_SUCCESS(rc))
2187 {
2188 LogRel(("Automatic update of Guest Additions succeeded\n"));
2189 rc = setProgressSuccess();
2190 }
2191 }
2192 }
2193
2194 if (RT_FAILURE(rc))
2195 {
2196 if (rc == VERR_CANCELLED)
2197 {
2198 LogRel(("Automatic update of Guest Additions was canceled\n"));
2199
2200 hr = setProgressErrorMsg(VBOX_E_IPRT_ERROR,
2201 Utf8StrFmt(GuestSession::tr("Installation was canceled")));
2202 }
2203 else
2204 {
2205 Utf8Str strError = Utf8StrFmt("No further error information available (%Rrc)", rc);
2206 if (!mProgress.isNull()) /* Progress object is optional. */
2207 {
2208 com::ProgressErrorInfo errorInfo(mProgress);
2209 if ( errorInfo.isFullAvailable()
2210 || errorInfo.isBasicAvailable())
2211 {
2212 strError = errorInfo.getText();
2213 }
2214 }
2215
2216 LogRel(("Automatic update of Guest Additions failed: %s (%Rhrc)\n",
2217 strError.c_str(), hr));
2218 }
2219
2220 LogRel(("Please install Guest Additions manually\n"));
2221 }
2222
2223 /** @todo Clean up copied / left over installation files. */
2224
2225 LogFlowFuncLeaveRC(rc);
2226 return rc;
2227}
2228
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