VirtualBox

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

Last change on this file since 79928 was 79418, checked in by vboxsync, 5 years ago

Main/GuestSessionTaskCopyFrom::Init: Corrected bogus error handling (mixed IPRT and COM in return). bugref:9320 bugref:9151

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 94.6 KB
Line 
1/* $Id: GuestSessionImplTasks.cpp 79418 2019-06-28 18:35:11Z vboxsync $ */
2/** @file
3 * VirtualBox Main - Guest session tasks.
4 */
5
6/*
7 * Copyright (C) 2012-2019 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 "GuestSessionImplTasks.h"
31#include "GuestCtrlImplPrivate.h"
32
33#include "Global.h"
34#include "AutoCaller.h"
35#include "ConsoleImpl.h"
36#include "ProgressImpl.h"
37
38#include <memory> /* For auto_ptr. */
39
40#include <iprt/env.h>
41#include <iprt/file.h> /* For CopyTo/From. */
42#include <iprt/dir.h>
43#include <iprt/path.h>
44#include <iprt/fsvfs.h>
45
46
47/*********************************************************************************************************************************
48* Defines *
49*********************************************************************************************************************************/
50
51/**
52 * (Guest Additions) ISO file flags.
53 * Needed for handling Guest Additions updates.
54 */
55#define ISOFILE_FLAG_NONE 0
56/** Copy over the file from host to the
57 * guest. */
58#define ISOFILE_FLAG_COPY_FROM_ISO RT_BIT(0)
59/** Execute file on the guest after it has
60 * been successfully transfered. */
61#define ISOFILE_FLAG_EXECUTE RT_BIT(7)
62/** File is optional, does not have to be
63 * existent on the .ISO. */
64#define ISOFILE_FLAG_OPTIONAL RT_BIT(8)
65
66
67// session task classes
68/////////////////////////////////////////////////////////////////////////////
69
70GuestSessionTask::GuestSessionTask(GuestSession *pSession)
71 : ThreadTask("GenericGuestSessionTask")
72{
73 mSession = pSession;
74
75 switch (mSession->i_getPathStyle())
76 {
77 case PathStyle_DOS:
78 mfPathStyle = RTPATH_STR_F_STYLE_DOS;
79 mPathStyle = "\\";
80 break;
81
82 default:
83 mfPathStyle = RTPATH_STR_F_STYLE_UNIX;
84 mPathStyle = "/";
85 break;
86 }
87}
88
89GuestSessionTask::~GuestSessionTask(void)
90{
91}
92
93int GuestSessionTask::createAndSetProgressObject(ULONG cOperations /* = 1 */)
94{
95 LogFlowThisFunc(("cOperations=%ld\n", cOperations));
96
97 /* Create the progress object. */
98 ComObjPtr<Progress> pProgress;
99 HRESULT hr = pProgress.createObject();
100 if (FAILED(hr))
101 return VERR_COM_UNEXPECTED;
102
103 hr = pProgress->init(static_cast<IGuestSession*>(mSession),
104 Bstr(mDesc).raw(),
105 TRUE /* aCancelable */, cOperations, Bstr(mDesc).raw());
106 if (FAILED(hr))
107 return VERR_COM_UNEXPECTED;
108
109 mProgress = pProgress;
110
111 LogFlowFuncLeave();
112 return VINF_SUCCESS;
113}
114
115#if 0 /* unsed */
116/** @note The task object is owned by the thread after this returns, regardless of the result. */
117int GuestSessionTask::RunAsync(const Utf8Str &strDesc, ComObjPtr<Progress> &pProgress)
118{
119 LogFlowThisFunc(("strDesc=%s\n", strDesc.c_str()));
120
121 mDesc = strDesc;
122 mProgress = pProgress;
123 HRESULT hrc = createThreadWithType(RTTHREADTYPE_MAIN_HEAVY_WORKER);
124
125 LogFlowThisFunc(("Returning hrc=%Rhrc\n", hrc));
126 return Global::vboxStatusCodeToCOM(hrc);
127}
128#endif
129
130int GuestSessionTask::getGuestProperty(const ComObjPtr<Guest> &pGuest,
131 const Utf8Str &strPath, Utf8Str &strValue)
132{
133 ComObjPtr<Console> pConsole = pGuest->i_getConsole();
134 const ComPtr<IMachine> pMachine = pConsole->i_machine();
135
136 Assert(!pMachine.isNull());
137 Bstr strTemp, strFlags;
138 LONG64 i64Timestamp;
139 HRESULT hr = pMachine->GetGuestProperty(Bstr(strPath).raw(),
140 strTemp.asOutParam(),
141 &i64Timestamp, strFlags.asOutParam());
142 if (SUCCEEDED(hr))
143 {
144 strValue = strTemp;
145 return VINF_SUCCESS;
146 }
147 return VERR_NOT_FOUND;
148}
149
150int GuestSessionTask::setProgress(ULONG uPercent)
151{
152 if (mProgress.isNull()) /* Progress is optional. */
153 return VINF_SUCCESS;
154
155 BOOL fCanceled;
156 if ( SUCCEEDED(mProgress->COMGETTER(Canceled(&fCanceled)))
157 && fCanceled)
158 return VERR_CANCELLED;
159 BOOL fCompleted;
160 if ( SUCCEEDED(mProgress->COMGETTER(Completed(&fCompleted)))
161 && fCompleted)
162 {
163 AssertMsgFailed(("Setting value of an already completed progress\n"));
164 return VINF_SUCCESS;
165 }
166 HRESULT hr = mProgress->SetCurrentOperationProgress(uPercent);
167 if (FAILED(hr))
168 return VERR_COM_UNEXPECTED;
169
170 return VINF_SUCCESS;
171}
172
173int GuestSessionTask::setProgressSuccess(void)
174{
175 if (mProgress.isNull()) /* Progress is optional. */
176 return VINF_SUCCESS;
177
178 BOOL fCompleted;
179 if ( SUCCEEDED(mProgress->COMGETTER(Completed(&fCompleted)))
180 && !fCompleted)
181 {
182#ifdef VBOX_STRICT
183 ULONG uCurOp; mProgress->COMGETTER(Operation(&uCurOp));
184 ULONG cOps; mProgress->COMGETTER(OperationCount(&cOps));
185 AssertMsg(uCurOp + 1 /* Zero-based */ == cOps, ("Not all operations done yet (%u/%u)\n", uCurOp + 1, cOps));
186#endif
187 HRESULT hr = mProgress->i_notifyComplete(S_OK);
188 if (FAILED(hr))
189 return VERR_COM_UNEXPECTED; /** @todo Find a better rc. */
190 }
191
192 return VINF_SUCCESS;
193}
194
195HRESULT GuestSessionTask::setProgressErrorMsg(HRESULT hr, const Utf8Str &strMsg)
196{
197 LogFlowFunc(("hr=%Rhrc, strMsg=%s\n",
198 hr, strMsg.c_str()));
199
200 if (mProgress.isNull()) /* Progress is optional. */
201 return hr; /* Return original rc. */
202
203 BOOL fCanceled;
204 BOOL fCompleted;
205 if ( SUCCEEDED(mProgress->COMGETTER(Canceled(&fCanceled)))
206 && !fCanceled
207 && SUCCEEDED(mProgress->COMGETTER(Completed(&fCompleted)))
208 && !fCompleted)
209 {
210#if 0 /* Had to quick fix this myself now that the test case triggers it. Please address properly as suggested below. */
211 HRESULT hr2 = mProgress->i_notifyComplete(hr,
212 COM_IIDOF(IGuestSession),
213 GuestSession::getStaticComponentName(),
214 /** @todo r=bird: i_notifyComplete takes a format string, so this is
215 * potentially risky business if a user input mentioned by the message
216 * text contains '%s'! With code below for how to do this less
217 * painfully and with fewer string copies. */
218 strMsg.c_str());
219#else
220 HRESULT hr2 = mProgress->i_notifyComplete(hr,
221 COM_IIDOF(IGuestSession),
222 GuestSession::getStaticComponentName(),
223 "%s", strMsg.c_str());
224#endif
225 if (FAILED(hr2))
226 return hr2;
227 }
228 return hr; /* Return original rc. */
229}
230
231HRESULT GuestSessionTask::setProgressErrorMsg(HRESULT hrc, int vrc, const char *pszFormat, ...)
232{
233 LogFlowFunc(("hrc=%Rhrc, vrc=%Rrc, pszFormat=%s\n", hrc, vrc, pszFormat));
234
235 /* The progress object is optional. */
236 if (!mProgress.isNull())
237 {
238 BOOL fCanceled;
239 BOOL fCompleted;
240 if ( SUCCEEDED(mProgress->COMGETTER(Canceled(&fCanceled)))
241 && !fCanceled
242 && SUCCEEDED(mProgress->COMGETTER(Completed(&fCompleted)))
243 && !fCompleted)
244 {
245 va_list va;
246 va_start(va, pszFormat);
247 HRESULT hrc2 = mProgress->i_notifyCompleteBothV(hrc, vrc, COM_IIDOF(IGuestSession),
248 GuestSession::getStaticComponentName(), pszFormat, va);
249 va_end(va);
250 if (FAILED(hrc2))
251 hrc = hrc2;
252 }
253 }
254 return hrc;
255}
256
257/**
258 * Creates a directory on the guest.
259 *
260 * @return VBox status code. VERR_ALREADY_EXISTS if directory on the guest already exists.
261 * @param strPath Absolute path to directory on the guest (guest style path) to create.
262 * @param enmDirectoryCreateFlags Directory creation flags.
263 * @param fMode Directory mode to use for creation.
264 * @param fFollowSymlinks Whether to follow symlinks on the guest or not.
265 * @param fCanExist Whether the directory to create is allowed to exist already.
266 */
267int GuestSessionTask::directoryCreateOnGuest(const com::Utf8Str &strPath,
268 DirectoryCreateFlag_T enmDirectoryCreateFlags, uint32_t fMode,
269 bool fFollowSymlinks, bool fCanExist)
270{
271 LogFlowFunc(("strPath=%s, enmDirectoryCreateFlags=0x%x, fMode=%RU32, fFollowSymlinks=%RTbool, fCanExist=%RTbool\n",
272 strPath.c_str(), enmDirectoryCreateFlags, fMode, fFollowSymlinks, fCanExist));
273
274 GuestFsObjData objData;
275 int rcGuest = VERR_IPE_UNINITIALIZED_STATUS;
276 int rc = mSession->i_directoryQueryInfo(strPath, fFollowSymlinks, objData, &rcGuest);
277 if (RT_SUCCESS(rc))
278 {
279 if (!fCanExist)
280 {
281 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
282 Utf8StrFmt(GuestSession::tr("Guest directory \"%s\" already exists"), strPath.c_str()));
283 return VERR_ALREADY_EXISTS;
284 }
285 }
286 else
287 {
288 switch (rc)
289 {
290 case VERR_GSTCTL_GUEST_ERROR:
291 {
292 switch (rcGuest)
293 {
294 case VERR_FILE_NOT_FOUND:
295 case VERR_PATH_NOT_FOUND:
296 rc = mSession->i_directoryCreate(strPath.c_str(), fMode, enmDirectoryCreateFlags, &rcGuest);
297 break;
298 default:
299 break;
300 }
301 break;
302 }
303
304 default:
305 break;
306 }
307 }
308
309 if (RT_FAILURE(rc))
310 {
311 if (rc == VERR_GSTCTL_GUEST_ERROR)
312 {
313 setProgressErrorMsg(VBOX_E_IPRT_ERROR, GuestProcess::i_guestErrorToString(rcGuest));
314 }
315 else
316 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
317 Utf8StrFmt(GuestSession::tr("Error creating directory on the guest: %Rrc"), strPath.c_str(), rc));
318 }
319
320 LogFlowFuncLeaveRC(rc);
321 return rc;
322}
323
324/**
325 * Creates a directory on the host.
326 *
327 * @return VBox status code. VERR_ALREADY_EXISTS if directory on the guest already exists.
328 * @param strPath Absolute path to directory on the host (host style path) to create.
329 * @param fCreate Directory creation flags.
330 * @param fMode Directory mode to use for creation.
331 * @param fCanExist Whether the directory to create is allowed to exist already.
332 */
333int GuestSessionTask::directoryCreateOnHost(const com::Utf8Str &strPath, uint32_t fCreate, uint32_t fMode, bool fCanExist)
334{
335 LogFlowFunc(("strPath=%s, fCreate=0x%x, fMode=%RU32, fCanExist=%RTbool\n", strPath.c_str(), fCreate, fMode, fCanExist));
336
337 int rc = RTDirCreate(strPath.c_str(), fMode, fCreate);
338 if (RT_FAILURE(rc))
339 {
340 if (rc == VERR_ALREADY_EXISTS)
341 {
342 if (!fCanExist)
343 {
344 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
345 Utf8StrFmt(GuestSession::tr("Host directory \"%s\" already exists"), strPath.c_str()));
346 }
347 else
348 rc = VINF_SUCCESS;
349 }
350 else
351 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
352 Utf8StrFmt(GuestSession::tr("Could not create host directory \"%s\": %Rrc"),
353 strPath.c_str(), rc));
354 }
355
356 LogFlowFuncLeaveRC(rc);
357 return rc;
358}
359
360/**
361 * Main function for copying a file from guest to the host.
362 *
363 * @return VBox status code.
364 * @param srcFile Guest file (source) to copy to the host. Must be in opened and ready state already.
365 * @param phDstFile Pointer to host file handle (destination) to copy to. Must be in opened and ready state already.
366 * @param fFileCopyFlags File copy flags.
367 * @param offCopy Offset (in bytes) where to start copying the source file.
368 * @param cbSize Size (in bytes) to copy from the source file.
369 */
370int GuestSessionTask::fileCopyFromGuestInner(ComObjPtr<GuestFile> &srcFile, PRTFILE phDstFile, FileCopyFlag_T fFileCopyFlags,
371 uint64_t offCopy, uint64_t cbSize)
372{
373 RT_NOREF(fFileCopyFlags);
374
375 BOOL fCanceled = FALSE;
376 uint64_t cbWrittenTotal = 0;
377 uint64_t cbToRead = cbSize;
378
379 uint32_t uTimeoutMs = 30 * 1000; /* 30s timeout. */
380
381 int rc = VINF_SUCCESS;
382
383 if (offCopy)
384 {
385 uint64_t offActual;
386 rc = srcFile->i_seekAt(offCopy, GUEST_FILE_SEEKTYPE_BEGIN, uTimeoutMs, &offActual);
387 if (RT_FAILURE(rc))
388 {
389 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
390 Utf8StrFmt(GuestSession::tr("Seeking to offset %RU64 failed: %Rrc"), offCopy, rc));
391 return rc;
392 }
393 }
394
395 BYTE byBuf[_64K];
396 while (cbToRead)
397 {
398 uint32_t cbRead;
399 const uint32_t cbChunk = RT_MIN(cbToRead, sizeof(byBuf));
400 rc = srcFile->i_readData(cbChunk, uTimeoutMs, byBuf, sizeof(byBuf), &cbRead);
401 if (RT_FAILURE(rc))
402 {
403 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
404 Utf8StrFmt(GuestSession::tr("Reading %RU32 bytes @ %RU64 from guest failed: %Rrc"), cbChunk, cbWrittenTotal, rc));
405 break;
406 }
407
408 rc = RTFileWrite(*phDstFile, byBuf, cbRead, NULL /* No partial writes */);
409 if (RT_FAILURE(rc))
410 {
411 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
412 Utf8StrFmt(GuestSession::tr("Writing %RU32 bytes to file on host failed: %Rrc"), cbRead, rc));
413 break;
414 }
415
416 Assert(cbToRead >= cbRead);
417 cbToRead -= cbRead;
418
419 /* Update total bytes written to the guest. */
420 cbWrittenTotal += cbRead;
421 Assert(cbWrittenTotal <= cbSize);
422
423 /* Did the user cancel the operation above? */
424 if ( SUCCEEDED(mProgress->COMGETTER(Canceled(&fCanceled)))
425 && fCanceled)
426 break;
427
428 rc = setProgress((ULONG)(cbWrittenTotal / ((uint64_t)cbSize / 100.0)));
429 if (RT_FAILURE(rc))
430 break;
431 }
432
433 if ( SUCCEEDED(mProgress->COMGETTER(Canceled(&fCanceled)))
434 && fCanceled)
435 return VINF_SUCCESS;
436
437 if (RT_FAILURE(rc))
438 return rc;
439
440 /*
441 * Even if we succeeded until here make sure to check whether we really transfered
442 * everything.
443 */
444 if ( cbSize > 0
445 && cbWrittenTotal == 0)
446 {
447 /* If nothing was transfered but the file size was > 0 then "vbox_cat" wasn't able to write
448 * to the destination -> access denied. */
449 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
450 Utf8StrFmt(GuestSession::tr("Writing guest file to host failed: Access denied")));
451 rc = VERR_ACCESS_DENIED;
452 }
453 else if (cbWrittenTotal < cbSize)
454 {
455 /* If we did not copy all let the user know. */
456 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
457 Utf8StrFmt(GuestSession::tr("Copying guest file to host to failed (%RU64/%RU64 bytes transfered)"),
458 cbWrittenTotal, cbSize));
459 rc = VERR_INTERRUPTED;
460 }
461
462 LogFlowFuncLeaveRC(rc);
463 return rc;
464}
465
466/**
467 * Copies a file from the guest to the host.
468 *
469 * @return VBox status code. VINF_NO_CHANGE if file was skipped.
470 * @param strSource Full path of source file on the guest to copy.
471 * @param strDest Full destination path and file name (host style) to copy file to.
472 * @param fFileCopyFlags File copy flags.
473 */
474int GuestSessionTask::fileCopyFromGuest(const Utf8Str &strSource, const Utf8Str &strDest, FileCopyFlag_T fFileCopyFlags)
475{
476 LogFlowThisFunc(("strSource=%s, strDest=%s, enmFileCopyFlags=0x%x\n", strSource.c_str(), strDest.c_str(), fFileCopyFlags));
477
478 GuestFileOpenInfo srcOpenInfo;
479 RT_ZERO(srcOpenInfo);
480 srcOpenInfo.mFilename = strSource;
481 srcOpenInfo.mOpenAction = FileOpenAction_OpenExisting;
482 srcOpenInfo.mAccessMode = FileAccessMode_ReadOnly;
483 srcOpenInfo.mSharingMode = FileSharingMode_All; /** @todo Use _Read when implemented. */
484
485 ComObjPtr<GuestFile> srcFile;
486
487 GuestFsObjData srcObjData;
488 int rcGuest = VERR_IPE_UNINITIALIZED_STATUS;
489 int rc = mSession->i_fsQueryInfo(strSource, TRUE /* fFollowSymlinks */, srcObjData, &rcGuest);
490 if (RT_FAILURE(rc))
491 {
492 switch (rc)
493 {
494 case VERR_GSTCTL_GUEST_ERROR:
495 setProgressErrorMsg(VBOX_E_IPRT_ERROR, GuestFile::i_guestErrorToString(rcGuest));
496 break;
497
498 default:
499 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
500 Utf8StrFmt(GuestSession::tr("Source file lookup for \"%s\" failed: %Rrc"),
501 strSource.c_str(), rc));
502 break;
503 }
504 }
505 else
506 {
507 switch (srcObjData.mType)
508 {
509 case FsObjType_File:
510 break;
511
512 case FsObjType_Symlink:
513 if (!(fFileCopyFlags & FileCopyFlag_FollowLinks))
514 {
515 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
516 Utf8StrFmt(GuestSession::tr("Source file \"%s\" is a symbolic link"),
517 strSource.c_str(), rc));
518 rc = VERR_IS_A_SYMLINK;
519 }
520 break;
521
522 default:
523 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
524 Utf8StrFmt(GuestSession::tr("Source element \"%s\" is not a file"), strSource.c_str()));
525 rc = VERR_NOT_A_FILE;
526 break;
527 }
528 }
529
530 if (RT_FAILURE(rc))
531 return rc;
532
533 rc = mSession->i_fileOpen(srcOpenInfo, srcFile, &rcGuest);
534 if (RT_FAILURE(rc))
535 {
536 switch (rc)
537 {
538 case VERR_GSTCTL_GUEST_ERROR:
539 setProgressErrorMsg(VBOX_E_IPRT_ERROR, GuestFile::i_guestErrorToString(rcGuest));
540 break;
541
542 default:
543 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
544 Utf8StrFmt(GuestSession::tr("Source file \"%s\" could not be opened: %Rrc"),
545 strSource.c_str(), rc));
546 break;
547 }
548 }
549
550 if (RT_FAILURE(rc))
551 return rc;
552
553 char *pszDstFile = NULL;
554 RTFSOBJINFO dstObjInfo;
555 RT_ZERO(dstObjInfo);
556
557 bool fSkip = false; /* Whether to skip handling the file. */
558
559 if (RT_SUCCESS(rc))
560 {
561 rc = RTPathQueryInfo(strDest.c_str(), &dstObjInfo, RTFSOBJATTRADD_NOTHING);
562 if (RT_SUCCESS(rc))
563 {
564 if (fFileCopyFlags & FileCopyFlag_NoReplace)
565 {
566 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
567 Utf8StrFmt(GuestSession::tr("Destination file \"%s\" already exists"), strDest.c_str()));
568 rc = VERR_ALREADY_EXISTS;
569 }
570
571 if (fFileCopyFlags & FileCopyFlag_Update)
572 {
573 RTTIMESPEC srcModificationTimeTS;
574 RTTimeSpecSetSeconds(&srcModificationTimeTS, srcObjData.mModificationTime);
575 if (RTTimeSpecCompare(&srcModificationTimeTS, &dstObjInfo.ModificationTime) <= 0)
576 {
577 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
578 Utf8StrFmt(GuestSession::tr("Destination file \"%s\" has same or newer modification date"),
579 strDest.c_str()));
580 fSkip = true;
581 }
582 }
583 }
584 else
585 {
586 if (rc != VERR_FILE_NOT_FOUND) /* Destination file does not exist (yet)? */
587 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
588 Utf8StrFmt(GuestSession::tr("Destination file lookup for \"%s\" failed: %Rrc"),
589 strDest.c_str(), rc));
590 }
591 }
592
593 if (fSkip)
594 {
595 int rc2 = srcFile->i_closeFile(&rcGuest);
596 AssertRC(rc2);
597 return VINF_SUCCESS;
598 }
599
600 if (RT_SUCCESS(rc))
601 {
602 if (RTFS_IS_FILE(dstObjInfo.Attr.fMode))
603 {
604 if (fFileCopyFlags & FileCopyFlag_NoReplace)
605 {
606 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
607 Utf8StrFmt(GuestSession::tr("Destination file \"%s\" already exists"),
608 strDest.c_str(), rc));
609 rc = VERR_ALREADY_EXISTS;
610 }
611 else
612 pszDstFile = RTStrDup(strDest.c_str());
613 }
614 else if (RTFS_IS_DIRECTORY(dstObjInfo.Attr.fMode))
615 {
616 /* Build the final file name with destination path (on the host). */
617 char szDstPath[RTPATH_MAX];
618 RTStrPrintf2(szDstPath, sizeof(szDstPath), "%s", strDest.c_str());
619
620 if ( !strDest.endsWith("\\")
621 && !strDest.endsWith("/"))
622 RTPathAppend(szDstPath, sizeof(szDstPath), "/"); /* IPRT can handle / on all hosts. */
623
624 RTPathAppend(szDstPath, sizeof(szDstPath), RTPathFilenameEx(strSource.c_str(), mfPathStyle));
625
626 pszDstFile = RTStrDup(szDstPath);
627 }
628 else if (RTFS_IS_SYMLINK(dstObjInfo.Attr.fMode))
629 {
630 if (!(fFileCopyFlags & FileCopyFlag_FollowLinks))
631 {
632 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
633 Utf8StrFmt(GuestSession::tr("Destination file \"%s\" is a symbolic link"),
634 strDest.c_str(), rc));
635 rc = VERR_IS_A_SYMLINK;
636 }
637 else
638 pszDstFile = RTStrDup(strDest.c_str());
639 }
640 else
641 {
642 LogFlowThisFunc(("Object type %RU32 not implemented yet\n", dstObjInfo.Attr.fMode));
643 rc = VERR_NOT_IMPLEMENTED;
644 }
645 }
646 else if (rc == VERR_FILE_NOT_FOUND)
647 pszDstFile = RTStrDup(strDest.c_str());
648
649 if ( RT_SUCCESS(rc)
650 || rc == VERR_FILE_NOT_FOUND)
651 {
652 if (!pszDstFile)
653 {
654 setProgressErrorMsg(VBOX_E_IPRT_ERROR, Utf8StrFmt(GuestSession::tr("No memory to allocate destination file path")));
655 rc = VERR_NO_MEMORY;
656 }
657 else
658 {
659 RTFILE hDstFile;
660 rc = RTFileOpen(&hDstFile, pszDstFile,
661 RTFILE_O_WRITE | RTFILE_O_OPEN_CREATE | RTFILE_O_DENY_WRITE); /** @todo Use the correct open modes! */
662 if (RT_SUCCESS(rc))
663 {
664 LogFlowThisFunc(("Copying '%s' to '%s' (%RI64 bytes) ...\n", strSource.c_str(), pszDstFile, srcObjData.mObjectSize));
665
666 rc = fileCopyFromGuestInner(srcFile, &hDstFile, fFileCopyFlags, 0 /* Offset, unused */, (uint64_t)srcObjData.mObjectSize);
667
668 int rc2 = RTFileClose(hDstFile);
669 AssertRC(rc2);
670 }
671 else
672 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
673 Utf8StrFmt(GuestSession::tr("Opening/creating destination file \"%s\" failed: %Rrc"),
674 pszDstFile, rc));
675 }
676 }
677
678 RTStrFree(pszDstFile);
679
680 int rc2 = srcFile->i_closeFile(&rcGuest);
681 AssertRC(rc2);
682
683 LogFlowFuncLeaveRC(rc);
684 return rc;
685}
686
687/**
688 * Main function for copying a file from host to the guest.
689 *
690 * @return VBox status code.
691 * @param hVfsFile The VFS file handle to read from.
692 * @param dstFile Guest file (destination) to copy to the guest. Must be in opened and ready state already.
693 * @param fFileCopyFlags File copy flags.
694 * @param offCopy Offset (in bytes) where to start copying the source file.
695 * @param cbSize Size (in bytes) to copy from the source file.
696 */
697int GuestSessionTask::fileCopyToGuestInner(RTVFSFILE hVfsFile, ComObjPtr<GuestFile> &dstFile, FileCopyFlag_T fFileCopyFlags,
698 uint64_t offCopy, uint64_t cbSize)
699{
700 RT_NOREF(fFileCopyFlags);
701
702 BOOL fCanceled = FALSE;
703 uint64_t cbWrittenTotal = 0;
704 uint64_t cbToRead = cbSize;
705
706 uint32_t uTimeoutMs = 30 * 1000; /* 30s timeout. */
707
708 int rc = VINF_SUCCESS;
709
710 if (offCopy)
711 {
712 uint64_t offActual;
713 rc = RTVfsFileSeek(hVfsFile, offCopy, RTFILE_SEEK_END, &offActual);
714 if (RT_FAILURE(rc))
715 {
716 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
717 Utf8StrFmt(GuestSession::tr("Seeking to offset %RU64 failed: %Rrc"), offCopy, rc));
718 return rc;
719 }
720 }
721
722 BYTE byBuf[_64K];
723 while (cbToRead)
724 {
725 size_t cbRead;
726 const uint32_t cbChunk = RT_MIN(cbToRead, sizeof(byBuf));
727 rc = RTVfsFileRead(hVfsFile, byBuf, cbChunk, &cbRead);
728 if (RT_FAILURE(rc))
729 {
730 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
731 Utf8StrFmt(GuestSession::tr("Reading %RU32 bytes @ %RU64 from host failed: %Rrc"), cbChunk, cbWrittenTotal, rc));
732 break;
733 }
734
735 rc = dstFile->i_writeData(uTimeoutMs, byBuf, (uint32_t)cbRead, NULL /* No partial writes */);
736 if (RT_FAILURE(rc))
737 {
738 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
739 Utf8StrFmt(GuestSession::tr("Writing %zu bytes to file on guest failed: %Rrc"), cbRead, rc));
740 break;
741 }
742
743 Assert(cbToRead >= cbRead);
744 cbToRead -= cbRead;
745
746 /* Update total bytes written to the guest. */
747 cbWrittenTotal += cbRead;
748 Assert(cbWrittenTotal <= cbSize);
749
750 /* Did the user cancel the operation above? */
751 if ( SUCCEEDED(mProgress->COMGETTER(Canceled(&fCanceled)))
752 && fCanceled)
753 break;
754
755 rc = setProgress((ULONG)(cbWrittenTotal / ((uint64_t)cbSize / 100.0)));
756 if (RT_FAILURE(rc))
757 break;
758 }
759
760 if (RT_FAILURE(rc))
761 return rc;
762
763 /*
764 * Even if we succeeded until here make sure to check whether we really transfered
765 * everything.
766 */
767 if ( cbSize > 0
768 && cbWrittenTotal == 0)
769 {
770 /* If nothing was transfered but the file size was > 0 then "vbox_cat" wasn't able to write
771 * to the destination -> access denied. */
772 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
773 Utf8StrFmt(GuestSession::tr("Writing to destination file failed: Access denied")));
774 rc = VERR_ACCESS_DENIED;
775 }
776 else if (cbWrittenTotal < cbSize)
777 {
778 /* If we did not copy all let the user know. */
779 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
780 Utf8StrFmt(GuestSession::tr("Copying to destination failed (%RU64/%RU64 bytes transfered)"),
781 cbWrittenTotal, cbSize));
782 rc = VERR_INTERRUPTED;
783 }
784
785 LogFlowFuncLeaveRC(rc);
786 return rc;
787}
788
789/**
790 * Copies a file from the guest to the host.
791 *
792 * @return VBox status code. VINF_NO_CHANGE if file was skipped.
793 * @param strSource Full path of source file on the host to copy.
794 * @param strDest Full destination path and file name (guest style) to copy file to.
795 * @param fFileCopyFlags File copy flags.
796 */
797int GuestSessionTask::fileCopyToGuest(const Utf8Str &strSource, const Utf8Str &strDest, FileCopyFlag_T fFileCopyFlags)
798{
799 LogFlowThisFunc(("strSource=%s, strDest=%s, fFileCopyFlags=0x%x\n", strSource.c_str(), strDest.c_str(), fFileCopyFlags));
800
801 Utf8Str strDestFinal = strDest;
802
803 GuestFsObjData dstObjData;
804 int rcGuest = VERR_IPE_UNINITIALIZED_STATUS;
805 int rc = mSession->i_fsQueryInfo(strDest, TRUE /* fFollowSymlinks */, dstObjData, &rcGuest);
806 if (rc == VERR_GSTCTL_GUEST_ERROR && rcGuest == VERR_FILE_NOT_FOUND) /* File might not exist on the guest yet. */
807 rc = VINF_SUCCESS;
808 else if (RT_FAILURE(rc))
809 {
810 setProgressErrorMsg(VBOX_E_IPRT_ERROR, rc == VERR_GSTCTL_GUEST_ERROR ? rcGuest : rc,
811 GuestSession::tr("Destination file lookup for \"%s\" failed: %Rrc"),
812 strDest.c_str(), rc == VERR_GSTCTL_GUEST_ERROR ? rcGuest : rc);
813 return rc;
814 }
815 else
816 {
817 switch (dstObjData.mType)
818 {
819 case FsObjType_Directory:
820 {
821 /* Build the final file name with destination path (on the host). */
822 char szDstPath[RTPATH_MAX];
823 /** @todo r=bird: WTF IS THIS SUPPOSED TO BE?!? Use RTStrCopy, memcpy, or similar!
824 * Ever thought about modifying strDestFinal (it's 'Dst' not 'Dest' btw.)
825 * directly? There are any number of append and insert methods in the
826 * RTCString/Utf8Str class for doing that! */
827 RTStrPrintf2(szDstPath, sizeof(szDstPath), "%s", strDest.c_str());
828
829 /** @todo r=bird: You're totally ignoring the guest slash-style here! Callers
830 * should have this info. */
831 if ( !strDest.endsWith("\\")
832 && !strDest.endsWith("/"))
833 RTStrCat(szDstPath, sizeof(szDstPath), "/");
834
835 RTStrCat(szDstPath, sizeof(szDstPath), RTPathFilename(strSource.c_str()));
836
837 strDestFinal = szDstPath;
838 break;
839 }
840
841 case FsObjType_File:
842 if (fFileCopyFlags & FileCopyFlag_NoReplace)
843 {
844 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
845 Utf8StrFmt(GuestSession::tr("Destination file \"%s\" already exists"),
846 strDest.c_str(), rc));
847 rc = VERR_ALREADY_EXISTS;
848 }
849 break;
850
851 case FsObjType_Symlink:
852 if (!(fFileCopyFlags & FileCopyFlag_FollowLinks))
853 {
854 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
855 Utf8StrFmt(GuestSession::tr("Destination file \"%s\" is a symbolic link"),
856 strDest.c_str(), rc));
857 rc = VERR_IS_A_SYMLINK;
858 }
859 break;
860
861 default:
862 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
863 Utf8StrFmt(GuestSession::tr("Destination element \"%s\" not supported"), strDest.c_str()));
864 rc = VERR_NOT_SUPPORTED;
865 break;
866 }
867 }
868
869 if (RT_FAILURE(rc))
870 return rc;
871
872 GuestFileOpenInfo dstOpenInfo;
873 RT_ZERO(dstOpenInfo);
874 dstOpenInfo.mFilename = strDestFinal;
875 if (fFileCopyFlags & FileCopyFlag_NoReplace)
876 dstOpenInfo.mOpenAction = FileOpenAction_CreateNew;
877 else
878 dstOpenInfo.mOpenAction = FileOpenAction_CreateOrReplace;
879 dstOpenInfo.mAccessMode = FileAccessMode_WriteOnly;
880 dstOpenInfo.mSharingMode = FileSharingMode_All; /** @todo Use _Read when implemented. */
881
882 ComObjPtr<GuestFile> dstFile;
883 rc = mSession->i_fileOpen(dstOpenInfo, dstFile, &rcGuest);
884 if (RT_FAILURE(rc))
885 {
886 setProgressErrorMsg(VBOX_E_IPRT_ERROR, rc == VERR_GSTCTL_GUEST_ERROR ? rcGuest : rc,
887 GuestSession::tr("Destination file \"%s\" could not be opened: %Rrc"),
888 strDestFinal.c_str(), rc == VERR_GSTCTL_GUEST_ERROR ? rcGuest : rc);
889 return rc;
890 }
891
892 char szSrcReal[RTPATH_MAX];
893
894 RTFSOBJINFO srcObjInfo;
895 RT_ZERO(srcObjInfo);
896
897 bool fSkip = false; /* Whether to skip handling the file. */
898
899 if (RT_SUCCESS(rc))
900 {
901 rc = RTPathReal(strSource.c_str(), szSrcReal, sizeof(szSrcReal));
902 if (RT_FAILURE(rc))
903 {
904 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
905 Utf8StrFmt(GuestSession::tr("Source path lookup for \"%s\" failed: %Rrc"),
906 strSource.c_str(), rc));
907 }
908 else
909 {
910 rc = RTPathQueryInfo(szSrcReal, &srcObjInfo, RTFSOBJATTRADD_NOTHING);
911 if (RT_SUCCESS(rc))
912 {
913 if (fFileCopyFlags & FileCopyFlag_Update)
914 {
915 RTTIMESPEC dstModificationTimeTS;
916 RTTimeSpecSetSeconds(&dstModificationTimeTS, dstObjData.mModificationTime);
917 if (RTTimeSpecCompare(&dstModificationTimeTS, &srcObjInfo.ModificationTime) <= 0)
918 {
919 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
920 Utf8StrFmt(GuestSession::tr("Destination file \"%s\" has same or newer modification date"),
921 strDestFinal.c_str()));
922 fSkip = true;
923 }
924 }
925 }
926 else
927 {
928 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
929 Utf8StrFmt(GuestSession::tr("Source file lookup for \"%s\" failed: %Rrc"),
930 szSrcReal, rc));
931 }
932 }
933 }
934
935 if (fSkip)
936 {
937 int rc2 = dstFile->i_closeFile(&rcGuest);
938 AssertRC(rc2);
939 return VINF_SUCCESS;
940 }
941
942 if (RT_SUCCESS(rc))
943 {
944 RTVFSFILE hSrcFile;
945 rc = RTVfsFileOpenNormal(szSrcReal, RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE, &hSrcFile); /** @todo Use the correct open modes! */
946 if (RT_SUCCESS(rc))
947 {
948 LogFlowThisFunc(("Copying '%s' to '%s' (%RI64 bytes) ...\n",
949 szSrcReal, strDestFinal.c_str(), srcObjInfo.cbObject));
950
951 rc = fileCopyToGuestInner(hSrcFile, dstFile, fFileCopyFlags, 0 /* Offset, unused */, srcObjInfo.cbObject);
952
953 int rc2 = RTVfsFileRelease(hSrcFile);
954 AssertRC(rc2);
955 }
956 else
957 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
958 Utf8StrFmt(GuestSession::tr("Opening source file \"%s\" failed: %Rrc"),
959 szSrcReal, rc));
960 }
961
962 int rc2 = dstFile->i_closeFile(&rcGuest);
963 AssertRC(rc2);
964
965 LogFlowFuncLeaveRC(rc);
966 return rc;
967}
968
969/**
970 * Adds a guest file system entry to a given list.
971 *
972 * @return VBox status code.
973 * @param strFile Path to file system entry to add.
974 * @param fsObjData Guest file system information of entry to add.
975 */
976int FsList::AddEntryFromGuest(const Utf8Str &strFile, const GuestFsObjData &fsObjData)
977{
978 LogFlowFunc(("Adding '%s'\n", strFile.c_str()));
979
980 FsEntry *pEntry = NULL;
981 try
982 {
983 pEntry = new FsEntry();
984 pEntry->fMode = fsObjData.GetFileMode();
985 pEntry->strPath = strFile;
986
987 mVecEntries.push_back(pEntry);
988 }
989 catch (...)
990 {
991 if (pEntry)
992 delete pEntry;
993 return VERR_NO_MEMORY;
994 }
995
996 return VINF_SUCCESS;
997}
998
999/**
1000 * Adds a host file system entry to a given list.
1001 *
1002 * @return VBox status code.
1003 * @param strFile Path to file system entry to add.
1004 * @param pcObjInfo File system information of entry to add.
1005 */
1006int FsList::AddEntryFromHost(const Utf8Str &strFile, PCRTFSOBJINFO pcObjInfo)
1007{
1008 LogFlowFunc(("Adding '%s'\n", strFile.c_str()));
1009
1010 FsEntry *pEntry = NULL;
1011 try
1012 {
1013 pEntry = new FsEntry();
1014 pEntry->fMode = pcObjInfo->Attr.fMode & RTFS_TYPE_MASK;
1015 pEntry->strPath = strFile;
1016
1017 mVecEntries.push_back(pEntry);
1018 }
1019 catch (...)
1020 {
1021 if (pEntry)
1022 delete pEntry;
1023 return VERR_NO_MEMORY;
1024 }
1025
1026 return VINF_SUCCESS;
1027}
1028
1029FsList::FsList(const GuestSessionTask &Task)
1030 : mTask(Task)
1031{
1032}
1033
1034FsList::~FsList()
1035{
1036 Destroy();
1037}
1038
1039/**
1040 * Initializes a file list.
1041 *
1042 * @return VBox status code.
1043 * @param strSrcRootAbs Source root path (absolute) for this file list.
1044 * @param strDstRootAbs Destination root path (absolute) for this file list.
1045 * @param SourceSpec Source specification to use.
1046 */
1047int FsList::Init(const Utf8Str &strSrcRootAbs, const Utf8Str &strDstRootAbs,
1048 const GuestSessionFsSourceSpec &SourceSpec)
1049{
1050 mSrcRootAbs = strSrcRootAbs;
1051 mDstRootAbs = strDstRootAbs;
1052 mSourceSpec = SourceSpec;
1053
1054 /* If the source is a directory, make sure the path is properly terminated already. */
1055 if (mSourceSpec.enmType == FsObjType_Directory)
1056 {
1057 if ( !mSrcRootAbs.endsWith("/")
1058 && !mSrcRootAbs.endsWith("\\"))
1059 mSrcRootAbs += "/";
1060
1061 if ( !mDstRootAbs.endsWith("/")
1062 && !mDstRootAbs.endsWith("\\"))
1063 mDstRootAbs += "/";
1064 }
1065
1066 return VINF_SUCCESS;
1067}
1068
1069/**
1070 * Destroys a file list.
1071 */
1072void FsList::Destroy(void)
1073{
1074 LogFlowFuncEnter();
1075
1076 FsEntries::iterator itEntry = mVecEntries.begin();
1077 while (itEntry != mVecEntries.end())
1078 {
1079 FsEntry *pEntry = *itEntry;
1080 delete pEntry;
1081 mVecEntries.erase(itEntry);
1082 itEntry = mVecEntries.begin();
1083 }
1084
1085 Assert(mVecEntries.empty());
1086
1087 LogFlowFuncLeave();
1088}
1089
1090/**
1091 * Builds a guest file list from a given path (and optional filter).
1092 *
1093 * @return VBox status code.
1094 * @param strPath Directory on the guest to build list from.
1095 * @param strSubDir Current sub directory path; needed for recursion.
1096 * Set to an empty path.
1097 */
1098int FsList::AddDirFromGuest(const Utf8Str &strPath, const Utf8Str &strSubDir /* = "" */)
1099{
1100 Utf8Str strPathAbs = strPath;
1101 if ( !strPathAbs.endsWith("/")
1102 && !strPathAbs.endsWith("\\"))
1103 strPathAbs += "/";
1104
1105 Utf8Str strPathSub = strSubDir;
1106 if ( strPathSub.isNotEmpty()
1107 && !strPathSub.endsWith("/")
1108 && !strPathSub.endsWith("\\"))
1109 strPathSub += "/";
1110
1111 strPathAbs += strPathSub;
1112
1113 LogFlowFunc(("Entering '%s' (sub '%s')\n", strPathAbs.c_str(), strPathSub.c_str()));
1114
1115 GuestDirectoryOpenInfo dirOpenInfo;
1116 dirOpenInfo.mFilter = "";
1117 dirOpenInfo.mPath = strPathAbs;
1118 dirOpenInfo.mFlags = 0; /** @todo Handle flags? */
1119
1120 const ComObjPtr<GuestSession> &pSession = mTask.GetSession();
1121
1122 ComObjPtr <GuestDirectory> pDir;
1123 int rcGuest = VERR_IPE_UNINITIALIZED_STATUS;
1124 int rc = pSession->i_directoryOpen(dirOpenInfo, pDir, &rcGuest);
1125 if (RT_FAILURE(rc))
1126 {
1127 switch (rc)
1128 {
1129 case VERR_INVALID_PARAMETER:
1130 break;
1131
1132 case VERR_GSTCTL_GUEST_ERROR:
1133 break;
1134
1135 default:
1136 break;
1137 }
1138
1139 return rc;
1140 }
1141
1142 if (strPathSub.isNotEmpty())
1143 {
1144 GuestFsObjData fsObjData;
1145 fsObjData.mType = FsObjType_Directory;
1146
1147 rc = AddEntryFromGuest(strPathSub, fsObjData);
1148 }
1149
1150 if (RT_SUCCESS(rc))
1151 {
1152 ComObjPtr<GuestFsObjInfo> fsObjInfo;
1153 while (RT_SUCCESS(rc = pDir->i_readInternal(fsObjInfo, &rcGuest)))
1154 {
1155 FsObjType_T enmObjType = FsObjType_Unknown; /* Shut up MSC. */
1156 HRESULT hr2 = fsObjInfo->COMGETTER(Type)(&enmObjType);
1157 AssertComRC(hr2);
1158
1159 com::Bstr bstrName;
1160 hr2 = fsObjInfo->COMGETTER(Name)(bstrName.asOutParam());
1161 AssertComRC(hr2);
1162
1163 Utf8Str strEntry = strPathSub + Utf8Str(bstrName);
1164
1165 LogFlowFunc(("Entry '%s'\n", strEntry.c_str()));
1166
1167 switch (enmObjType)
1168 {
1169 case FsObjType_Directory:
1170 {
1171 if ( bstrName.equals(".")
1172 || bstrName.equals(".."))
1173 {
1174 break;
1175 }
1176
1177 if (!(mSourceSpec.Type.Dir.fRecursive))
1178 break;
1179
1180 rc = AddDirFromGuest(strPath, strEntry);
1181 break;
1182 }
1183
1184 case FsObjType_Symlink:
1185 {
1186 if (mSourceSpec.Type.Dir.fFollowSymlinks)
1187 {
1188 /** @todo Symlink handling from guest is not imlemented yet.
1189 * See IGuestSession::symlinkRead(). */
1190 LogRel2(("Guest Control: Warning: Symlink support on guest side not available, skipping \"%s\"",
1191 strEntry.c_str()));
1192 }
1193 break;
1194 }
1195
1196 case FsObjType_File:
1197 {
1198 rc = AddEntryFromGuest(strEntry, fsObjInfo->i_getData());
1199 break;
1200 }
1201
1202 default:
1203 break;
1204 }
1205 }
1206
1207 if (rc == VERR_NO_MORE_FILES) /* End of listing reached? */
1208 rc = VINF_SUCCESS;
1209 }
1210
1211 int rc2 = pDir->i_closeInternal(&rcGuest);
1212 if (RT_SUCCESS(rc))
1213 rc = rc2;
1214
1215 return rc;
1216}
1217
1218/**
1219 * Builds a host file list from a given path (and optional filter).
1220 *
1221 * @return VBox status code.
1222 * @param strPath Directory on the host to build list from.
1223 * @param strSubDir Current sub directory path; needed for recursion.
1224 * Set to an empty path.
1225 */
1226int FsList::AddDirFromHost(const Utf8Str &strPath, const Utf8Str &strSubDir)
1227{
1228 Utf8Str strPathAbs = strPath;
1229 if ( !strPathAbs.endsWith("/")
1230 && !strPathAbs.endsWith("\\"))
1231 strPathAbs += "/";
1232
1233 Utf8Str strPathSub = strSubDir;
1234 if ( strPathSub.isNotEmpty()
1235 && !strPathSub.endsWith("/")
1236 && !strPathSub.endsWith("\\"))
1237 strPathSub += "/";
1238
1239 strPathAbs += strPathSub;
1240
1241 LogFlowFunc(("Entering '%s' (sub '%s')\n", strPathAbs.c_str(), strPathSub.c_str()));
1242
1243 RTFSOBJINFO objInfo;
1244 int rc = RTPathQueryInfo(strPathAbs.c_str(), &objInfo, RTFSOBJATTRADD_NOTHING);
1245 if (RT_SUCCESS(rc))
1246 {
1247 if (RTFS_IS_DIRECTORY(objInfo.Attr.fMode))
1248 {
1249 if (strPathSub.isNotEmpty())
1250 rc = AddEntryFromHost(strPathSub, &objInfo);
1251
1252 if (RT_SUCCESS(rc))
1253 {
1254 RTDIR hDir;
1255 rc = RTDirOpen(&hDir, strPathAbs.c_str());
1256 if (RT_SUCCESS(rc))
1257 {
1258 do
1259 {
1260 /* Retrieve the next directory entry. */
1261 RTDIRENTRYEX Entry;
1262 rc = RTDirReadEx(hDir, &Entry, NULL, RTFSOBJATTRADD_NOTHING, RTPATH_F_ON_LINK);
1263 if (RT_FAILURE(rc))
1264 {
1265 if (rc == VERR_NO_MORE_FILES)
1266 rc = VINF_SUCCESS;
1267 break;
1268 }
1269
1270 Utf8Str strEntry = strPathSub + Utf8Str(Entry.szName);
1271
1272 LogFlowFunc(("Entry '%s'\n", strEntry.c_str()));
1273
1274 switch (Entry.Info.Attr.fMode & RTFS_TYPE_MASK)
1275 {
1276 case RTFS_TYPE_DIRECTORY:
1277 {
1278 /* Skip "." and ".." entries. */
1279 if (RTDirEntryExIsStdDotLink(&Entry))
1280 break;
1281
1282 if (!(mSourceSpec.Type.Dir.fRecursive))
1283 break;
1284
1285 rc = AddDirFromHost(strPath, strEntry);
1286 break;
1287 }
1288
1289 case RTFS_TYPE_FILE:
1290 {
1291 rc = AddEntryFromHost(strEntry, &Entry.Info);
1292 break;
1293 }
1294
1295 case RTFS_TYPE_SYMLINK:
1296 {
1297 if (mSourceSpec.Type.Dir.fFollowSymlinks)
1298 {
1299 Utf8Str strEntryAbs = strPathAbs + Utf8Str(Entry.szName);
1300
1301 char szPathReal[RTPATH_MAX];
1302 rc = RTPathReal(strEntryAbs.c_str(), szPathReal, sizeof(szPathReal));
1303 if (RT_SUCCESS(rc))
1304 {
1305 rc = RTPathQueryInfo(szPathReal, &objInfo, RTFSOBJATTRADD_NOTHING);
1306 if (RT_SUCCESS(rc))
1307 {
1308 LogFlowFunc(("Symlink '%s' -> '%s'\n", strEntryAbs.c_str(), szPathReal));
1309
1310 if (RTFS_IS_DIRECTORY(objInfo.Attr.fMode))
1311 {
1312 LogFlowFunc(("Symlink to directory\n"));
1313 rc = AddDirFromHost(strPath, strEntry);
1314 }
1315 else if (RTFS_IS_FILE(objInfo.Attr.fMode))
1316 {
1317 LogFlowFunc(("Symlink to file\n"));
1318 rc = AddEntryFromHost(strEntry, &objInfo);
1319 }
1320 else
1321 rc = VERR_NOT_SUPPORTED;
1322 }
1323 else
1324 LogFlowFunc(("Unable to query symlink info for '%s', rc=%Rrc\n", szPathReal, rc));
1325 }
1326 else
1327 {
1328 LogFlowFunc(("Unable to resolve symlink for '%s', rc=%Rrc\n", strPathAbs.c_str(), rc));
1329 if (rc == VERR_FILE_NOT_FOUND) /* Broken symlink, skip. */
1330 rc = VINF_SUCCESS;
1331 }
1332 }
1333 break;
1334 }
1335
1336 default:
1337 break;
1338 }
1339
1340 } while (RT_SUCCESS(rc));
1341
1342 RTDirClose(hDir);
1343 }
1344 }
1345 }
1346 else if (RTFS_IS_FILE(objInfo.Attr.fMode))
1347 {
1348 rc = VERR_IS_A_FILE;
1349 }
1350 else if (RTFS_IS_SYMLINK(objInfo.Attr.fMode))
1351 {
1352 rc = VERR_IS_A_SYMLINK;
1353 }
1354 else
1355 rc = VERR_NOT_SUPPORTED;
1356 }
1357 else
1358 LogFlowFunc(("Unable to query '%s', rc=%Rrc\n", strPathAbs.c_str(), rc));
1359
1360 LogFlowFuncLeaveRC(rc);
1361 return rc;
1362}
1363
1364GuestSessionTaskOpen::GuestSessionTaskOpen(GuestSession *pSession, uint32_t uFlags, uint32_t uTimeoutMS)
1365 : GuestSessionTask(pSession)
1366 , mFlags(uFlags)
1367 , mTimeoutMS(uTimeoutMS)
1368{
1369 m_strTaskName = "gctlSesOpen";
1370}
1371
1372GuestSessionTaskOpen::~GuestSessionTaskOpen(void)
1373{
1374
1375}
1376
1377int GuestSessionTaskOpen::Run(void)
1378{
1379 LogFlowThisFuncEnter();
1380
1381 AutoCaller autoCaller(mSession);
1382 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1383
1384 int vrc = mSession->i_startSession(NULL /*pvrcGuest*/);
1385 /* Nothing to do here anymore. */
1386
1387 LogFlowFuncLeaveRC(vrc);
1388 return vrc;
1389}
1390
1391GuestSessionCopyTask::GuestSessionCopyTask(GuestSession *pSession)
1392 : GuestSessionTask(pSession)
1393{
1394}
1395
1396GuestSessionCopyTask::~GuestSessionCopyTask()
1397{
1398 FsLists::iterator itList = mVecLists.begin();
1399 while (itList != mVecLists.end())
1400 {
1401 FsList *pFsList = (*itList);
1402 pFsList->Destroy();
1403 delete pFsList;
1404 mVecLists.erase(itList);
1405 itList = mVecLists.begin();
1406 }
1407
1408 Assert(mVecLists.empty());
1409}
1410
1411GuestSessionTaskCopyFrom::GuestSessionTaskCopyFrom(GuestSession *pSession, GuestSessionFsSourceSet const &vecSrc,
1412 const Utf8Str &strDest)
1413 : GuestSessionCopyTask(pSession)
1414{
1415 m_strTaskName = "gctlCpyFrm";
1416
1417 mSources = vecSrc;
1418 mDest = strDest;
1419}
1420
1421GuestSessionTaskCopyFrom::~GuestSessionTaskCopyFrom(void)
1422{
1423}
1424
1425HRESULT GuestSessionTaskCopyFrom::Init(const Utf8Str &strTaskDesc)
1426{
1427 setTaskDesc(strTaskDesc);
1428
1429 /* Create the progress object. */
1430 ComObjPtr<Progress> pProgress;
1431 HRESULT hrc = pProgress.createObject();
1432 if (FAILED(hrc))
1433 return hrc;
1434
1435 mProgress = pProgress;
1436
1437 int vrc = VINF_SUCCESS;
1438
1439 ULONG cOperations = 0;
1440 Utf8Str strErrorInfo;
1441
1442 /**
1443 * Note: We need to build up the file/directory here instead of GuestSessionTaskCopyFrom::Run
1444 * because the caller expects a ready-for-operation progress object on return.
1445 * The progress object will have a variable operation count, based on the elements to
1446 * be processed.
1447 */
1448
1449 GuestSessionFsSourceSet::iterator itSrc = mSources.begin();
1450 while (itSrc != mSources.end())
1451 {
1452 Utf8Str strSrc = itSrc->strSource;
1453 Utf8Str strDst = mDest;
1454
1455 bool fFollowSymlinks;
1456
1457 if (itSrc->enmType == FsObjType_Directory)
1458 {
1459 /* If the source does not end with a slash, copy over the entire directory
1460 * (and not just its contents). */
1461 /** @todo r=bird: Try get the path style stuff right and stop assuming all guest are windows guests. */
1462 if ( !strSrc.endsWith("/")
1463 && !strSrc.endsWith("\\"))
1464 {
1465 /** @todo r=bird: All hosts aren't windows either, use RTPATH_IS_SLASH() here! */
1466 if ( !strDst.endsWith("/")
1467 && !strDst.endsWith("\\"))
1468 strDst += "/";
1469
1470 /** @todo r=bird: Very unnecessary to use Utf8StrFmt(%s) here when Utf8Str()
1471 * would do perfectly. Also missing try catch. */
1472 strDst += Utf8StrFmt("%s", RTPathFilenameEx(strSrc.c_str(), mfPathStyle));
1473 }
1474
1475 fFollowSymlinks = itSrc->Type.Dir.fFollowSymlinks;
1476 }
1477 else
1478 {
1479 fFollowSymlinks = RT_BOOL(itSrc->Type.File.fCopyFlags & FileCopyFlag_FollowLinks);
1480 }
1481
1482 LogFlowFunc(("strSrc=%s, strDst=%s, fFollowSymlinks=%RTbool\n", strSrc.c_str(), strDst.c_str(), fFollowSymlinks));
1483
1484 GuestFsObjData srcObjData;
1485 int rcGuest = VERR_IPE_UNINITIALIZED_STATUS;
1486 vrc = mSession->i_fsQueryInfo(strSrc, fFollowSymlinks, srcObjData, &rcGuest);
1487 if (RT_FAILURE(vrc))
1488 {
1489 strErrorInfo = Utf8StrFmt(GuestSession::tr("No such source file/directory: %s"), strSrc.c_str());
1490 break;
1491 }
1492
1493 if (srcObjData.mType == FsObjType_Directory)
1494 {
1495 if (itSrc->enmType != FsObjType_Directory)
1496 {
1497 strErrorInfo = Utf8StrFmt(GuestSession::tr("Source is not a file: %s"), strSrc.c_str());
1498 vrc = VERR_NOT_A_FILE;
1499 break;
1500 }
1501 }
1502 else
1503 {
1504 if (itSrc->enmType != FsObjType_File)
1505 {
1506 strErrorInfo = Utf8StrFmt(GuestSession::tr("Source is not a directory: %s"), strSrc.c_str());
1507 vrc = VERR_NOT_A_DIRECTORY;
1508 break;
1509 }
1510 }
1511
1512 FsList *pFsList = NULL;
1513 try
1514 {
1515 pFsList = new FsList(*this);
1516 vrc = pFsList->Init(strSrc, strDst, *itSrc);
1517 if (RT_SUCCESS(vrc))
1518 {
1519 if (itSrc->enmType == FsObjType_Directory)
1520 vrc = pFsList->AddDirFromGuest(strSrc);
1521 else
1522 vrc = pFsList->AddEntryFromGuest(RTPathFilename(strSrc.c_str()), srcObjData);
1523 }
1524
1525 if (RT_FAILURE(vrc))
1526 {
1527 delete pFsList;
1528 strErrorInfo = Utf8StrFmt(GuestSession::tr("Error adding source '%s' to list: %Rrc"), strSrc.c_str(), vrc);
1529 break;
1530 }
1531
1532 mVecLists.push_back(pFsList);
1533 }
1534 catch (...) /** @todo r=bird: Catch std:bad_alloc &, not ... Will avoid headscratching if something is thrown. */
1535 {
1536 vrc = VERR_NO_MEMORY;
1537 break;
1538 }
1539
1540 AssertPtr(pFsList);
1541 cOperations += (ULONG)pFsList->mVecEntries.size();
1542
1543 itSrc++;
1544 }
1545
1546 if (cOperations) /* Use the first element as description (if available). */
1547 {
1548 Assert(mVecLists.size());
1549 Assert(mVecLists[0]->mVecEntries.size());
1550
1551 Utf8Str strFirstOp = mDest + mVecLists[0]->mVecEntries[0]->strPath;
1552 hrc = pProgress->init(static_cast<IGuestSession*>(mSession), Bstr(mDesc).raw(),
1553 TRUE /* aCancelable */, cOperations + 1 /* Number of operations */, Bstr(strFirstOp).raw());
1554 }
1555 else /* If no operations have been defined, go with an "empty" progress object when will be used for error handling. */
1556 hrc = pProgress->init(static_cast<IGuestSession*>(mSession), Bstr(mDesc).raw(),
1557 TRUE /* aCancelable */, 1 /* cOperations */, Bstr(mDesc).raw());
1558
1559 if (RT_FAILURE(vrc))
1560 {
1561 Assert(strErrorInfo.isNotEmpty());
1562 setProgressErrorMsg(VBOX_E_IPRT_ERROR, vrc, "%s", strErrorInfo.c_str());
1563 }
1564
1565 LogFlowFunc(("Returning %Rhrc (%Rrc)\n", hrc, vrc));
1566 return hrc;
1567}
1568
1569int GuestSessionTaskCopyFrom::Run(void)
1570{
1571 LogFlowThisFuncEnter();
1572
1573 AutoCaller autoCaller(mSession);
1574 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1575
1576 int rc = VINF_SUCCESS;
1577
1578 FsLists::const_iterator itList = mVecLists.begin();
1579 while (itList != mVecLists.end())
1580 {
1581 FsList *pList = *itList;
1582 AssertPtr(pList);
1583
1584 const bool fCopyIntoExisting = pList->mSourceSpec.Type.Dir.fCopyFlags & DirectoryCopyFlag_CopyIntoExisting;
1585 const bool fFollowSymlinks = true; /** @todo */
1586 const uint32_t fDirMode = 0700; /** @todo Play safe by default; implement ACLs. */
1587 uint32_t fDirCreate = 0;
1588
1589 if (!fFollowSymlinks)
1590 fDirCreate |= RTDIRCREATE_FLAGS_NO_SYMLINKS;
1591
1592 LogFlowFunc(("List: srcRootAbs=%s, dstRootAbs=%s\n", pList->mSrcRootAbs.c_str(), pList->mDstRootAbs.c_str()));
1593
1594 /* Create the root directory. */
1595 if ( pList->mSourceSpec.enmType == FsObjType_Directory
1596 && pList->mSourceSpec.fDryRun == false)
1597 {
1598 rc = directoryCreateOnHost(pList->mDstRootAbs, fDirCreate, fDirMode, fCopyIntoExisting);
1599 if (RT_FAILURE(rc))
1600 break;
1601 }
1602
1603 FsEntries::const_iterator itEntry = pList->mVecEntries.begin();
1604 while (itEntry != pList->mVecEntries.end())
1605 {
1606 FsEntry *pEntry = *itEntry;
1607 AssertPtr(pEntry);
1608
1609 Utf8Str strSrcAbs = pList->mSrcRootAbs;
1610 Utf8Str strDstAbs = pList->mDstRootAbs;
1611 if (pList->mSourceSpec.enmType == FsObjType_Directory)
1612 {
1613 strSrcAbs += pEntry->strPath;
1614 strDstAbs += pEntry->strPath;
1615
1616 if (pList->mSourceSpec.enmPathStyle == PathStyle_DOS)
1617 strDstAbs.findReplace('\\', '/');
1618 }
1619
1620 mProgress->SetNextOperation(Bstr(strSrcAbs).raw(), 1);
1621
1622 switch (pEntry->fMode & RTFS_TYPE_MASK)
1623 {
1624 case RTFS_TYPE_DIRECTORY:
1625 LogFlowFunc(("Directory '%s': %s -> %s\n", pEntry->strPath.c_str(), strSrcAbs.c_str(), strDstAbs.c_str()));
1626 if (!pList->mSourceSpec.fDryRun)
1627 rc = directoryCreateOnHost(strDstAbs, fDirCreate, fDirMode, fCopyIntoExisting);
1628 break;
1629
1630 case RTFS_TYPE_FILE:
1631 LogFlowFunc(("File '%s': %s -> %s\n", pEntry->strPath.c_str(), strSrcAbs.c_str(), strDstAbs.c_str()));
1632 if (!pList->mSourceSpec.fDryRun)
1633 rc = fileCopyFromGuest(strSrcAbs, strDstAbs, FileCopyFlag_None);
1634 break;
1635
1636 default:
1637 LogFlowFunc(("Warning: Type %d for '%s' is not supported\n",
1638 pEntry->fMode & RTFS_TYPE_MASK, strSrcAbs.c_str()));
1639 break;
1640 }
1641
1642 if (RT_FAILURE(rc))
1643 break;
1644
1645 ++itEntry;
1646 }
1647
1648 if (RT_FAILURE(rc))
1649 break;
1650
1651 ++itList;
1652 }
1653
1654 if (RT_SUCCESS(rc))
1655 rc = setProgressSuccess();
1656
1657 LogFlowFuncLeaveRC(rc);
1658 return rc;
1659}
1660
1661GuestSessionTaskCopyTo::GuestSessionTaskCopyTo(GuestSession *pSession, GuestSessionFsSourceSet const &vecSrc,
1662 const Utf8Str &strDest)
1663 : GuestSessionCopyTask(pSession)
1664{
1665 m_strTaskName = "gctlCpyTo";
1666
1667 mSources = vecSrc;
1668 mDest = strDest;
1669}
1670
1671GuestSessionTaskCopyTo::~GuestSessionTaskCopyTo(void)
1672{
1673}
1674
1675HRESULT GuestSessionTaskCopyTo::Init(const Utf8Str &strTaskDesc)
1676{
1677 LogFlowFuncEnter();
1678
1679 setTaskDesc(strTaskDesc);
1680
1681 /* Create the progress object. */
1682 ComObjPtr<Progress> pProgress;
1683 HRESULT hr = pProgress.createObject();
1684 if (FAILED(hr))
1685 return hr;
1686
1687 mProgress = pProgress;
1688
1689 int rc = VINF_SUCCESS;
1690
1691 ULONG cOperations = 0;
1692 Utf8Str strErrorInfo;
1693
1694 /**
1695 * Note: We need to build up the file/directory here instead of GuestSessionTaskCopyTo::Run
1696 * because the caller expects a ready-for-operation progress object on return.
1697 * The progress object will have a variable operation count, based on the elements to
1698 * be processed.
1699 */
1700
1701 GuestSessionFsSourceSet::iterator itSrc = mSources.begin();
1702 while (itSrc != mSources.end())
1703 {
1704 Utf8Str strSrc = itSrc->strSource;
1705 Utf8Str strDst = mDest;
1706
1707 if (itSrc->enmType == FsObjType_Directory)
1708 {
1709 /* If the source does not end with a slash, copy over the entire directory
1710 * (and not just its contents). */
1711 if ( !strSrc.endsWith("/")
1712 && !strSrc.endsWith("\\"))
1713 {
1714 if ( !strDst.endsWith("/")
1715 && !strDst.endsWith("\\"))
1716 strDst += "/";
1717
1718 strDst += Utf8StrFmt("%s", RTPathFilenameEx(strSrc.c_str(), mfPathStyle));
1719 }
1720 }
1721
1722 LogFlowFunc(("strSrc=%s, strDst=%s\n", strSrc.c_str(), strDst.c_str()));
1723
1724 RTFSOBJINFO srcFsObjInfo;
1725 rc = RTPathQueryInfo(strSrc.c_str(), &srcFsObjInfo, RTFSOBJATTRADD_NOTHING);
1726 if (RT_FAILURE(rc))
1727 {
1728 strErrorInfo = Utf8StrFmt(GuestSession::tr("No such source file/directory: %s"), strSrc.c_str());
1729 break;
1730 }
1731
1732 if (RTFS_IS_DIRECTORY(srcFsObjInfo.Attr.fMode))
1733 {
1734 if (itSrc->enmType != FsObjType_Directory)
1735 {
1736 strErrorInfo = Utf8StrFmt(GuestSession::tr("Source is not a file: %s"), strSrc.c_str());
1737 rc = VERR_NOT_A_FILE;
1738 break;
1739 }
1740 }
1741 else
1742 {
1743 if (itSrc->enmType == FsObjType_Directory)
1744 {
1745 strErrorInfo = Utf8StrFmt(GuestSession::tr("Source is not a directory: %s"), strSrc.c_str());
1746 rc = VERR_NOT_A_DIRECTORY;
1747 break;
1748 }
1749 }
1750
1751 FsList *pFsList = NULL;
1752 try
1753 {
1754 pFsList = new FsList(*this);
1755 rc = pFsList->Init(strSrc, strDst, *itSrc);
1756 if (RT_SUCCESS(rc))
1757 {
1758 if (itSrc->enmType == FsObjType_Directory)
1759 {
1760 rc = pFsList->AddDirFromHost(strSrc);
1761 }
1762 else
1763 rc = pFsList->AddEntryFromHost(RTPathFilename(strSrc.c_str()), &srcFsObjInfo);
1764 }
1765
1766 if (RT_FAILURE(rc))
1767 {
1768 delete pFsList;
1769 strErrorInfo = Utf8StrFmt(GuestSession::tr("Error adding source '%s' to list: %Rrc"), strSrc.c_str(), rc);
1770 break;
1771 }
1772
1773 mVecLists.push_back(pFsList);
1774 }
1775 catch (...)
1776 {
1777 rc = VERR_NO_MEMORY;
1778 break;
1779 }
1780
1781 AssertPtr(pFsList);
1782 cOperations += (ULONG)pFsList->mVecEntries.size();
1783
1784 itSrc++;
1785 }
1786
1787 if (cOperations) /* Use the first element as description (if available). */
1788 {
1789 Assert(mVecLists.size());
1790 Assert(mVecLists[0]->mVecEntries.size());
1791
1792 hr = pProgress->init(static_cast<IGuestSession*>(mSession), Bstr(mDesc).raw(),
1793 TRUE /* aCancelable */, cOperations + 1 /* Number of operations */,
1794 Bstr(mDesc).raw());
1795 }
1796 else /* If no operations have been defined, go with an "empty" progress object when will be used for error handling. */
1797 hr = pProgress->init(static_cast<IGuestSession*>(mSession), Bstr(mDesc).raw(),
1798 TRUE /* aCancelable */, 1 /* cOperations */, Bstr(mDesc).raw());
1799
1800 if (RT_FAILURE(rc))
1801 {
1802 Assert(strErrorInfo.isNotEmpty());
1803 setProgressErrorMsg(VBOX_E_IPRT_ERROR, strErrorInfo);
1804 }
1805
1806 LogFlowFunc(("Returning %Rhrc (%Rrc)\n", hr, rc));
1807 return hr;
1808}
1809
1810int GuestSessionTaskCopyTo::Run(void)
1811{
1812 LogFlowThisFuncEnter();
1813
1814 AutoCaller autoCaller(mSession);
1815 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1816
1817 int rc = VINF_SUCCESS;
1818
1819 FsLists::const_iterator itList = mVecLists.begin();
1820 while (itList != mVecLists.end())
1821 {
1822 FsList *pList = *itList;
1823 AssertPtr(pList);
1824
1825 bool fCopyIntoExisting = false;
1826 bool fFollowSymlinks = false;
1827 uint32_t fDirMode = 0700; /** @todo Play safe by default; implement ACLs. */
1828
1829 LogFlowFunc(("List: srcRootAbs=%s, dstRootAbs=%s\n", pList->mSrcRootAbs.c_str(), pList->mDstRootAbs.c_str()));
1830
1831 /* Create the root directory. */
1832 if (pList->mSourceSpec.enmType == FsObjType_Directory)
1833 {
1834 fCopyIntoExisting = RT_BOOL(pList->mSourceSpec.Type.Dir.fCopyFlags & DirectoryCopyFlag_CopyIntoExisting);
1835 fFollowSymlinks = pList->mSourceSpec.Type.Dir.fFollowSymlinks;
1836
1837 if (pList->mSourceSpec.fDryRun == false)
1838 {
1839 rc = directoryCreateOnGuest(pList->mDstRootAbs, DirectoryCreateFlag_None, fDirMode,
1840 fFollowSymlinks, fCopyIntoExisting);
1841 if (RT_FAILURE(rc))
1842 break;
1843 }
1844 }
1845 else if (pList->mSourceSpec.enmType == FsObjType_File)
1846 {
1847 fCopyIntoExisting = !(pList->mSourceSpec.Type.File.fCopyFlags & FileCopyFlag_NoReplace);
1848 fFollowSymlinks = RT_BOOL(pList->mSourceSpec.Type.File.fCopyFlags & FileCopyFlag_FollowLinks);
1849 }
1850 else
1851 AssertFailed();
1852
1853 FsEntries::const_iterator itEntry = pList->mVecEntries.begin();
1854 while (itEntry != pList->mVecEntries.end())
1855 {
1856 FsEntry *pEntry = *itEntry;
1857 AssertPtr(pEntry);
1858
1859 Utf8Str strSrcAbs = pList->mSrcRootAbs;
1860 Utf8Str strDstAbs = pList->mDstRootAbs;
1861 if (pList->mSourceSpec.enmType == FsObjType_Directory)
1862 {
1863 strSrcAbs += pEntry->strPath;
1864 strDstAbs += pEntry->strPath;
1865 }
1866
1867 mProgress->SetNextOperation(Bstr(strSrcAbs).raw(), 1);
1868
1869 switch (pEntry->fMode & RTFS_TYPE_MASK)
1870 {
1871 case RTFS_TYPE_DIRECTORY:
1872 LogFlowFunc(("Directory '%s': %s -> %s\n", pEntry->strPath.c_str(), strSrcAbs.c_str(), strDstAbs.c_str()));
1873 if (!pList->mSourceSpec.fDryRun)
1874 {
1875 rc = directoryCreateOnGuest(strDstAbs, DirectoryCreateFlag_None, fDirMode,
1876 fFollowSymlinks, fCopyIntoExisting);
1877 if (RT_FAILURE(rc))
1878 break;
1879 }
1880 break;
1881
1882 case RTFS_TYPE_FILE:
1883 LogFlowFunc(("File '%s': %s -> %s\n", pEntry->strPath.c_str(), strSrcAbs.c_str(), strDstAbs.c_str()));
1884 if (!pList->mSourceSpec.fDryRun)
1885 rc = fileCopyToGuest(strSrcAbs, strDstAbs, pList->mSourceSpec.Type.File.fCopyFlags);
1886 break;
1887
1888 default:
1889 LogFlowFunc(("Warning: Type %d for '%s' is not supported\n",
1890 pEntry->fMode & RTFS_TYPE_MASK, strSrcAbs.c_str()));
1891 break;
1892 }
1893
1894 if (RT_FAILURE(rc))
1895 break;
1896
1897 ++itEntry;
1898 }
1899
1900 if (RT_FAILURE(rc))
1901 break;
1902
1903 ++itList;
1904 }
1905
1906 if (RT_SUCCESS(rc))
1907 rc = setProgressSuccess();
1908
1909 LogFlowFuncLeaveRC(rc);
1910 return rc;
1911}
1912
1913GuestSessionTaskUpdateAdditions::GuestSessionTaskUpdateAdditions(GuestSession *pSession,
1914 const Utf8Str &strSource,
1915 const ProcessArguments &aArguments,
1916 uint32_t fFlags)
1917 : GuestSessionTask(pSession)
1918{
1919 m_strTaskName = "gctlUpGA";
1920
1921 mSource = strSource;
1922 mArguments = aArguments;
1923 mFlags = fFlags;
1924}
1925
1926GuestSessionTaskUpdateAdditions::~GuestSessionTaskUpdateAdditions(void)
1927{
1928
1929}
1930
1931int GuestSessionTaskUpdateAdditions::addProcessArguments(ProcessArguments &aArgumentsDest, const ProcessArguments &aArgumentsSource)
1932{
1933 int rc = VINF_SUCCESS;
1934
1935 try
1936 {
1937 /* Filter out arguments which already are in the destination to
1938 * not end up having them specified twice. Not the fastest method on the
1939 * planet but does the job. */
1940 ProcessArguments::const_iterator itSource = aArgumentsSource.begin();
1941 while (itSource != aArgumentsSource.end())
1942 {
1943 bool fFound = false;
1944 ProcessArguments::iterator itDest = aArgumentsDest.begin();
1945 while (itDest != aArgumentsDest.end())
1946 {
1947 if ((*itDest).equalsIgnoreCase((*itSource)))
1948 {
1949 fFound = true;
1950 break;
1951 }
1952 ++itDest;
1953 }
1954
1955 if (!fFound)
1956 aArgumentsDest.push_back((*itSource));
1957
1958 ++itSource;
1959 }
1960 }
1961 catch(std::bad_alloc &)
1962 {
1963 return VERR_NO_MEMORY;
1964 }
1965
1966 return rc;
1967}
1968
1969int GuestSessionTaskUpdateAdditions::copyFileToGuest(GuestSession *pSession, RTVFS hVfsIso,
1970 Utf8Str const &strFileSource, const Utf8Str &strFileDest,
1971 bool fOptional)
1972{
1973 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1974 AssertReturn(hVfsIso != NIL_RTVFS, VERR_INVALID_POINTER);
1975
1976 RTVFSFILE hVfsFile = NIL_RTVFSFILE;
1977 int rc = RTVfsFileOpen(hVfsIso, strFileSource.c_str(), RTFILE_O_OPEN | RTFILE_O_READ, &hVfsFile);
1978 if (RT_SUCCESS(rc))
1979 {
1980 uint64_t cbSrcSize = 0;
1981 rc = RTVfsFileGetSize(hVfsFile, &cbSrcSize);
1982 if (RT_SUCCESS(rc))
1983 {
1984 LogRel(("Copying Guest Additions installer file \"%s\" to \"%s\" on guest ...\n",
1985 strFileSource.c_str(), strFileDest.c_str()));
1986
1987 GuestFileOpenInfo dstOpenInfo;
1988 RT_ZERO(dstOpenInfo);
1989 dstOpenInfo.mFilename = strFileDest;
1990 dstOpenInfo.mOpenAction = FileOpenAction_CreateOrReplace;
1991 dstOpenInfo.mAccessMode = FileAccessMode_WriteOnly;
1992 dstOpenInfo.mSharingMode = FileSharingMode_All; /** @todo Use _Read when implemented. */
1993
1994 ComObjPtr<GuestFile> dstFile;
1995 int rcGuest = VERR_IPE_UNINITIALIZED_STATUS;
1996 rc = mSession->i_fileOpen(dstOpenInfo, dstFile, &rcGuest);
1997 if (RT_FAILURE(rc))
1998 {
1999 switch (rc)
2000 {
2001 case VERR_GSTCTL_GUEST_ERROR:
2002 setProgressErrorMsg(VBOX_E_IPRT_ERROR, GuestFile::i_guestErrorToString(rcGuest));
2003 break;
2004
2005 default:
2006 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
2007 Utf8StrFmt(GuestSession::tr("Destination file \"%s\" could not be opened: %Rrc"),
2008 strFileDest.c_str(), rc));
2009 break;
2010 }
2011 }
2012 else
2013 {
2014 rc = fileCopyToGuestInner(hVfsFile, dstFile, FileCopyFlag_None, 0 /*cbOffset*/, cbSrcSize);
2015
2016 int rc2 = dstFile->i_closeFile(&rcGuest);
2017 AssertRC(rc2);
2018 }
2019 }
2020
2021 RTVfsFileRelease(hVfsFile);
2022 if (RT_FAILURE(rc))
2023 return rc;
2024 }
2025 else
2026 {
2027 if (fOptional)
2028 return VINF_SUCCESS;
2029
2030 return rc;
2031 }
2032
2033 return rc;
2034}
2035
2036int GuestSessionTaskUpdateAdditions::runFileOnGuest(GuestSession *pSession, GuestProcessStartupInfo &procInfo)
2037{
2038 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
2039
2040 LogRel(("Running %s ...\n", procInfo.mName.c_str()));
2041
2042 GuestProcessTool procTool;
2043 int rcGuest = VERR_IPE_UNINITIALIZED_STATUS;
2044 int vrc = procTool.init(pSession, procInfo, false /* Async */, &rcGuest);
2045 if (RT_SUCCESS(vrc))
2046 {
2047 if (RT_SUCCESS(rcGuest))
2048 vrc = procTool.wait(GUESTPROCESSTOOL_WAIT_FLAG_NONE, &rcGuest);
2049 if (RT_SUCCESS(vrc))
2050 vrc = procTool.getTerminationStatus();
2051 }
2052
2053 if (RT_FAILURE(vrc))
2054 {
2055 switch (vrc)
2056 {
2057 case VERR_GSTCTL_PROCESS_EXIT_CODE:
2058 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
2059 Utf8StrFmt(GuestSession::tr("Running update file \"%s\" on guest failed: %Rrc"),
2060 procInfo.mExecutable.c_str(), procTool.getRc()));
2061 break;
2062
2063 case VERR_GSTCTL_GUEST_ERROR:
2064 setProgressErrorMsg(VBOX_E_IPRT_ERROR, GuestProcess::i_guestErrorToString(rcGuest));
2065 break;
2066
2067 case VERR_INVALID_STATE: /** @todo Special guest control rc needed! */
2068 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
2069 Utf8StrFmt(GuestSession::tr("Update file \"%s\" reported invalid running state"),
2070 procInfo.mExecutable.c_str()));
2071 break;
2072
2073 default:
2074 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
2075 Utf8StrFmt(GuestSession::tr("Error while running update file \"%s\" on guest: %Rrc"),
2076 procInfo.mExecutable.c_str(), vrc));
2077 break;
2078 }
2079 }
2080
2081 return vrc;
2082}
2083
2084int GuestSessionTaskUpdateAdditions::Run(void)
2085{
2086 LogFlowThisFuncEnter();
2087
2088 ComObjPtr<GuestSession> pSession = mSession;
2089 Assert(!pSession.isNull());
2090
2091 AutoCaller autoCaller(pSession);
2092 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2093
2094 int rc = setProgress(10);
2095 if (RT_FAILURE(rc))
2096 return rc;
2097
2098 HRESULT hr = S_OK;
2099
2100 LogRel(("Automatic update of Guest Additions started, using \"%s\"\n", mSource.c_str()));
2101
2102 ComObjPtr<Guest> pGuest(mSession->i_getParent());
2103#if 0
2104 /*
2105 * Wait for the guest being ready within 30 seconds.
2106 */
2107 AdditionsRunLevelType_T addsRunLevel;
2108 uint64_t tsStart = RTTimeSystemMilliTS();
2109 while ( SUCCEEDED(hr = pGuest->COMGETTER(AdditionsRunLevel)(&addsRunLevel))
2110 && ( addsRunLevel != AdditionsRunLevelType_Userland
2111 && addsRunLevel != AdditionsRunLevelType_Desktop))
2112 {
2113 if ((RTTimeSystemMilliTS() - tsStart) > 30 * 1000)
2114 {
2115 rc = VERR_TIMEOUT;
2116 break;
2117 }
2118
2119 RTThreadSleep(100); /* Wait a bit. */
2120 }
2121
2122 if (FAILED(hr)) rc = VERR_TIMEOUT;
2123 if (rc == VERR_TIMEOUT)
2124 hr = setProgressErrorMsg(VBOX_E_NOT_SUPPORTED,
2125 Utf8StrFmt(GuestSession::tr("Guest Additions were not ready within time, giving up")));
2126#else
2127 /*
2128 * For use with the GUI we don't want to wait, just return so that the manual .ISO mounting
2129 * can continue.
2130 */
2131 AdditionsRunLevelType_T addsRunLevel;
2132 if ( FAILED(hr = pGuest->COMGETTER(AdditionsRunLevel)(&addsRunLevel))
2133 || ( addsRunLevel != AdditionsRunLevelType_Userland
2134 && addsRunLevel != AdditionsRunLevelType_Desktop))
2135 {
2136 if (addsRunLevel == AdditionsRunLevelType_System)
2137 hr = setProgressErrorMsg(VBOX_E_NOT_SUPPORTED,
2138 Utf8StrFmt(GuestSession::tr("Guest Additions are installed but not fully loaded yet, aborting automatic update")));
2139 else
2140 hr = setProgressErrorMsg(VBOX_E_NOT_SUPPORTED,
2141 Utf8StrFmt(GuestSession::tr("Guest Additions not installed or ready, aborting automatic update")));
2142 rc = VERR_NOT_SUPPORTED;
2143 }
2144#endif
2145
2146 if (RT_SUCCESS(rc))
2147 {
2148 /*
2149 * Determine if we are able to update automatically. This only works
2150 * if there are recent Guest Additions installed already.
2151 */
2152 Utf8Str strAddsVer;
2153 rc = getGuestProperty(pGuest, "/VirtualBox/GuestAdd/Version", strAddsVer);
2154 if ( RT_SUCCESS(rc)
2155 && RTStrVersionCompare(strAddsVer.c_str(), "4.1") < 0)
2156 {
2157 hr = setProgressErrorMsg(VBOX_E_NOT_SUPPORTED,
2158 Utf8StrFmt(GuestSession::tr("Guest has too old Guest Additions (%s) installed for automatic updating, please update manually"),
2159 strAddsVer.c_str()));
2160 rc = VERR_NOT_SUPPORTED;
2161 }
2162 }
2163
2164 Utf8Str strOSVer;
2165 eOSType osType = eOSType_Unknown;
2166 if (RT_SUCCESS(rc))
2167 {
2168 /*
2169 * Determine guest OS type and the required installer image.
2170 */
2171 Utf8Str strOSType;
2172 rc = getGuestProperty(pGuest, "/VirtualBox/GuestInfo/OS/Product", strOSType);
2173 if (RT_SUCCESS(rc))
2174 {
2175 if ( strOSType.contains("Microsoft", Utf8Str::CaseInsensitive)
2176 || strOSType.contains("Windows", Utf8Str::CaseInsensitive))
2177 {
2178 osType = eOSType_Windows;
2179
2180 /*
2181 * Determine guest OS version.
2182 */
2183 rc = getGuestProperty(pGuest, "/VirtualBox/GuestInfo/OS/Release", strOSVer);
2184 if (RT_FAILURE(rc))
2185 {
2186 hr = setProgressErrorMsg(VBOX_E_NOT_SUPPORTED,
2187 Utf8StrFmt(GuestSession::tr("Unable to detected guest OS version, please update manually")));
2188 rc = VERR_NOT_SUPPORTED;
2189 }
2190
2191 /* Because Windows 2000 + XP and is bitching with WHQL popups even if we have signed drivers we
2192 * can't do automated updates here. */
2193 /* Windows XP 64-bit (5.2) is a Windows 2003 Server actually, so skip this here. */
2194 if ( RT_SUCCESS(rc)
2195 && RTStrVersionCompare(strOSVer.c_str(), "5.0") >= 0)
2196 {
2197 if ( strOSVer.startsWith("5.0") /* Exclude the build number. */
2198 || strOSVer.startsWith("5.1") /* Exclude the build number. */)
2199 {
2200 /* If we don't have AdditionsUpdateFlag_WaitForUpdateStartOnly set we can't continue
2201 * because the Windows Guest Additions installer will fail because of WHQL popups. If the
2202 * flag is set this update routine ends successfully as soon as the installer was started
2203 * (and the user has to deal with it in the guest). */
2204 if (!(mFlags & AdditionsUpdateFlag_WaitForUpdateStartOnly))
2205 {
2206 hr = setProgressErrorMsg(VBOX_E_NOT_SUPPORTED,
2207 Utf8StrFmt(GuestSession::tr("Windows 2000 and XP are not supported for automatic updating due to WHQL interaction, please update manually")));
2208 rc = VERR_NOT_SUPPORTED;
2209 }
2210 }
2211 }
2212 else
2213 {
2214 hr = setProgressErrorMsg(VBOX_E_NOT_SUPPORTED,
2215 Utf8StrFmt(GuestSession::tr("%s (%s) not supported for automatic updating, please update manually"),
2216 strOSType.c_str(), strOSVer.c_str()));
2217 rc = VERR_NOT_SUPPORTED;
2218 }
2219 }
2220 else if (strOSType.contains("Solaris", Utf8Str::CaseInsensitive))
2221 {
2222 osType = eOSType_Solaris;
2223 }
2224 else /* Everything else hopefully means Linux :-). */
2225 osType = eOSType_Linux;
2226
2227#if 1 /* Only Windows is supported (and tested) at the moment. */
2228 if ( RT_SUCCESS(rc)
2229 && osType != eOSType_Windows)
2230 {
2231 hr = setProgressErrorMsg(VBOX_E_NOT_SUPPORTED,
2232 Utf8StrFmt(GuestSession::tr("Detected guest OS (%s) does not support automatic Guest Additions updating, please update manually"),
2233 strOSType.c_str()));
2234 rc = VERR_NOT_SUPPORTED;
2235 }
2236#endif
2237 }
2238 }
2239
2240 if (RT_SUCCESS(rc))
2241 {
2242 /*
2243 * Try to open the .ISO file to extract all needed files.
2244 */
2245 RTVFSFILE hVfsFileIso;
2246 rc = RTVfsFileOpenNormal(mSource.c_str(), RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE, &hVfsFileIso);
2247 if (RT_SUCCESS(rc))
2248 {
2249 RTVFS hVfsIso;
2250 rc = RTFsIso9660VolOpen(hVfsFileIso, 0 /*fFlags*/, &hVfsIso, NULL);
2251 if (RT_FAILURE(rc))
2252 {
2253 hr = setProgressErrorMsg(VBOX_E_IPRT_ERROR,
2254 Utf8StrFmt(GuestSession::tr("Unable to open Guest Additions .ISO file \"%s\": %Rrc"),
2255 mSource.c_str(), rc));
2256 }
2257 else
2258 {
2259 /* Set default installation directories. */
2260 Utf8Str strUpdateDir = "/tmp/";
2261 if (osType == eOSType_Windows)
2262 strUpdateDir = "C:\\Temp\\";
2263
2264 rc = setProgress(5);
2265
2266 /* Try looking up the Guest Additions installation directory. */
2267 if (RT_SUCCESS(rc))
2268 {
2269 /* Try getting the installed Guest Additions version to know whether we
2270 * can install our temporary Guest Addition data into the original installation
2271 * directory.
2272 *
2273 * Because versions prior to 4.2 had bugs wrt spaces in paths we have to choose
2274 * a different location then.
2275 */
2276 bool fUseInstallDir = false;
2277
2278 Utf8Str strAddsVer;
2279 rc = getGuestProperty(pGuest, "/VirtualBox/GuestAdd/Version", strAddsVer);
2280 if ( RT_SUCCESS(rc)
2281 && RTStrVersionCompare(strAddsVer.c_str(), "4.2r80329") > 0)
2282 {
2283 fUseInstallDir = true;
2284 }
2285
2286 if (fUseInstallDir)
2287 {
2288 if (RT_SUCCESS(rc))
2289 rc = getGuestProperty(pGuest, "/VirtualBox/GuestAdd/InstallDir", strUpdateDir);
2290 if (RT_SUCCESS(rc))
2291 {
2292 if (osType == eOSType_Windows)
2293 {
2294 strUpdateDir.findReplace('/', '\\');
2295 strUpdateDir.append("\\Update\\");
2296 }
2297 else
2298 strUpdateDir.append("/update/");
2299 }
2300 }
2301 }
2302
2303 if (RT_SUCCESS(rc))
2304 LogRel(("Guest Additions update directory is: %s\n",
2305 strUpdateDir.c_str()));
2306
2307 /* Create the installation directory. */
2308 int rcGuest = VERR_IPE_UNINITIALIZED_STATUS;
2309 rc = pSession->i_directoryCreate(strUpdateDir, 755 /* Mode */, DirectoryCreateFlag_Parents, &rcGuest);
2310 if (RT_FAILURE(rc))
2311 {
2312 switch (rc)
2313 {
2314 case VERR_GSTCTL_GUEST_ERROR:
2315 hr = setProgressErrorMsg(VBOX_E_IPRT_ERROR, GuestProcess::i_guestErrorToString(rcGuest));
2316 break;
2317
2318 default:
2319 hr = setProgressErrorMsg(VBOX_E_IPRT_ERROR,
2320 Utf8StrFmt(GuestSession::tr("Error creating installation directory \"%s\" on the guest: %Rrc"),
2321 strUpdateDir.c_str(), rc));
2322 break;
2323 }
2324 }
2325 if (RT_SUCCESS(rc))
2326 rc = setProgress(10);
2327
2328 if (RT_SUCCESS(rc))
2329 {
2330 /* Prepare the file(s) we want to copy over to the guest and
2331 * (maybe) want to run. */
2332 switch (osType)
2333 {
2334 case eOSType_Windows:
2335 {
2336 /* Do we need to install our certificates? We do this for W2K and up. */
2337 bool fInstallCert = false;
2338
2339 /* Only Windows 2000 and up need certificates to be installed. */
2340 if (RTStrVersionCompare(strOSVer.c_str(), "5.0") >= 0)
2341 {
2342 fInstallCert = true;
2343 LogRel(("Certificates for auto updating WHQL drivers will be installed\n"));
2344 }
2345 else
2346 LogRel(("Skipping installation of certificates for WHQL drivers\n"));
2347
2348 if (fInstallCert)
2349 {
2350 static struct { const char *pszDst, *pszIso; } const s_aCertFiles[] =
2351 {
2352 { "vbox.cer", "CERT/VBOX.CER" },
2353 { "vbox-sha1.cer", "CERT/VBOX_SHA1.CER" },
2354 { "vbox-sha256.cer", "CERT/VBOX_SHA256.CER" },
2355 { "vbox-sha256-r3.cer", "CERT/VBOX_SHA256_R3.CER" },
2356 { "oracle-vbox.cer", "CERT/ORACLE_VBOX.CER" },
2357 };
2358 uint32_t fCopyCertUtil = ISOFILE_FLAG_COPY_FROM_ISO;
2359 for (uint32_t i = 0; i < RT_ELEMENTS(s_aCertFiles); i++)
2360 {
2361 /* Skip if not present on the ISO. */
2362 RTFSOBJINFO ObjInfo;
2363 rc = RTVfsQueryPathInfo(hVfsIso, s_aCertFiles[i].pszIso, &ObjInfo, RTFSOBJATTRADD_NOTHING,
2364 RTPATH_F_ON_LINK);
2365 if (RT_FAILURE(rc))
2366 continue;
2367
2368 /* Copy the certificate certificate. */
2369 Utf8Str const strDstCert(strUpdateDir + s_aCertFiles[i].pszDst);
2370 mFiles.push_back(ISOFile(s_aCertFiles[i].pszIso,
2371 strDstCert,
2372 ISOFILE_FLAG_COPY_FROM_ISO | ISOFILE_FLAG_OPTIONAL));
2373
2374 /* Out certificate installation utility. */
2375 /* First pass: Copy over the file (first time only) + execute it to remove any
2376 * existing VBox certificates. */
2377 GuestProcessStartupInfo siCertUtilRem;
2378 siCertUtilRem.mName = "VirtualBox Certificate Utility, removing old VirtualBox certificates";
2379 siCertUtilRem.mArguments.push_back(Utf8Str("remove-trusted-publisher"));
2380 siCertUtilRem.mArguments.push_back(Utf8Str("--root")); /* Add root certificate as well. */
2381 siCertUtilRem.mArguments.push_back(strDstCert);
2382 siCertUtilRem.mArguments.push_back(strDstCert);
2383 mFiles.push_back(ISOFile("CERT/VBOXCERTUTIL.EXE",
2384 strUpdateDir + "VBoxCertUtil.exe",
2385 fCopyCertUtil | ISOFILE_FLAG_EXECUTE | ISOFILE_FLAG_OPTIONAL,
2386 siCertUtilRem));
2387 fCopyCertUtil = 0;
2388 /* Second pass: Only execute (but don't copy) again, this time installng the
2389 * recent certificates just copied over. */
2390 GuestProcessStartupInfo siCertUtilAdd;
2391 siCertUtilAdd.mName = "VirtualBox Certificate Utility, installing VirtualBox certificates";
2392 siCertUtilAdd.mArguments.push_back(Utf8Str("add-trusted-publisher"));
2393 siCertUtilAdd.mArguments.push_back(Utf8Str("--root")); /* Add root certificate as well. */
2394 siCertUtilAdd.mArguments.push_back(strDstCert);
2395 siCertUtilAdd.mArguments.push_back(strDstCert);
2396 mFiles.push_back(ISOFile("CERT/VBOXCERTUTIL.EXE",
2397 strUpdateDir + "VBoxCertUtil.exe",
2398 ISOFILE_FLAG_EXECUTE | ISOFILE_FLAG_OPTIONAL,
2399 siCertUtilAdd));
2400 }
2401 }
2402 /* The installers in different flavors, as we don't know (and can't assume)
2403 * the guest's bitness. */
2404 mFiles.push_back(ISOFile("VBOXWINDOWSADDITIONS_X86.EXE",
2405 strUpdateDir + "VBoxWindowsAdditions-x86.exe",
2406 ISOFILE_FLAG_COPY_FROM_ISO));
2407 mFiles.push_back(ISOFile("VBOXWINDOWSADDITIONS_AMD64.EXE",
2408 strUpdateDir + "VBoxWindowsAdditions-amd64.exe",
2409 ISOFILE_FLAG_COPY_FROM_ISO));
2410 /* The stub loader which decides which flavor to run. */
2411 GuestProcessStartupInfo siInstaller;
2412 siInstaller.mName = "VirtualBox Windows Guest Additions Installer";
2413 /* Set a running timeout of 5 minutes -- the Windows Guest Additions
2414 * setup can take quite a while, so be on the safe side. */
2415 siInstaller.mTimeoutMS = 5 * 60 * 1000;
2416 siInstaller.mArguments.push_back(Utf8Str("/S")); /* We want to install in silent mode. */
2417 siInstaller.mArguments.push_back(Utf8Str("/l")); /* ... and logging enabled. */
2418 /* Don't quit VBoxService during upgrade because it still is used for this
2419 * piece of code we're in right now (that is, here!) ... */
2420 siInstaller.mArguments.push_back(Utf8Str("/no_vboxservice_exit"));
2421 /* Tell the installer to report its current installation status
2422 * using a running VBoxTray instance via balloon messages in the
2423 * Windows taskbar. */
2424 siInstaller.mArguments.push_back(Utf8Str("/post_installstatus"));
2425 /* Add optional installer command line arguments from the API to the
2426 * installer's startup info. */
2427 rc = addProcessArguments(siInstaller.mArguments, mArguments);
2428 AssertRC(rc);
2429 /* If the caller does not want to wait for out guest update process to end,
2430 * complete the progress object now so that the caller can do other work. */
2431 if (mFlags & AdditionsUpdateFlag_WaitForUpdateStartOnly)
2432 siInstaller.mFlags |= ProcessCreateFlag_WaitForProcessStartOnly;
2433 mFiles.push_back(ISOFile("VBOXWINDOWSADDITIONS.EXE",
2434 strUpdateDir + "VBoxWindowsAdditions.exe",
2435 ISOFILE_FLAG_COPY_FROM_ISO | ISOFILE_FLAG_EXECUTE, siInstaller));
2436 break;
2437 }
2438 case eOSType_Linux:
2439 /** @todo Add Linux support. */
2440 break;
2441 case eOSType_Solaris:
2442 /** @todo Add Solaris support. */
2443 break;
2444 default:
2445 AssertReleaseMsgFailed(("Unsupported guest type: %d\n", osType));
2446 break;
2447 }
2448 }
2449
2450 if (RT_SUCCESS(rc))
2451 {
2452 /* We want to spend 40% total for all copying operations. So roughly
2453 * calculate the specific percentage step of each copied file. */
2454 uint8_t uOffset = 20; /* Start at 20%. */
2455 uint8_t uStep = 40 / (uint8_t)mFiles.size(); Assert(mFiles.size() <= 10);
2456
2457 LogRel(("Copying over Guest Additions update files to the guest ...\n"));
2458
2459 std::vector<ISOFile>::const_iterator itFiles = mFiles.begin();
2460 while (itFiles != mFiles.end())
2461 {
2462 if (itFiles->fFlags & ISOFILE_FLAG_COPY_FROM_ISO)
2463 {
2464 bool fOptional = false;
2465 if (itFiles->fFlags & ISOFILE_FLAG_OPTIONAL)
2466 fOptional = true;
2467 rc = copyFileToGuest(pSession, hVfsIso, itFiles->strSource, itFiles->strDest, fOptional);
2468 if (RT_FAILURE(rc))
2469 {
2470 hr = setProgressErrorMsg(VBOX_E_IPRT_ERROR,
2471 Utf8StrFmt(GuestSession::tr("Error while copying file \"%s\" to \"%s\" on the guest: %Rrc"),
2472 itFiles->strSource.c_str(), itFiles->strDest.c_str(), rc));
2473 break;
2474 }
2475 }
2476
2477 rc = setProgress(uOffset);
2478 if (RT_FAILURE(rc))
2479 break;
2480 uOffset += uStep;
2481
2482 ++itFiles;
2483 }
2484 }
2485
2486 /* Done copying, close .ISO file. */
2487 RTVfsRelease(hVfsIso);
2488
2489 if (RT_SUCCESS(rc))
2490 {
2491 /* We want to spend 35% total for all copying operations. So roughly
2492 * calculate the specific percentage step of each copied file. */
2493 uint8_t uOffset = 60; /* Start at 60%. */
2494 uint8_t uStep = 35 / (uint8_t)mFiles.size(); Assert(mFiles.size() <= 10);
2495
2496 LogRel(("Executing Guest Additions update files ...\n"));
2497
2498 std::vector<ISOFile>::iterator itFiles = mFiles.begin();
2499 while (itFiles != mFiles.end())
2500 {
2501 if (itFiles->fFlags & ISOFILE_FLAG_EXECUTE)
2502 {
2503 rc = runFileOnGuest(pSession, itFiles->mProcInfo);
2504 if (RT_FAILURE(rc))
2505 break;
2506 }
2507
2508 rc = setProgress(uOffset);
2509 if (RT_FAILURE(rc))
2510 break;
2511 uOffset += uStep;
2512
2513 ++itFiles;
2514 }
2515 }
2516
2517 if (RT_SUCCESS(rc))
2518 {
2519 LogRel(("Automatic update of Guest Additions succeeded\n"));
2520 rc = setProgressSuccess();
2521 }
2522 }
2523
2524 RTVfsFileRelease(hVfsFileIso);
2525 }
2526 }
2527
2528 if (RT_FAILURE(rc))
2529 {
2530 if (rc == VERR_CANCELLED)
2531 {
2532 LogRel(("Automatic update of Guest Additions was canceled\n"));
2533
2534 hr = setProgressErrorMsg(VBOX_E_IPRT_ERROR,
2535 Utf8StrFmt(GuestSession::tr("Installation was canceled")));
2536 }
2537 else
2538 {
2539 Utf8Str strError = Utf8StrFmt("No further error information available (%Rrc)", rc);
2540 if (!mProgress.isNull()) /* Progress object is optional. */
2541 {
2542 com::ProgressErrorInfo errorInfo(mProgress);
2543 if ( errorInfo.isFullAvailable()
2544 || errorInfo.isBasicAvailable())
2545 {
2546 strError = errorInfo.getText();
2547 }
2548 }
2549
2550 LogRel(("Automatic update of Guest Additions failed: %s (%Rhrc)\n",
2551 strError.c_str(), hr));
2552 }
2553
2554 LogRel(("Please install Guest Additions manually\n"));
2555 }
2556
2557 /** @todo Clean up copied / left over installation files. */
2558
2559 LogFlowFuncLeaveRC(rc);
2560 return rc;
2561}
2562
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