VirtualBox

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

Last change on this file since 96606 was 96407, checked in by vboxsync, 3 years ago

scm copyright and license note update

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