VirtualBox

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

Last change on this file since 92558 was 92558, checked in by vboxsync, 4 years ago

Guest Control/Main + FE/Qt: Fixes for host -> guest and guest -> host copy operations using GuestSession::copyFromGuest() and GuestSession::copyToGuest() -- follow-up fix, also handle symlinks here. bugref:10139

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

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