VirtualBox

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

Last change on this file since 96617 was 96617, checked in by vboxsync, 2 years ago

Main: whitespace/nits.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 108.8 KB
Line 
1/* $Id: GuestSessionImplTasks.cpp 96617 2022-09-06 20:31:42Z 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 vrc = VERR_IS_A_FILE;
1342 else if (RTFS_IS_SYMLINK(objInfo.Attr.fMode))
1343 vrc = VERR_IS_A_SYMLINK;
1344 else
1345 vrc = VERR_NOT_SUPPORTED;
1346 }
1347 else
1348 LogFlowFunc(("Unable to query '%s', rc=%Rrc\n", strPathAbs.c_str(), vrc));
1349
1350 LogFlowFuncLeaveRC(vrc);
1351 return vrc;
1352}
1353
1354GuestSessionTaskOpen::GuestSessionTaskOpen(GuestSession *pSession, uint32_t uFlags, uint32_t uTimeoutMS)
1355 : GuestSessionTask(pSession)
1356 , mFlags(uFlags)
1357 , mTimeoutMS(uTimeoutMS)
1358{
1359 m_strTaskName = "gctlSesOpen";
1360}
1361
1362GuestSessionTaskOpen::~GuestSessionTaskOpen(void)
1363{
1364
1365}
1366
1367/** @copydoc GuestSessionTask::Run */
1368int GuestSessionTaskOpen::Run(void)
1369{
1370 LogFlowThisFuncEnter();
1371
1372 AutoCaller autoCaller(mSession);
1373 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1374
1375 int vrc = mSession->i_startSession(NULL /*pvrcGuest*/);
1376 /* Nothing to do here anymore. */
1377
1378 LogFlowFuncLeaveRC(vrc);
1379 return vrc;
1380}
1381
1382GuestSessionCopyTask::GuestSessionCopyTask(GuestSession *pSession)
1383 : GuestSessionTask(pSession)
1384{
1385}
1386
1387GuestSessionCopyTask::~GuestSessionCopyTask()
1388{
1389 FsLists::iterator itList = mVecLists.begin();
1390 while (itList != mVecLists.end())
1391 {
1392 FsList *pFsList = (*itList);
1393 pFsList->Destroy();
1394 delete pFsList;
1395 mVecLists.erase(itList);
1396 itList = mVecLists.begin();
1397 }
1398
1399 Assert(mVecLists.empty());
1400}
1401
1402GuestSessionTaskCopyFrom::GuestSessionTaskCopyFrom(GuestSession *pSession, GuestSessionFsSourceSet const &vecSrc,
1403 const Utf8Str &strDest)
1404 : GuestSessionCopyTask(pSession)
1405{
1406 m_strTaskName = "gctlCpyFrm";
1407
1408 mSources = vecSrc;
1409 mDest = strDest;
1410}
1411
1412GuestSessionTaskCopyFrom::~GuestSessionTaskCopyFrom(void)
1413{
1414}
1415
1416/**
1417 * Initializes a copy-from-guest task.
1418 *
1419 * @returns HRESULT
1420 * @param strTaskDesc Friendly task description.
1421 */
1422HRESULT GuestSessionTaskCopyFrom::Init(const Utf8Str &strTaskDesc)
1423{
1424 setTaskDesc(strTaskDesc);
1425
1426 /* Create the progress object. */
1427 ComObjPtr<Progress> pProgress;
1428 HRESULT hrc = pProgress.createObject();
1429 if (FAILED(hrc))
1430 return hrc;
1431
1432 mProgress = pProgress;
1433
1434 int vrc = VINF_SUCCESS;
1435
1436 ULONG cOperations = 0;
1437 Utf8Str strErrorInfo;
1438
1439 /**
1440 * Note: We need to build up the file/directory here instead of GuestSessionTaskCopyFrom::Run
1441 * because the caller expects a ready-for-operation progress object on return.
1442 * The progress object will have a variable operation count, based on the elements to
1443 * be processed.
1444 */
1445
1446 if (mDest.isEmpty())
1447 {
1448 strErrorInfo = Utf8StrFmt(tr("Host destination must not be empty"));
1449 vrc = VERR_INVALID_PARAMETER;
1450 }
1451 else
1452 {
1453 GuestSessionFsSourceSet::iterator itSrc = mSources.begin();
1454 while (itSrc != mSources.end())
1455 {
1456 Utf8Str strSrc = itSrc->strSource;
1457 Utf8Str strDst = mDest;
1458
1459 bool fFollowSymlinks;
1460
1461 if (strSrc.isEmpty())
1462 {
1463 strErrorInfo = Utf8StrFmt(tr("Guest source entry must not be empty"));
1464 vrc = VERR_INVALID_PARAMETER;
1465 break;
1466 }
1467
1468 if (itSrc->enmType == FsObjType_Directory)
1469 {
1470 /* If the source does not end with a slash, copy over the entire directory
1471 * (and not just its contents). */
1472 /** @todo r=bird: Try get the path style stuff right and stop assuming all guest are windows guests. */
1473 if ( !strSrc.endsWith("/")
1474 && !strSrc.endsWith("\\"))
1475 {
1476 if (!RTPATH_IS_SLASH(strDst[strDst.length() - 1]))
1477 strDst += "/";
1478
1479 strDst += Utf8Str(RTPathFilenameEx(strSrc.c_str(), mfPathStyle));
1480 }
1481
1482 fFollowSymlinks = itSrc->Type.Dir.fCopyFlags & DirectoryCopyFlag_FollowLinks;
1483 }
1484 else
1485 {
1486 fFollowSymlinks = RT_BOOL(itSrc->Type.File.fCopyFlags & FileCopyFlag_FollowLinks);
1487 }
1488
1489 LogFlowFunc(("strSrc=%s, strDst=%s, fFollowSymlinks=%RTbool\n", strSrc.c_str(), strDst.c_str(), fFollowSymlinks));
1490
1491 GuestFsObjData srcObjData;
1492 int vrcGuest = VERR_IPE_UNINITIALIZED_STATUS;
1493 vrc = mSession->i_fsQueryInfo(strSrc, fFollowSymlinks, srcObjData, &vrcGuest);
1494 if (RT_FAILURE(vrc))
1495 {
1496 if (vrc == VERR_GSTCTL_GUEST_ERROR)
1497 strErrorInfo = GuestBase::getErrorAsString(tr("Guest file lookup failed"),
1498 GuestErrorInfo(GuestErrorInfo::Type_ToolStat, vrcGuest, strSrc.c_str()));
1499 else
1500 strErrorInfo = Utf8StrFmt(tr("Guest file lookup for \"%s\" failed: %Rrc"),
1501 strSrc.c_str(), vrc);
1502 break;
1503 }
1504
1505 if (srcObjData.mType == FsObjType_Directory)
1506 {
1507 if (itSrc->enmType != FsObjType_Directory)
1508 {
1509 strErrorInfo = Utf8StrFmt(tr("Guest source is not a file: %s"), strSrc.c_str());
1510 vrc = VERR_NOT_A_FILE;
1511 break;
1512 }
1513 }
1514 else
1515 {
1516 if (itSrc->enmType != FsObjType_File)
1517 {
1518 strErrorInfo = Utf8StrFmt(tr("Guest source is not a directory: %s"), strSrc.c_str());
1519 vrc = VERR_NOT_A_DIRECTORY;
1520 break;
1521 }
1522 }
1523
1524 FsList *pFsList = NULL;
1525 try
1526 {
1527 pFsList = new FsList(*this);
1528 vrc = pFsList->Init(strSrc, strDst, *itSrc);
1529 if (RT_SUCCESS(vrc))
1530 {
1531 if (itSrc->enmType == FsObjType_Directory)
1532 vrc = pFsList->AddDirFromGuest(strSrc);
1533 else
1534 vrc = pFsList->AddEntryFromGuest(RTPathFilename(strSrc.c_str()), srcObjData);
1535 }
1536
1537 if (RT_FAILURE(vrc))
1538 {
1539 delete pFsList;
1540 strErrorInfo = Utf8StrFmt(tr("Error adding guest source '%s' to list: %Rrc"),
1541 strSrc.c_str(), vrc);
1542 break;
1543 }
1544
1545 mVecLists.push_back(pFsList);
1546 }
1547 catch (std::bad_alloc &)
1548 {
1549 vrc = VERR_NO_MEMORY;
1550 break;
1551 }
1552
1553 AssertPtr(pFsList);
1554 cOperations += (ULONG)pFsList->mVecEntries.size();
1555
1556 itSrc++;
1557 }
1558 }
1559
1560 if (cOperations) /* Use the first element as description (if available). */
1561 {
1562 Assert(mVecLists.size());
1563 Assert(mVecLists[0]->mVecEntries.size());
1564
1565 Utf8Str strFirstOp = mDest + mVecLists[0]->mVecEntries[0]->strPath;
1566 hrc = pProgress->init(static_cast<IGuestSession*>(mSession), Bstr(mDesc).raw(),
1567 TRUE /* aCancelable */, cOperations + 1 /* Number of operations */, Bstr(strFirstOp).raw());
1568 }
1569 else /* If no operations have been defined, go with an "empty" progress object when will be used for error handling. */
1570 hrc = pProgress->init(static_cast<IGuestSession*>(mSession), Bstr(mDesc).raw(),
1571 TRUE /* aCancelable */, 1 /* cOperations */, Bstr(mDesc).raw());
1572
1573 if (RT_FAILURE(vrc))
1574 {
1575 if (strErrorInfo.isEmpty())
1576 strErrorInfo = Utf8StrFmt(tr("Failed with %Rrc"), vrc);
1577 setProgressErrorMsg(VBOX_E_IPRT_ERROR, strErrorInfo);
1578 }
1579
1580 LogFlowFunc(("Returning %Rhrc (%Rrc)\n", hrc, vrc));
1581 return hrc;
1582}
1583
1584/** @copydoc GuestSessionTask::Run */
1585int GuestSessionTaskCopyFrom::Run(void)
1586{
1587 LogFlowThisFuncEnter();
1588
1589 AutoCaller autoCaller(mSession);
1590 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1591
1592 int vrc = VINF_SUCCESS;
1593
1594 FsLists::const_iterator itList = mVecLists.begin();
1595 while (itList != mVecLists.end())
1596 {
1597 FsList *pList = *itList;
1598 AssertPtr(pList);
1599
1600 const bool fCopyIntoExisting = pList->mSourceSpec.Type.Dir.fCopyFlags & DirectoryCopyFlag_CopyIntoExisting;
1601 const bool fFollowSymlinks = true; /** @todo */
1602 const uint32_t fDirMode = 0700; /** @todo Play safe by default; implement ACLs. */
1603 uint32_t fDirCreate = 0;
1604
1605 if (!fFollowSymlinks)
1606 fDirCreate |= RTDIRCREATE_FLAGS_NO_SYMLINKS;
1607
1608 LogFlowFunc(("List: srcRootAbs=%s, dstRootAbs=%s\n", pList->mSrcRootAbs.c_str(), pList->mDstRootAbs.c_str()));
1609
1610 /* Create the root directory. */
1611 if ( pList->mSourceSpec.enmType == FsObjType_Directory
1612 && pList->mSourceSpec.fDryRun == false)
1613 {
1614 vrc = directoryCreateOnHost(pList->mDstRootAbs, fDirCreate, fDirMode, fCopyIntoExisting);
1615 if (RT_FAILURE(vrc))
1616 break;
1617 }
1618
1619 FsEntries::const_iterator itEntry = pList->mVecEntries.begin();
1620 while (itEntry != pList->mVecEntries.end())
1621 {
1622 FsEntry *pEntry = *itEntry;
1623 AssertPtr(pEntry);
1624
1625 Utf8Str strSrcAbs = pList->mSrcRootAbs;
1626 Utf8Str strDstAbs = pList->mDstRootAbs;
1627
1628 LogFlowFunc(("Entry: srcRootAbs=%s, dstRootAbs=%s\n", pList->mSrcRootAbs.c_str(), pList->mDstRootAbs.c_str()));
1629
1630 if (pList->mSourceSpec.enmType == FsObjType_Directory)
1631 {
1632 char szPath[RTPATH_MAX];
1633
1634 /* Build the source path on the guest. */
1635 vrc = RTStrCopy(szPath, sizeof(szPath), pList->mSrcRootAbs.c_str());
1636 if (RT_SUCCESS(vrc))
1637 {
1638 vrc = RTPathAppend(szPath, sizeof(szPath), pEntry->strPath.c_str());
1639 if (RT_SUCCESS(vrc))
1640 strSrcAbs = szPath;
1641 }
1642
1643 /* Build the destination path on the host. */
1644 vrc = RTStrCopy(szPath, sizeof(szPath), pList->mDstRootAbs.c_str());
1645 if (RT_SUCCESS(vrc))
1646 {
1647 vrc = RTPathAppend(szPath, sizeof(szPath), pEntry->strPath.c_str());
1648 if (RT_SUCCESS(vrc))
1649 strDstAbs = szPath;
1650 }
1651 }
1652
1653 if (pList->mSourceSpec.enmPathStyle == PathStyle_DOS)
1654 strDstAbs.findReplace('\\', '/');
1655
1656 mProgress->SetNextOperation(Bstr(strSrcAbs).raw(), 1);
1657
1658 LogRel2(("Guest Control: Copying '%s' from guest to '%s' on host ...\n", strSrcAbs.c_str(), strDstAbs.c_str()));
1659
1660 switch (pEntry->fMode & RTFS_TYPE_MASK)
1661 {
1662 case RTFS_TYPE_DIRECTORY:
1663 LogFlowFunc(("Directory '%s': %s -> %s\n", pEntry->strPath.c_str(), strSrcAbs.c_str(), strDstAbs.c_str()));
1664 if (!pList->mSourceSpec.fDryRun)
1665 vrc = directoryCreateOnHost(strDstAbs, fDirCreate, fDirMode, fCopyIntoExisting);
1666 break;
1667
1668 case RTFS_TYPE_FILE:
1669 RT_FALL_THROUGH();
1670 case RTFS_TYPE_SYMLINK:
1671 LogFlowFunc(("%s '%s': %s -> %s\n", pEntry->strPath.c_str(),
1672 (pEntry->fMode & RTFS_TYPE_MASK) == RTFS_TYPE_SYMLINK ? "Symlink" : "File",
1673 strSrcAbs.c_str(), strDstAbs.c_str()));
1674 if (!pList->mSourceSpec.fDryRun)
1675 vrc = fileCopyFromGuest(strSrcAbs, strDstAbs, FileCopyFlag_None);
1676 break;
1677
1678 default:
1679 LogFlowFunc(("Warning: Type %d for '%s' is not supported\n",
1680 pEntry->fMode & RTFS_TYPE_MASK, strSrcAbs.c_str()));
1681 break;
1682 }
1683
1684 if (RT_FAILURE(vrc))
1685 break;
1686
1687 ++itEntry;
1688 }
1689
1690 if (RT_FAILURE(vrc))
1691 break;
1692
1693 ++itList;
1694 }
1695
1696 if (RT_SUCCESS(vrc))
1697 vrc = setProgressSuccess();
1698
1699 LogFlowFuncLeaveRC(vrc);
1700 return vrc;
1701}
1702
1703GuestSessionTaskCopyTo::GuestSessionTaskCopyTo(GuestSession *pSession, GuestSessionFsSourceSet const &vecSrc,
1704 const Utf8Str &strDest)
1705 : GuestSessionCopyTask(pSession)
1706{
1707 m_strTaskName = "gctlCpyTo";
1708
1709 mSources = vecSrc;
1710 mDest = strDest;
1711}
1712
1713GuestSessionTaskCopyTo::~GuestSessionTaskCopyTo(void)
1714{
1715}
1716
1717/**
1718 * Initializes a copy-to-guest task.
1719 *
1720 * @returns HRESULT
1721 * @param strTaskDesc Friendly task description.
1722 */
1723HRESULT GuestSessionTaskCopyTo::Init(const Utf8Str &strTaskDesc)
1724{
1725 LogFlowFuncEnter();
1726
1727 setTaskDesc(strTaskDesc);
1728
1729 /* Create the progress object. */
1730 ComObjPtr<Progress> pProgress;
1731 HRESULT hrc = pProgress.createObject();
1732 if (FAILED(hrc))
1733 return hrc;
1734
1735 mProgress = pProgress;
1736
1737 int vrc = VINF_SUCCESS;
1738
1739 ULONG cOperations = 0;
1740 Utf8Str strErrorInfo;
1741
1742 /*
1743 * Note: We need to build up the file/directory here instead of GuestSessionTaskCopyTo::Run
1744 * because the caller expects a ready-for-operation progress object on return.
1745 * The progress object will have a variable operation count, based on the elements to
1746 * be processed.
1747 */
1748
1749 if (mDest.isEmpty())
1750 {
1751 strErrorInfo = Utf8StrFmt(tr("Guest destination must not be empty"));
1752 vrc = VERR_INVALID_PARAMETER;
1753 }
1754 else
1755 {
1756 GuestSessionFsSourceSet::iterator itSrc = mSources.begin();
1757 while (itSrc != mSources.end())
1758 {
1759 Utf8Str strSrc = itSrc->strSource;
1760 Utf8Str strDst = mDest;
1761
1762 LogFlowFunc(("strSrc=%s, strDst=%s\n", strSrc.c_str(), strDst.c_str()));
1763
1764 if (strSrc.isEmpty())
1765 {
1766 strErrorInfo = Utf8StrFmt(tr("Host source entry must not be empty"));
1767 vrc = VERR_INVALID_PARAMETER;
1768 break;
1769 }
1770
1771 RTFSOBJINFO srcFsObjInfo;
1772 vrc = RTPathQueryInfo(strSrc.c_str(), &srcFsObjInfo, RTFSOBJATTRADD_NOTHING);
1773 if (RT_FAILURE(vrc))
1774 {
1775 strErrorInfo = Utf8StrFmt(tr("No such host file/directory: %s"), strSrc.c_str());
1776 break;
1777 }
1778
1779 if (RTFS_IS_DIRECTORY(srcFsObjInfo.Attr.fMode))
1780 {
1781 if (itSrc->enmType != FsObjType_Directory)
1782 {
1783 strErrorInfo = Utf8StrFmt(tr("Host source is not a file: %s"), strSrc.c_str());
1784 vrc = VERR_NOT_A_FILE;
1785 break;
1786 }
1787 }
1788 else
1789 {
1790 if (itSrc->enmType == FsObjType_Directory)
1791 {
1792 strErrorInfo = Utf8StrFmt(tr("Host source is not a directory: %s"), strSrc.c_str());
1793 vrc = VERR_NOT_A_DIRECTORY;
1794 break;
1795 }
1796 }
1797
1798 FsList *pFsList = NULL;
1799 try
1800 {
1801 pFsList = new FsList(*this);
1802 vrc = pFsList->Init(strSrc, strDst, *itSrc);
1803 if (RT_SUCCESS(vrc))
1804 {
1805 if (itSrc->enmType == FsObjType_Directory)
1806 vrc = pFsList->AddDirFromHost(strSrc);
1807 else
1808 vrc = pFsList->AddEntryFromHost(RTPathFilename(strSrc.c_str()), &srcFsObjInfo);
1809 }
1810
1811 if (RT_FAILURE(vrc))
1812 {
1813 delete pFsList;
1814 strErrorInfo = Utf8StrFmt(tr("Error adding host source '%s' to list: %Rrc"),
1815 strSrc.c_str(), vrc);
1816 break;
1817 }
1818
1819 mVecLists.push_back(pFsList);
1820 }
1821 catch (std::bad_alloc &)
1822 {
1823 vrc = VERR_NO_MEMORY;
1824 break;
1825 }
1826
1827 AssertPtr(pFsList);
1828 cOperations += (ULONG)pFsList->mVecEntries.size();
1829
1830 itSrc++;
1831 }
1832 }
1833
1834 if (cOperations) /* Use the first element as description (if available). */
1835 {
1836 Assert(mVecLists.size());
1837 Assert(mVecLists[0]->mVecEntries.size());
1838
1839 hrc = pProgress->init(static_cast<IGuestSession*>(mSession), Bstr(mDesc).raw(),
1840 TRUE /* aCancelable */, cOperations + 1 /* Number of operations */,
1841 Bstr(mDesc).raw());
1842 }
1843 else /* If no operations have been defined, go with an "empty" progress object when will be used for error handling. */
1844 hrc = pProgress->init(static_cast<IGuestSession*>(mSession), Bstr(mDesc).raw(),
1845 TRUE /* aCancelable */, 1 /* cOperations */, Bstr(mDesc).raw());
1846
1847 if (RT_FAILURE(vrc))
1848 {
1849 if (strErrorInfo.isEmpty())
1850 strErrorInfo = Utf8StrFmt(tr("Failed with %Rrc"), vrc);
1851 setProgressErrorMsg(VBOX_E_IPRT_ERROR, strErrorInfo);
1852 }
1853
1854 LogFlowFunc(("Returning %Rhrc (%Rrc)\n", hrc, vrc));
1855 return hrc;
1856}
1857
1858/** @copydoc GuestSessionTask::Run */
1859int GuestSessionTaskCopyTo::Run(void)
1860{
1861 LogFlowThisFuncEnter();
1862
1863 AutoCaller autoCaller(mSession);
1864 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1865
1866 int vrc = VINF_SUCCESS;
1867
1868 FsLists::const_iterator itList = mVecLists.begin();
1869 while (itList != mVecLists.end())
1870 {
1871 FsList *pList = *itList;
1872 AssertPtr(pList);
1873
1874 Utf8Str strSrcRootAbs = pList->mSrcRootAbs;
1875 Utf8Str strDstRootAbs = pList->mDstRootAbs;
1876
1877 bool fCopyIntoExisting = false;
1878 bool fFollowSymlinks = false;
1879 uint32_t fDirMode = 0700; /** @todo Play safe by default; implement ACLs. */
1880
1881 GuestFsObjData dstObjData;
1882 int vrcGuest;
1883 vrc = mSession->i_fsQueryInfo(strDstRootAbs, pList->mSourceSpec.Type.Dir.fCopyFlags & DirectoryCopyFlag_FollowLinks,
1884 dstObjData, &vrcGuest);
1885 if (RT_FAILURE(vrc))
1886 {
1887 if (vrc == VERR_GSTCTL_GUEST_ERROR)
1888 {
1889 switch (vrcGuest)
1890 {
1891 case VERR_PATH_NOT_FOUND:
1892 RT_FALL_THROUGH();
1893 case VERR_FILE_NOT_FOUND:
1894 /* We will deal with this down below. */
1895 vrc = VINF_SUCCESS;
1896 break;
1897 default:
1898 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1899 Utf8StrFmt(tr("Querying information on guest for '%s' failed: %Rrc"),
1900 strDstRootAbs.c_str(), vrcGuest));
1901 break;
1902 }
1903 }
1904 else
1905 {
1906 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1907 Utf8StrFmt(tr("Querying information on guest for '%s' failed: %Rrc"),
1908 strDstRootAbs.c_str(), vrc));
1909 break;
1910 }
1911 }
1912
1913 char szPath[RTPATH_MAX];
1914
1915 LogFlowFunc(("List inital: rc=%Rrc, srcRootAbs=%s, dstRootAbs=%s\n",
1916 vrc, strSrcRootAbs.c_str(), strDstRootAbs.c_str()));
1917
1918 /* Calculated file copy flags for the current source spec. */
1919 FileCopyFlag_T fFileCopyFlags = FileCopyFlag_None;
1920
1921 /* Create the root directory. */
1922 if (pList->mSourceSpec.enmType == FsObjType_Directory)
1923 {
1924 fCopyIntoExisting = RT_BOOL(pList->mSourceSpec.Type.Dir.fCopyFlags & DirectoryCopyFlag_CopyIntoExisting);
1925 fFollowSymlinks = RT_BOOL(pList->mSourceSpec.Type.Dir.fCopyFlags & DirectoryCopyFlag_FollowLinks);
1926
1927 LogFlowFunc(("Directory: fDirCopyFlags=%#x, fCopyIntoExisting=%RTbool, fFollowSymlinks=%RTbool\n",
1928 pList->mSourceSpec.Type.Dir.fCopyFlags, fCopyIntoExisting, fFollowSymlinks));
1929
1930 /* If the directory on the guest already exists, append the name of the root source directory to it. */
1931 switch (dstObjData.mType)
1932 {
1933 case FsObjType_Directory:
1934 {
1935 if (fCopyIntoExisting)
1936 {
1937 /* Build the destination path on the guest. */
1938 vrc = RTStrCopy(szPath, sizeof(szPath), strDstRootAbs.c_str());
1939 if (RT_SUCCESS(vrc))
1940 {
1941 vrc = RTPathAppend(szPath, sizeof(szPath), RTPathFilenameEx(strSrcRootAbs.c_str(), mfPathStyle));
1942 if (RT_SUCCESS(vrc))
1943 strDstRootAbs = szPath;
1944 }
1945 }
1946 else
1947 {
1948 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1949 Utf8StrFmt(tr("Guest directory \"%s\" already exists"),
1950 strDstRootAbs.c_str()));
1951 vrc = VERR_ALREADY_EXISTS;
1952 }
1953 break;
1954 }
1955
1956 case FsObjType_File:
1957 RT_FALL_THROUGH();
1958 case FsObjType_Symlink:
1959 /* Nothing to do. */
1960 break;
1961
1962 default:
1963 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1964 Utf8StrFmt(tr("Unknown object type (%#x) on guest for \"%s\""),
1965 dstObjData.mType, strDstRootAbs.c_str()));
1966 vrc = VERR_NOT_SUPPORTED;
1967 break;
1968 }
1969
1970 /* Make sure the destination root directory exists. */
1971 if ( RT_SUCCESS(vrc)
1972 && pList->mSourceSpec.fDryRun == false)
1973 {
1974 vrc = directoryCreateOnGuest(strDstRootAbs, DirectoryCreateFlag_None, fDirMode,
1975 fFollowSymlinks, true /* fCanExist */);
1976 }
1977
1978 /* No tweaking of fFileCopyFlags needed here. */
1979 }
1980 else if (pList->mSourceSpec.enmType == FsObjType_File)
1981 {
1982 fCopyIntoExisting = !(pList->mSourceSpec.Type.File.fCopyFlags & FileCopyFlag_NoReplace);
1983 fFollowSymlinks = RT_BOOL(pList->mSourceSpec.Type.File.fCopyFlags & FileCopyFlag_FollowLinks);
1984
1985 LogFlowFunc(("File: fFileCopyFlags=%#x, fCopyIntoExisting=%RTbool, fFollowSymlinks=%RTbool\n",
1986 pList->mSourceSpec.Type.File.fCopyFlags, fCopyIntoExisting, fFollowSymlinks));
1987
1988 fFileCopyFlags = pList->mSourceSpec.Type.File.fCopyFlags; /* Just use the flags directly from the spec. */
1989 }
1990 else
1991 AssertFailedStmt(vrc = VERR_NOT_SUPPORTED);
1992
1993 LogFlowFunc(("List final: rc=%Rrc, srcRootAbs=%s, dstRootAbs=%s, fFileCopyFlags=%#x\n",
1994 vrc, strSrcRootAbs.c_str(), strDstRootAbs.c_str(), fFileCopyFlags));
1995
1996 LogRel2(("Guest Control: Copying '%s' from host to '%s' on guest ...\n", strSrcRootAbs.c_str(), strDstRootAbs.c_str()));
1997
1998 if (RT_FAILURE(vrc))
1999 break;
2000
2001 FsEntries::const_iterator itEntry = pList->mVecEntries.begin();
2002 while ( RT_SUCCESS(vrc)
2003 && itEntry != pList->mVecEntries.end())
2004 {
2005 FsEntry *pEntry = *itEntry;
2006 AssertPtr(pEntry);
2007
2008 Utf8Str strSrcAbs = strSrcRootAbs;
2009 Utf8Str strDstAbs = strDstRootAbs;
2010
2011 if (pList->mSourceSpec.enmType == FsObjType_Directory)
2012 {
2013 /* Build the final (absolute) source path (on the host). */
2014 vrc = RTStrCopy(szPath, sizeof(szPath), strSrcAbs.c_str());
2015 if (RT_SUCCESS(vrc))
2016 {
2017 vrc = RTPathAppend(szPath, sizeof(szPath), pEntry->strPath.c_str());
2018 if (RT_SUCCESS(vrc))
2019 strSrcAbs = szPath;
2020 }
2021
2022 if (RT_FAILURE(vrc))
2023 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
2024 Utf8StrFmt(tr("Building source host path for entry \"%s\" failed (%Rrc)"),
2025 pEntry->strPath.c_str(), vrc));
2026 }
2027
2028 /** @todo Handle stuff like "C:" for destination, where the destination will be the CWD for drive C. */
2029 if (dstObjData.mType == FsObjType_Directory)
2030 {
2031 /* Build the final (absolute) destination path (on the guest). */
2032 vrc = RTStrCopy(szPath, sizeof(szPath), strDstAbs.c_str());
2033 if (RT_SUCCESS(vrc))
2034 {
2035 vrc = RTPathAppend(szPath, sizeof(szPath), pEntry->strPath.c_str());
2036 if (RT_SUCCESS(vrc))
2037 strDstAbs = szPath;
2038 }
2039
2040 if (RT_FAILURE(vrc))
2041 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
2042 Utf8StrFmt(tr("Building destination guest path for entry \"%s\" failed (%Rrc)"),
2043 pEntry->strPath.c_str(), vrc));
2044 }
2045
2046 mProgress->SetNextOperation(Bstr(strSrcAbs).raw(), 1);
2047
2048 LogRel2(("Guest Control: Copying '%s' from host to '%s' on guest ...\n", strSrcAbs.c_str(), strDstAbs.c_str()));
2049
2050 switch (pEntry->fMode & RTFS_TYPE_MASK)
2051 {
2052 case RTFS_TYPE_DIRECTORY:
2053 {
2054 if (!pList->mSourceSpec.fDryRun)
2055 vrc = directoryCreateOnGuest(strDstAbs, DirectoryCreateFlag_None, fDirMode,
2056 fFollowSymlinks, fCopyIntoExisting);
2057 break;
2058 }
2059
2060 case RTFS_TYPE_FILE:
2061 {
2062 if (!pList->mSourceSpec.fDryRun)
2063 vrc = fileCopyToGuest(strSrcAbs, strDstAbs, fFileCopyFlags);
2064 break;
2065 }
2066
2067 default:
2068 LogRel2(("Guest Control: Warning: Type 0x%x for '%s' is not supported, skipping\n",
2069 pEntry->fMode & RTFS_TYPE_MASK, strSrcAbs.c_str()));
2070 break;
2071 }
2072
2073 if (RT_FAILURE(vrc))
2074 break;
2075
2076 ++itEntry;
2077 }
2078
2079 if (RT_FAILURE(vrc))
2080 break;
2081
2082 ++itList;
2083 }
2084
2085 if (RT_SUCCESS(vrc))
2086 vrc = setProgressSuccess();
2087
2088 LogFlowFuncLeaveRC(vrc);
2089 return vrc;
2090}
2091
2092GuestSessionTaskUpdateAdditions::GuestSessionTaskUpdateAdditions(GuestSession *pSession,
2093 const Utf8Str &strSource,
2094 const ProcessArguments &aArguments,
2095 uint32_t fFlags)
2096 : GuestSessionTask(pSession)
2097{
2098 m_strTaskName = "gctlUpGA";
2099
2100 mSource = strSource;
2101 mArguments = aArguments;
2102 mFlags = fFlags;
2103}
2104
2105GuestSessionTaskUpdateAdditions::~GuestSessionTaskUpdateAdditions(void)
2106{
2107
2108}
2109
2110/**
2111 * Adds arguments to existing process arguments.
2112 * Identical / already existing arguments will be filtered out.
2113 *
2114 * @returns VBox status code.
2115 * @param aArgumentsDest Destination to add arguments to.
2116 * @param aArgumentsSource Arguments to add.
2117 */
2118int GuestSessionTaskUpdateAdditions::addProcessArguments(ProcessArguments &aArgumentsDest, const ProcessArguments &aArgumentsSource)
2119{
2120 try
2121 {
2122 /* Filter out arguments which already are in the destination to
2123 * not end up having them specified twice. Not the fastest method on the
2124 * planet but does the job. */
2125 ProcessArguments::const_iterator itSource = aArgumentsSource.begin();
2126 while (itSource != aArgumentsSource.end())
2127 {
2128 bool fFound = false;
2129 ProcessArguments::iterator itDest = aArgumentsDest.begin();
2130 while (itDest != aArgumentsDest.end())
2131 {
2132 if ((*itDest).equalsIgnoreCase((*itSource)))
2133 {
2134 fFound = true;
2135 break;
2136 }
2137 ++itDest;
2138 }
2139
2140 if (!fFound)
2141 aArgumentsDest.push_back((*itSource));
2142
2143 ++itSource;
2144 }
2145 }
2146 catch(std::bad_alloc &)
2147 {
2148 return VERR_NO_MEMORY;
2149 }
2150
2151 return VINF_SUCCESS;
2152}
2153
2154/**
2155 * Helper function to copy a file from a VISO to the guest.
2156 *
2157 * @returns VBox status code.
2158 * @param pSession Guest session to use.
2159 * @param hVfsIso VISO handle to use.
2160 * @param strFileSrc Source file path on VISO to copy.
2161 * @param strFileDst Destination file path on guest.
2162 * @param fOptional When set to \c true, the file is optional, i.e. can be skipped
2163 * when not found, \c false if not.
2164 */
2165int GuestSessionTaskUpdateAdditions::copyFileToGuest(GuestSession *pSession, RTVFS hVfsIso,
2166 Utf8Str const &strFileSrc, const Utf8Str &strFileDst, bool fOptional)
2167{
2168 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
2169 AssertReturn(hVfsIso != NIL_RTVFS, VERR_INVALID_POINTER);
2170
2171 RTVFSFILE hVfsFile = NIL_RTVFSFILE;
2172 int vrc = RTVfsFileOpen(hVfsIso, strFileSrc.c_str(), RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_WRITE, &hVfsFile);
2173 if (RT_SUCCESS(vrc))
2174 {
2175 uint64_t cbSrcSize = 0;
2176 vrc = RTVfsFileQuerySize(hVfsFile, &cbSrcSize);
2177 if (RT_SUCCESS(vrc))
2178 {
2179 LogRel(("Copying Guest Additions installer file \"%s\" to \"%s\" on guest ...\n",
2180 strFileSrc.c_str(), strFileDst.c_str()));
2181
2182 GuestFileOpenInfo dstOpenInfo;
2183 dstOpenInfo.mFilename = strFileDst;
2184 dstOpenInfo.mOpenAction = FileOpenAction_CreateOrReplace;
2185 dstOpenInfo.mAccessMode = FileAccessMode_WriteOnly;
2186 dstOpenInfo.mSharingMode = FileSharingMode_All; /** @todo Use _Read when implemented. */
2187
2188 ComObjPtr<GuestFile> dstFile;
2189 int vrcGuest = VERR_IPE_UNINITIALIZED_STATUS;
2190 vrc = mSession->i_fileOpen(dstOpenInfo, dstFile, &vrcGuest);
2191 if (RT_FAILURE(vrc))
2192 {
2193 switch (vrc)
2194 {
2195 case VERR_GSTCTL_GUEST_ERROR:
2196 setProgressErrorMsg(VBOX_E_IPRT_ERROR, GuestFile::i_guestErrorToString(vrcGuest, strFileDst.c_str()));
2197 break;
2198
2199 default:
2200 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
2201 Utf8StrFmt(tr("Guest file \"%s\" could not be opened: %Rrc"),
2202 strFileDst.c_str(), vrc));
2203 break;
2204 }
2205 }
2206 else
2207 {
2208 vrc = fileCopyToGuestInner(strFileSrc, hVfsFile, strFileDst, dstFile, FileCopyFlag_None, 0 /*offCopy*/, cbSrcSize);
2209
2210 int vrc2 = dstFile->i_closeFile(&vrcGuest);
2211 AssertRC(vrc2);
2212 }
2213 }
2214
2215 RTVfsFileRelease(hVfsFile);
2216 }
2217 else if (fOptional)
2218 vrc = VINF_SUCCESS;
2219
2220 return vrc;
2221}
2222
2223/**
2224 * Helper function to run (start) a file on the guest.
2225 *
2226 * @returns VBox status code.
2227 * @param pSession Guest session to use.
2228 * @param procInfo Guest process startup info to use.
2229 */
2230int GuestSessionTaskUpdateAdditions::runFileOnGuest(GuestSession *pSession, GuestProcessStartupInfo &procInfo)
2231{
2232 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
2233
2234 LogRel(("Running %s ...\n", procInfo.mName.c_str()));
2235
2236 GuestProcessTool procTool;
2237 int vrcGuest = VERR_IPE_UNINITIALIZED_STATUS;
2238 int vrc = procTool.init(pSession, procInfo, false /* Async */, &vrcGuest);
2239 if (RT_SUCCESS(vrc))
2240 {
2241 if (RT_SUCCESS(vrcGuest))
2242 vrc = procTool.wait(GUESTPROCESSTOOL_WAIT_FLAG_NONE, &vrcGuest);
2243 if (RT_SUCCESS(vrc))
2244 vrc = procTool.getTerminationStatus();
2245 }
2246
2247 if (RT_FAILURE(vrc))
2248 {
2249 switch (vrc)
2250 {
2251 case VERR_GSTCTL_PROCESS_EXIT_CODE:
2252 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
2253 Utf8StrFmt(tr("Running update file \"%s\" on guest failed: %Rrc"),
2254 procInfo.mExecutable.c_str(), procTool.getRc()));
2255 break;
2256
2257 case VERR_GSTCTL_GUEST_ERROR:
2258 setProgressErrorMsg(VBOX_E_IPRT_ERROR, tr("Running update file on guest failed"),
2259 GuestErrorInfo(GuestErrorInfo::Type_Process, vrcGuest, procInfo.mExecutable.c_str()));
2260 break;
2261
2262 case VERR_INVALID_STATE: /** @todo Special guest control rc needed! */
2263 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
2264 Utf8StrFmt(tr("Update file \"%s\" reported invalid running state"),
2265 procInfo.mExecutable.c_str()));
2266 break;
2267
2268 default:
2269 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
2270 Utf8StrFmt(tr("Error while running update file \"%s\" on guest: %Rrc"),
2271 procInfo.mExecutable.c_str(), vrc));
2272 break;
2273 }
2274 }
2275
2276 return vrc;
2277}
2278
2279/** @copydoc GuestSessionTask::Run */
2280int GuestSessionTaskUpdateAdditions::Run(void)
2281{
2282 LogFlowThisFuncEnter();
2283
2284 ComObjPtr<GuestSession> pSession = mSession;
2285 Assert(!pSession.isNull());
2286
2287 AutoCaller autoCaller(pSession);
2288 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2289
2290 int vrc = setProgress(10);
2291 if (RT_FAILURE(vrc))
2292 return vrc;
2293
2294 HRESULT hrc = S_OK;
2295
2296 LogRel(("Automatic update of Guest Additions started, using \"%s\"\n", mSource.c_str()));
2297
2298 ComObjPtr<Guest> pGuest(mSession->i_getParent());
2299#if 0
2300 /*
2301 * Wait for the guest being ready within 30 seconds.
2302 */
2303 AdditionsRunLevelType_T addsRunLevel;
2304 uint64_t tsStart = RTTimeSystemMilliTS();
2305 while ( SUCCEEDED(hrc = pGuest->COMGETTER(AdditionsRunLevel)(&addsRunLevel))
2306 && ( addsRunLevel != AdditionsRunLevelType_Userland
2307 && addsRunLevel != AdditionsRunLevelType_Desktop))
2308 {
2309 if ((RTTimeSystemMilliTS() - tsStart) > 30 * 1000)
2310 {
2311 vrc = VERR_TIMEOUT;
2312 break;
2313 }
2314
2315 RTThreadSleep(100); /* Wait a bit. */
2316 }
2317
2318 if (FAILED(hrc)) vrc = VERR_TIMEOUT;
2319 if (vrc == VERR_TIMEOUT)
2320 hrc = setProgressErrorMsg(VBOX_E_NOT_SUPPORTED,
2321 Utf8StrFmt(tr("Guest Additions were not ready within time, giving up")));
2322#else
2323 /*
2324 * For use with the GUI we don't want to wait, just return so that the manual .ISO mounting
2325 * can continue.
2326 */
2327 AdditionsRunLevelType_T addsRunLevel;
2328 if ( FAILED(hrc = pGuest->COMGETTER(AdditionsRunLevel)(&addsRunLevel))
2329 || ( addsRunLevel != AdditionsRunLevelType_Userland
2330 && addsRunLevel != AdditionsRunLevelType_Desktop))
2331 {
2332 if (addsRunLevel == AdditionsRunLevelType_System)
2333 hrc = setProgressErrorMsg(VBOX_E_NOT_SUPPORTED,
2334 Utf8StrFmt(tr("Guest Additions are installed but not fully loaded yet, aborting automatic update")));
2335 else
2336 hrc = setProgressErrorMsg(VBOX_E_NOT_SUPPORTED,
2337 Utf8StrFmt(tr("Guest Additions not installed or ready, aborting automatic update")));
2338 vrc = VERR_NOT_SUPPORTED;
2339 }
2340#endif
2341
2342 if (RT_SUCCESS(vrc))
2343 {
2344 /*
2345 * Determine if we are able to update automatically. This only works
2346 * if there are recent Guest Additions installed already.
2347 */
2348 Utf8Str strAddsVer;
2349 vrc = getGuestProperty(pGuest, "/VirtualBox/GuestAdd/Version", strAddsVer);
2350 if ( RT_SUCCESS(vrc)
2351 && RTStrVersionCompare(strAddsVer.c_str(), "4.1") < 0)
2352 {
2353 hrc = setProgressErrorMsg(VBOX_E_NOT_SUPPORTED,
2354 Utf8StrFmt(tr("Guest has too old Guest Additions (%s) installed for automatic updating, please update manually"),
2355 strAddsVer.c_str()));
2356 vrc = VERR_NOT_SUPPORTED;
2357 }
2358 }
2359
2360 Utf8Str strOSVer;
2361 eOSType osType = eOSType_Unknown;
2362 if (RT_SUCCESS(vrc))
2363 {
2364 /*
2365 * Determine guest OS type and the required installer image.
2366 */
2367 Utf8Str strOSType;
2368 vrc = getGuestProperty(pGuest, "/VirtualBox/GuestInfo/OS/Product", strOSType);
2369 if (RT_SUCCESS(vrc))
2370 {
2371 if ( strOSType.contains("Microsoft", Utf8Str::CaseInsensitive)
2372 || strOSType.contains("Windows", Utf8Str::CaseInsensitive))
2373 {
2374 osType = eOSType_Windows;
2375
2376 /*
2377 * Determine guest OS version.
2378 */
2379 vrc = getGuestProperty(pGuest, "/VirtualBox/GuestInfo/OS/Release", strOSVer);
2380 if (RT_FAILURE(vrc))
2381 {
2382 hrc = setProgressErrorMsg(VBOX_E_NOT_SUPPORTED,
2383 Utf8StrFmt(tr("Unable to detected guest OS version, please update manually")));
2384 vrc = VERR_NOT_SUPPORTED;
2385 }
2386
2387 /* Because Windows 2000 + XP and is bitching with WHQL popups even if we have signed drivers we
2388 * can't do automated updates here. */
2389 /* Windows XP 64-bit (5.2) is a Windows 2003 Server actually, so skip this here. */
2390 if ( RT_SUCCESS(vrc)
2391 && RTStrVersionCompare(strOSVer.c_str(), "5.0") >= 0)
2392 {
2393 if ( strOSVer.startsWith("5.0") /* Exclude the build number. */
2394 || strOSVer.startsWith("5.1") /* Exclude the build number. */)
2395 {
2396 /* If we don't have AdditionsUpdateFlag_WaitForUpdateStartOnly set we can't continue
2397 * because the Windows Guest Additions installer will fail because of WHQL popups. If the
2398 * flag is set this update routine ends successfully as soon as the installer was started
2399 * (and the user has to deal with it in the guest). */
2400 if (!(mFlags & AdditionsUpdateFlag_WaitForUpdateStartOnly))
2401 {
2402 hrc = setProgressErrorMsg(VBOX_E_NOT_SUPPORTED,
2403 Utf8StrFmt(tr("Windows 2000 and XP are not supported for automatic updating due to WHQL interaction, please update manually")));
2404 vrc = VERR_NOT_SUPPORTED;
2405 }
2406 }
2407 }
2408 else
2409 {
2410 hrc = setProgressErrorMsg(VBOX_E_NOT_SUPPORTED,
2411 Utf8StrFmt(tr("%s (%s) not supported for automatic updating, please update manually"),
2412 strOSType.c_str(), strOSVer.c_str()));
2413 vrc = VERR_NOT_SUPPORTED;
2414 }
2415 }
2416 else if (strOSType.contains("Solaris", Utf8Str::CaseInsensitive))
2417 {
2418 osType = eOSType_Solaris;
2419 }
2420 else /* Everything else hopefully means Linux :-). */
2421 osType = eOSType_Linux;
2422
2423 if ( RT_SUCCESS(vrc)
2424 && ( osType != eOSType_Windows
2425 && osType != eOSType_Linux))
2426 /** @todo Support Solaris. */
2427 {
2428 hrc = setProgressErrorMsg(VBOX_E_NOT_SUPPORTED,
2429 Utf8StrFmt(tr("Detected guest OS (%s) does not support automatic Guest Additions updating, please update manually"),
2430 strOSType.c_str()));
2431 vrc = VERR_NOT_SUPPORTED;
2432 }
2433 }
2434 }
2435
2436 if (RT_SUCCESS(vrc))
2437 {
2438 /*
2439 * Try to open the .ISO file to extract all needed files.
2440 */
2441 RTVFSFILE hVfsFileIso;
2442 vrc = RTVfsFileOpenNormal(mSource.c_str(), RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_WRITE, &hVfsFileIso);
2443 if (RT_FAILURE(vrc))
2444 {
2445 hrc = setProgressErrorMsg(VBOX_E_IPRT_ERROR,
2446 Utf8StrFmt(tr("Unable to open Guest Additions .ISO file \"%s\": %Rrc"),
2447 mSource.c_str(), vrc));
2448 }
2449 else
2450 {
2451 RTVFS hVfsIso;
2452 vrc = RTFsIso9660VolOpen(hVfsFileIso, 0 /*fFlags*/, &hVfsIso, NULL);
2453 if (RT_FAILURE(vrc))
2454 {
2455 hrc = setProgressErrorMsg(VBOX_E_IPRT_ERROR,
2456 Utf8StrFmt(tr("Unable to open file as ISO 9660 file system volume: %Rrc"), vrc));
2457 }
2458 else
2459 {
2460 Utf8Str strUpdateDir;
2461
2462 vrc = setProgress(5);
2463 if (RT_SUCCESS(vrc))
2464 {
2465 /* Try getting the installed Guest Additions version to know whether we
2466 * can install our temporary Guest Addition data into the original installation
2467 * directory.
2468 *
2469 * Because versions prior to 4.2 had bugs wrt spaces in paths we have to choose
2470 * a different location then.
2471 */
2472 bool fUseInstallDir = false;
2473
2474 Utf8Str strAddsVer;
2475 vrc = getGuestProperty(pGuest, "/VirtualBox/GuestAdd/Version", strAddsVer);
2476 if ( RT_SUCCESS(vrc)
2477 && RTStrVersionCompare(strAddsVer.c_str(), "4.2r80329") > 0)
2478 {
2479 fUseInstallDir = true;
2480 }
2481
2482 if (fUseInstallDir)
2483 {
2484 vrc = getGuestProperty(pGuest, "/VirtualBox/GuestAdd/InstallDir", strUpdateDir);
2485 if (RT_SUCCESS(vrc))
2486 {
2487 if (strUpdateDir.isNotEmpty())
2488 {
2489 if (osType == eOSType_Windows)
2490 {
2491 strUpdateDir.findReplace('/', '\\');
2492 strUpdateDir.append("\\Update\\");
2493 }
2494 else
2495 strUpdateDir.append("/update/");
2496 }
2497 /* else Older Guest Additions might not handle this property correctly. */
2498 }
2499 /* Ditto. */
2500 }
2501
2502 /** @todo Set fallback installation directory. Make this a *lot* smarter. Later. */
2503 if (strUpdateDir.isEmpty())
2504 {
2505 if (osType == eOSType_Windows)
2506 strUpdateDir = "C:\\Temp\\";
2507 else
2508 strUpdateDir = "/tmp/";
2509 }
2510 }
2511
2512 /* Create the installation directory. */
2513 int vrcGuest = VERR_IPE_UNINITIALIZED_STATUS;
2514 if (RT_SUCCESS(vrc))
2515 {
2516 LogRel(("Guest Additions update directory is: %s\n", strUpdateDir.c_str()));
2517
2518 vrc = pSession->i_directoryCreate(strUpdateDir, 755 /* Mode */, DirectoryCreateFlag_Parents, &vrcGuest);
2519 if (RT_FAILURE(vrc))
2520 {
2521 switch (vrc)
2522 {
2523 case VERR_GSTCTL_GUEST_ERROR:
2524 hrc = setProgressErrorMsg(VBOX_E_IPRT_ERROR, tr("Creating installation directory on guest failed"),
2525 GuestErrorInfo(GuestErrorInfo::Type_Directory, vrcGuest, strUpdateDir.c_str()));
2526 break;
2527
2528 default:
2529 hrc = setProgressErrorMsg(VBOX_E_IPRT_ERROR,
2530 Utf8StrFmt(tr("Creating installation directory \"%s\" on guest failed: %Rrc"),
2531 strUpdateDir.c_str(), vrc));
2532 break;
2533 }
2534 }
2535 }
2536
2537 if (RT_SUCCESS(vrc))
2538 vrc = setProgress(10);
2539
2540 if (RT_SUCCESS(vrc))
2541 {
2542 /* Prepare the file(s) we want to copy over to the guest and
2543 * (maybe) want to run. */
2544 switch (osType)
2545 {
2546 case eOSType_Windows:
2547 {
2548 /* Do we need to install our certificates? We do this for W2K and up. */
2549 bool fInstallCert = false;
2550
2551 /* Only Windows 2000 and up need certificates to be installed. */
2552 if (RTStrVersionCompare(strOSVer.c_str(), "5.0") >= 0)
2553 {
2554 fInstallCert = true;
2555 LogRel(("Certificates for auto updating WHQL drivers will be installed\n"));
2556 }
2557 else
2558 LogRel(("Skipping installation of certificates for WHQL drivers\n"));
2559
2560 if (fInstallCert)
2561 {
2562 static struct { const char *pszDst, *pszIso; } const s_aCertFiles[] =
2563 {
2564 { "vbox.cer", "/CERT/VBOX.CER" },
2565 { "vbox-sha1.cer", "/CERT/VBOX-SHA1.CER" },
2566 { "vbox-sha256.cer", "/CERT/VBOX-SHA256.CER" },
2567 { "vbox-sha256-r3.cer", "/CERT/VBOX-SHA256-R3.CER" },
2568 { "oracle-vbox.cer", "/CERT/ORACLE-VBOX.CER" },
2569 };
2570 uint32_t fCopyCertUtil = ISOFILE_FLAG_COPY_FROM_ISO;
2571 for (uint32_t i = 0; i < RT_ELEMENTS(s_aCertFiles); i++)
2572 {
2573 /* Skip if not present on the ISO. */
2574 RTFSOBJINFO ObjInfo;
2575 vrc = RTVfsQueryPathInfo(hVfsIso, s_aCertFiles[i].pszIso, &ObjInfo, RTFSOBJATTRADD_NOTHING,
2576 RTPATH_F_ON_LINK);
2577 if (RT_FAILURE(vrc))
2578 continue;
2579
2580 /* Copy the certificate certificate. */
2581 Utf8Str const strDstCert(strUpdateDir + s_aCertFiles[i].pszDst);
2582 mFiles.push_back(ISOFile(s_aCertFiles[i].pszIso,
2583 strDstCert,
2584 ISOFILE_FLAG_COPY_FROM_ISO | ISOFILE_FLAG_OPTIONAL));
2585
2586 /* Out certificate installation utility. */
2587 /* First pass: Copy over the file (first time only) + execute it to remove any
2588 * existing VBox certificates. */
2589 GuestProcessStartupInfo siCertUtilRem;
2590 siCertUtilRem.mName = "VirtualBox Certificate Utility, removing old VirtualBox certificates";
2591 /* The argv[0] should contain full path to the executable module */
2592 siCertUtilRem.mArguments.push_back(strUpdateDir + "VBoxCertUtil.exe");
2593 siCertUtilRem.mArguments.push_back(Utf8Str("remove-trusted-publisher"));
2594 siCertUtilRem.mArguments.push_back(Utf8Str("--root")); /* Add root certificate as well. */
2595 siCertUtilRem.mArguments.push_back(strDstCert);
2596 siCertUtilRem.mArguments.push_back(strDstCert);
2597 mFiles.push_back(ISOFile("CERT/VBOXCERTUTIL.EXE",
2598 strUpdateDir + "VBoxCertUtil.exe",
2599 fCopyCertUtil | ISOFILE_FLAG_EXECUTE | ISOFILE_FLAG_OPTIONAL,
2600 siCertUtilRem));
2601 fCopyCertUtil = 0;
2602 /* Second pass: Only execute (but don't copy) again, this time installng the
2603 * recent certificates just copied over. */
2604 GuestProcessStartupInfo siCertUtilAdd;
2605 siCertUtilAdd.mName = "VirtualBox Certificate Utility, installing VirtualBox certificates";
2606 /* The argv[0] should contain full path to the executable module */
2607 siCertUtilAdd.mArguments.push_back(strUpdateDir + "VBoxCertUtil.exe");
2608 siCertUtilAdd.mArguments.push_back(Utf8Str("add-trusted-publisher"));
2609 siCertUtilAdd.mArguments.push_back(Utf8Str("--root")); /* Add root certificate as well. */
2610 siCertUtilAdd.mArguments.push_back(strDstCert);
2611 siCertUtilAdd.mArguments.push_back(strDstCert);
2612 mFiles.push_back(ISOFile("CERT/VBOXCERTUTIL.EXE",
2613 strUpdateDir + "VBoxCertUtil.exe",
2614 ISOFILE_FLAG_EXECUTE | ISOFILE_FLAG_OPTIONAL,
2615 siCertUtilAdd));
2616 }
2617 }
2618 /* The installers in different flavors, as we don't know (and can't assume)
2619 * the guest's bitness. */
2620 mFiles.push_back(ISOFile("VBOXWINDOWSADDITIONS-X86.EXE",
2621 strUpdateDir + "VBoxWindowsAdditions-x86.exe",
2622 ISOFILE_FLAG_COPY_FROM_ISO));
2623 mFiles.push_back(ISOFile("VBOXWINDOWSADDITIONS-AMD64.EXE",
2624 strUpdateDir + "VBoxWindowsAdditions-amd64.exe",
2625 ISOFILE_FLAG_COPY_FROM_ISO));
2626 /* The stub loader which decides which flavor to run. */
2627 GuestProcessStartupInfo siInstaller;
2628 siInstaller.mName = "VirtualBox Windows Guest Additions Installer";
2629 /* Set a running timeout of 5 minutes -- the Windows Guest Additions
2630 * setup can take quite a while, so be on the safe side. */
2631 siInstaller.mTimeoutMS = 5 * 60 * 1000;
2632
2633 /* The argv[0] should contain full path to the executable module */
2634 siInstaller.mArguments.push_back(strUpdateDir + "VBoxWindowsAdditions.exe");
2635 siInstaller.mArguments.push_back(Utf8Str("/S")); /* We want to install in silent mode. */
2636 siInstaller.mArguments.push_back(Utf8Str("/l")); /* ... and logging enabled. */
2637 /* Don't quit VBoxService during upgrade because it still is used for this
2638 * piece of code we're in right now (that is, here!) ... */
2639 siInstaller.mArguments.push_back(Utf8Str("/no_vboxservice_exit"));
2640 /* Tell the installer to report its current installation status
2641 * using a running VBoxTray instance via balloon messages in the
2642 * Windows taskbar. */
2643 siInstaller.mArguments.push_back(Utf8Str("/post_installstatus"));
2644 /* Add optional installer command line arguments from the API to the
2645 * installer's startup info. */
2646 vrc = addProcessArguments(siInstaller.mArguments, mArguments);
2647 AssertRC(vrc);
2648 /* If the caller does not want to wait for out guest update process to end,
2649 * complete the progress object now so that the caller can do other work. */
2650 if (mFlags & AdditionsUpdateFlag_WaitForUpdateStartOnly)
2651 siInstaller.mFlags |= ProcessCreateFlag_WaitForProcessStartOnly;
2652 mFiles.push_back(ISOFile("VBOXWINDOWSADDITIONS.EXE",
2653 strUpdateDir + "VBoxWindowsAdditions.exe",
2654 ISOFILE_FLAG_COPY_FROM_ISO | ISOFILE_FLAG_EXECUTE, siInstaller));
2655 break;
2656 }
2657 case eOSType_Linux:
2658 {
2659 /* Copy over the installer to the guest but don't execute it.
2660 * Execution will be done by the shell instead. */
2661 mFiles.push_back(ISOFile("VBOXLINUXADDITIONS.RUN",
2662 strUpdateDir + "VBoxLinuxAdditions.run", ISOFILE_FLAG_COPY_FROM_ISO));
2663
2664 GuestProcessStartupInfo siInstaller;
2665 siInstaller.mName = "VirtualBox Linux Guest Additions Installer";
2666 /* Set a running timeout of 5 minutes -- compiling modules and stuff for the Linux Guest Additions
2667 * setup can take quite a while, so be on the safe side. */
2668 siInstaller.mTimeoutMS = 5 * 60 * 1000;
2669 /* The argv[0] should contain full path to the shell we're using to execute the installer. */
2670 siInstaller.mArguments.push_back("/bin/sh");
2671 /* Now add the stuff we need in order to execute the installer. */
2672 siInstaller.mArguments.push_back(strUpdateDir + "VBoxLinuxAdditions.run");
2673 /* Make sure to add "--nox11" to the makeself wrapper in order to not getting any blocking xterm
2674 * window spawned when doing any unattended Linux GA installations. */
2675 siInstaller.mArguments.push_back("--nox11");
2676 siInstaller.mArguments.push_back("--");
2677 /* Force the upgrade. Needed in order to skip the confirmation dialog about warning to upgrade. */
2678 siInstaller.mArguments.push_back("--force"); /** @todo We might want a dedicated "--silent" switch here. */
2679 /* If the caller does not want to wait for out guest update process to end,
2680 * complete the progress object now so that the caller can do other work. */
2681 if (mFlags & AdditionsUpdateFlag_WaitForUpdateStartOnly)
2682 siInstaller.mFlags |= ProcessCreateFlag_WaitForProcessStartOnly;
2683 mFiles.push_back(ISOFile("/bin/sh" /* Source */, "/bin/sh" /* Dest */,
2684 ISOFILE_FLAG_EXECUTE, siInstaller));
2685 break;
2686 }
2687 case eOSType_Solaris:
2688 /** @todo Add Solaris support. */
2689 break;
2690 default:
2691 AssertReleaseMsgFailed(("Unsupported guest type: %d\n", osType));
2692 break;
2693 }
2694 }
2695
2696 if (RT_SUCCESS(vrc))
2697 {
2698 /* We want to spend 40% total for all copying operations. So roughly
2699 * calculate the specific percentage step of each copied file. */
2700 uint8_t uOffset = 20; /* Start at 20%. */
2701 uint8_t uStep = 40 / (uint8_t)mFiles.size(); Assert(mFiles.size() <= 10);
2702
2703 LogRel(("Copying over Guest Additions update files to the guest ...\n"));
2704
2705 std::vector<ISOFile>::const_iterator itFiles = mFiles.begin();
2706 while (itFiles != mFiles.end())
2707 {
2708 if (itFiles->fFlags & ISOFILE_FLAG_COPY_FROM_ISO)
2709 {
2710 bool fOptional = false;
2711 if (itFiles->fFlags & ISOFILE_FLAG_OPTIONAL)
2712 fOptional = true;
2713 vrc = copyFileToGuest(pSession, hVfsIso, itFiles->strSource, itFiles->strDest, fOptional);
2714 if (RT_FAILURE(vrc))
2715 {
2716 hrc = setProgressErrorMsg(VBOX_E_IPRT_ERROR,
2717 Utf8StrFmt(tr("Error while copying file \"%s\" to \"%s\" on the guest: %Rrc"),
2718 itFiles->strSource.c_str(), itFiles->strDest.c_str(), vrc));
2719 break;
2720 }
2721 }
2722
2723 vrc = setProgress(uOffset);
2724 if (RT_FAILURE(vrc))
2725 break;
2726 uOffset += uStep;
2727
2728 ++itFiles;
2729 }
2730 }
2731
2732 /* Done copying, close .ISO file. */
2733 RTVfsRelease(hVfsIso);
2734
2735 if (RT_SUCCESS(vrc))
2736 {
2737 /* We want to spend 35% total for all copying operations. So roughly
2738 * calculate the specific percentage step of each copied file. */
2739 uint8_t uOffset = 60; /* Start at 60%. */
2740 uint8_t uStep = 35 / (uint8_t)mFiles.size(); Assert(mFiles.size() <= 10);
2741
2742 LogRel(("Executing Guest Additions update files ...\n"));
2743
2744 std::vector<ISOFile>::iterator itFiles = mFiles.begin();
2745 while (itFiles != mFiles.end())
2746 {
2747 if (itFiles->fFlags & ISOFILE_FLAG_EXECUTE)
2748 {
2749 vrc = runFileOnGuest(pSession, itFiles->mProcInfo);
2750 if (RT_FAILURE(vrc))
2751 break;
2752 }
2753
2754 vrc = setProgress(uOffset);
2755 if (RT_FAILURE(vrc))
2756 break;
2757 uOffset += uStep;
2758
2759 ++itFiles;
2760 }
2761 }
2762
2763 if (RT_SUCCESS(vrc))
2764 {
2765 LogRel(("Automatic update of Guest Additions succeeded\n"));
2766 vrc = setProgressSuccess();
2767 }
2768 }
2769
2770 RTVfsFileRelease(hVfsFileIso);
2771 }
2772 }
2773
2774 if (RT_FAILURE(vrc))
2775 {
2776 if (vrc == VERR_CANCELLED)
2777 {
2778 LogRel(("Automatic update of Guest Additions was canceled\n"));
2779
2780 hrc = setProgressErrorMsg(VBOX_E_IPRT_ERROR,
2781 Utf8StrFmt(tr("Installation was canceled")));
2782 }
2783 else
2784 {
2785 Utf8Str strError = Utf8StrFmt("No further error information available (%Rrc)", vrc);
2786 if (!mProgress.isNull()) /* Progress object is optional. */
2787 {
2788#ifdef VBOX_STRICT
2789 /* If we forgot to set the progress object accordingly, let us know. */
2790 LONG rcProgress;
2791 AssertMsg( SUCCEEDED(mProgress->COMGETTER(ResultCode(&rcProgress)))
2792 && FAILED(rcProgress), ("Task indicated an error (%Rrc), but progress did not indicate this (%Rhrc)\n",
2793 vrc, rcProgress));
2794#endif
2795 com::ProgressErrorInfo errorInfo(mProgress);
2796 if ( errorInfo.isFullAvailable()
2797 || errorInfo.isBasicAvailable())
2798 {
2799 strError = errorInfo.getText();
2800 }
2801 }
2802
2803 LogRel(("Automatic update of Guest Additions failed: %s (%Rhrc)\n",
2804 strError.c_str(), hrc));
2805 }
2806
2807 LogRel(("Please install Guest Additions manually\n"));
2808 }
2809
2810 /** @todo Clean up copied / left over installation files. */
2811
2812 LogFlowFuncLeaveRC(vrc);
2813 return vrc;
2814}
2815
Note: See TracBrowser for help on using the repository browser.

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