VirtualBox

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

Last change on this file since 104636 was 104636, checked in by vboxsync, 7 months ago

Main: Improved release logging of Guest Additions auto update. Unified logging prefix for simpler lookup.

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