VirtualBox

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

Last change on this file since 107644 was 107585, checked in by vboxsync, 3 months ago

src/VBox/Main/src-client/GuestSessionImplTasks.cpp: Fixed warnings found by Parfait (assignment unused). jiraref:VBP-1424

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 138.3 KB
Line 
1/* $Id: GuestSessionImplTasks.cpp 107585 2025-01-09 10:23:37Z vboxsync $ */
2/** @file
3 * VirtualBox Main - Guest session tasks.
4 */
5
6/*
7 * Copyright (C) 2012-2024 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 , mcbTotalSize(0)
1047{
1048}
1049
1050FsList::~FsList()
1051{
1052 Destroy();
1053}
1054
1055/**
1056 * Initializes a file list.
1057 *
1058 * @return VBox status code.
1059 * @param strSrcRootAbs Source root path (absolute) for this file list.
1060 * @param strDstRootAbs Destination root path (absolute) for this file list.
1061 * @param SourceSpec Source specification to use.
1062 */
1063int FsList::Init(const Utf8Str &strSrcRootAbs, const Utf8Str &strDstRootAbs,
1064 const GuestSessionFsSourceSpec &SourceSpec)
1065{
1066 mSrcRootAbs = strSrcRootAbs;
1067 mDstRootAbs = strDstRootAbs;
1068 mSourceSpec = SourceSpec;
1069
1070 /* Note: Leave the source and dest roots unmodified -- how paths will be treated
1071 * will be done directly when working on those. See @bugref{10139}. */
1072
1073 LogFlowFunc(("mSrcRootAbs=%s, mDstRootAbs=%s, fDirCopyFlags=%#x, fFileCopyFlags=%#x\n",
1074 mSrcRootAbs.c_str(), mDstRootAbs.c_str(), mSourceSpec.fDirCopyFlags, mSourceSpec.fFileCopyFlags));
1075
1076 return VINF_SUCCESS;
1077}
1078
1079/**
1080 * Destroys a file list.
1081 */
1082void FsList::Destroy(void)
1083{
1084 LogFlowFuncEnter();
1085
1086 FsEntries::iterator itEntry = mVecEntries.begin();
1087 while (itEntry != mVecEntries.end())
1088 {
1089 FsEntry *pEntry = *itEntry;
1090 delete pEntry;
1091 mVecEntries.erase(itEntry);
1092 itEntry = mVecEntries.begin();
1093 }
1094
1095 Assert(mVecEntries.empty());
1096
1097 LogFlowFuncLeave();
1098}
1099
1100#ifdef DEBUG
1101/**
1102 * Dumps a FsList to the debug log.
1103 */
1104void FsList::DumpToLog(void)
1105{
1106 LogFlowFunc(("strSrcRootAbs=%s, strDstRootAbs=%s\n", mSrcRootAbs.c_str(), mDstRootAbs.c_str()));
1107
1108 FsEntries::iterator itEntry = mVecEntries.begin();
1109 while (itEntry != mVecEntries.end())
1110 {
1111 FsEntry *pEntry = *itEntry;
1112 LogFlowFunc(("\tstrPath=%s (fMode %#x)\n", pEntry->strPath.c_str(), pEntry->fMode));
1113 ++itEntry;
1114 }
1115
1116 LogFlowFuncLeave();
1117}
1118#endif /* DEBUG */
1119
1120/**
1121 * Builds a guest file list from a given path (and optional filter).
1122 *
1123 * @return VBox status code.
1124 * @param strPath Directory on the guest to build list from.
1125 * @param strSubDir Current sub directory path; needed for recursion.
1126 * Set to an empty path.
1127 */
1128int FsList::AddDirFromGuest(const Utf8Str &strPath, const Utf8Str &strSubDir /* = "" */)
1129{
1130 Utf8Str strPathAbs = strPath;
1131 if (!strPathAbs.endsWith(PATH_STYLE_SEP_STR(mSourceSpec.enmPathStyle)))
1132 strPathAbs += PATH_STYLE_SEP_STR(mSourceSpec.enmPathStyle);
1133
1134 Utf8Str strPathSub = strSubDir;
1135 if ( strPathSub.isNotEmpty()
1136 && !strPathSub.endsWith(PATH_STYLE_SEP_STR(mSourceSpec.enmPathStyle)))
1137 strPathSub += PATH_STYLE_SEP_STR(mSourceSpec.enmPathStyle);
1138
1139 strPathAbs += strPathSub;
1140
1141 LogFlowFunc(("Entering \"%s\" (sub \"%s\")\n", strPathAbs.c_str(), strPathSub.c_str()));
1142
1143 LogRel2(("Guest Control: Handling directory \"%s\" on guest ...\n", strPathAbs.c_str()));
1144
1145 GuestDirectoryOpenInfo dirOpenInfo;
1146 dirOpenInfo.mFilter = "";
1147 dirOpenInfo.mPath = strPathAbs;
1148 dirOpenInfo.mFlags = 0; /** @todo Handle flags? */
1149
1150 const ComObjPtr<GuestSession> &pSession = mTask.GetSession();
1151
1152 ComObjPtr <GuestDirectory> pDir;
1153 int vrcGuest = VERR_IPE_UNINITIALIZED_STATUS;
1154 int vrc = pSession->i_directoryOpen(dirOpenInfo, pDir, &vrcGuest);
1155 if (RT_FAILURE(vrc))
1156 {
1157 switch (vrc)
1158 {
1159 case VERR_INVALID_PARAMETER:
1160 break;
1161
1162 case VERR_GSTCTL_GUEST_ERROR:
1163 break;
1164
1165 default:
1166 break;
1167 }
1168
1169 return vrc;
1170 }
1171
1172 if (strPathSub.isNotEmpty())
1173 {
1174 GuestFsObjData fsObjData;
1175 fsObjData.mType = FsObjType_Directory;
1176
1177 vrc = AddEntryFromGuest(strPathSub, fsObjData);
1178 }
1179
1180 if (RT_SUCCESS(vrc))
1181 {
1182 ComObjPtr<GuestFsObjInfo> fsObjInfo;
1183 while (RT_SUCCESS(vrc = pDir->i_read(fsObjInfo, &vrcGuest)))
1184 {
1185 FsObjType_T enmObjType = FsObjType_Unknown; /* Shut up MSC. */
1186 HRESULT hrc2 = fsObjInfo->COMGETTER(Type)(&enmObjType);
1187 AssertComRC(hrc2);
1188
1189 com::Bstr bstrName;
1190 hrc2 = fsObjInfo->COMGETTER(Name)(bstrName.asOutParam());
1191 AssertComRC(hrc2);
1192
1193 Utf8Str strEntry = strPathSub + Utf8Str(bstrName);
1194
1195 LogFlowFunc(("Entry \"%s\"\n", strEntry.c_str()));
1196
1197 switch (enmObjType)
1198 {
1199 case FsObjType_Directory:
1200 {
1201 if ( bstrName.equals(".")
1202 || bstrName.equals(".."))
1203 {
1204 break;
1205 }
1206
1207 LogRel2(("Guest Control: Directory \"%s\"\n", strEntry.c_str()));
1208
1209 if (!(mSourceSpec.fDirCopyFlags & DirectoryCopyFlag_Recursive))
1210 break;
1211
1212 vrc = AddDirFromGuest(strPath, strEntry);
1213 break;
1214 }
1215
1216 case FsObjType_Symlink:
1217 {
1218 if ( mSourceSpec.fDirCopyFlags & DirectoryCopyFlag_FollowLinks
1219 || mSourceSpec.fFileCopyFlags & FileCopyFlag_FollowLinks)
1220 {
1221 /** @todo Symlink handling from guest is not implemented yet.
1222 * See IGuestSession::symlinkRead(). */
1223 LogRel2(("Guest Control: Warning: Symlink support on guest side not available, skipping \"%s\"\n",
1224 strEntry.c_str()));
1225 }
1226 break;
1227 }
1228
1229 case FsObjType_File:
1230 {
1231 LogRel2(("Guest Control: File \"%s\"\n", strEntry.c_str()));
1232
1233 vrc = AddEntryFromGuest(strEntry, fsObjInfo->i_getData());
1234 break;
1235 }
1236
1237 default:
1238 break;
1239 }
1240
1241 if (RT_FAILURE(vrc))
1242 break;
1243 }
1244
1245 if ( vrc == VERR_GSTCTL_GUEST_ERROR
1246 && vrcGuest == VERR_NO_MORE_FILES) /* End of listing reached? */
1247 vrc = VINF_SUCCESS;
1248 }
1249
1250 int vrc2 = pDir->i_close(&vrcGuest);
1251 if (RT_SUCCESS(vrc))
1252 vrc = vrc2;
1253
1254 return vrc;
1255}
1256
1257/**
1258 * Builds a host file list from a given path.
1259 *
1260 * @return VBox status code.
1261 * @param strPath Directory on the host to build list from.
1262 * @param strSubDir Current sub directory path; needed for recursion.
1263 * Set to an empty path.
1264 * @param pszPathReal Scratch buffer for holding the resolved real path.
1265 * Needed for recursion.
1266 * @param cbPathReal Size (in bytes) of \a pszPathReal.
1267 * @param pDirEntry Where to store looked up directory information for handled paths.
1268 * Needed for recursion.
1269 */
1270int FsList::AddDirFromHost(const Utf8Str &strPath, const Utf8Str &strSubDir,
1271 char *pszPathReal, size_t cbPathReal, PRTDIRENTRYEX pDirEntry)
1272{
1273 Utf8Str strPathAbs = strPath;
1274 if (!strPathAbs.endsWith(RTPATH_SLASH_STR))
1275 strPathAbs += RTPATH_SLASH_STR;
1276
1277 Utf8Str strPathSub = strSubDir;
1278 if ( strPathSub.isNotEmpty()
1279 && !strPathSub.endsWith(RTPATH_SLASH_STR))
1280 strPathSub += RTPATH_SLASH_STR;
1281
1282 strPathAbs += strPathSub;
1283
1284 LogFlowFunc(("Entering \"%s\" (sub \"%s\")\n", strPathAbs.c_str(), strPathSub.c_str()));
1285
1286 LogRel2(("Guest Control: Handling directory \"%s\" on host ...\n", strPathAbs.c_str()));
1287
1288 RTFSOBJINFO objInfo;
1289 int vrc = RTPathQueryInfo(strPathAbs.c_str(), &objInfo, RTFSOBJATTRADD_NOTHING);
1290 if (RT_SUCCESS(vrc))
1291 {
1292 if (RTFS_IS_DIRECTORY(objInfo.Attr.fMode))
1293 {
1294 if (strPathSub.isNotEmpty())
1295 vrc = AddEntryFromHost(strPathSub, &objInfo);
1296
1297 if (RT_SUCCESS(vrc))
1298 {
1299 RTDIR hDir;
1300 vrc = RTDirOpen(&hDir, strPathAbs.c_str());
1301 if (RT_SUCCESS(vrc))
1302 {
1303 do
1304 {
1305 /* Retrieve the next directory entry. */
1306 vrc = RTDirReadEx(hDir, pDirEntry, NULL, RTFSOBJATTRADD_NOTHING, RTPATH_F_ON_LINK);
1307 if (RT_FAILURE(vrc))
1308 {
1309 if (vrc == VERR_NO_MORE_FILES)
1310 vrc = VINF_SUCCESS;
1311 break;
1312 }
1313
1314 Utf8Str strEntry = strPathSub + Utf8Str(pDirEntry->szName);
1315
1316 LogFlowFunc(("Entry \"%s\"\n", strEntry.c_str()));
1317
1318 switch (pDirEntry->Info.Attr.fMode & RTFS_TYPE_MASK)
1319 {
1320 case RTFS_TYPE_DIRECTORY:
1321 {
1322 /* Skip "." and ".." entries. */
1323 if (RTDirEntryExIsStdDotLink(pDirEntry))
1324 break;
1325
1326 LogRel2(("Guest Control: Directory \"%s\"\n", strEntry.c_str()));
1327
1328 if (!(mSourceSpec.fDirCopyFlags & DirectoryCopyFlag_Recursive))
1329 break;
1330
1331 vrc = AddDirFromHost(strPath, strEntry, pszPathReal, cbPathReal, pDirEntry);
1332 break;
1333 }
1334
1335 case RTFS_TYPE_FILE:
1336 {
1337 LogRel2(("Guest Control: File \"%s\"\n", strEntry.c_str()));
1338
1339 vrc = AddEntryFromHost(strEntry, &pDirEntry->Info);
1340 break;
1341 }
1342
1343 case RTFS_TYPE_SYMLINK:
1344 {
1345 Utf8Str strEntryAbs = strPathAbs + (const char *)pDirEntry->szName;
1346
1347 vrc = RTPathReal(strEntryAbs.c_str(), pszPathReal, cbPathReal);
1348 if (RT_SUCCESS(vrc))
1349 {
1350 vrc = RTPathQueryInfo(pszPathReal, &objInfo, RTFSOBJATTRADD_NOTHING);
1351 if (RT_SUCCESS(vrc))
1352 {
1353 if (RTFS_IS_DIRECTORY(objInfo.Attr.fMode))
1354 {
1355 LogRel2(("Guest Control: Symbolic link \"%s\" -> \"%s\" (directory)\n",
1356 strEntryAbs.c_str(), pszPathReal));
1357 if (mSourceSpec.fDirCopyFlags & DirectoryCopyFlag_FollowLinks)
1358 vrc = AddDirFromHost(strPath, strEntry, pszPathReal, cbPathReal, pDirEntry);
1359 }
1360 else if (RTFS_IS_FILE(objInfo.Attr.fMode))
1361 {
1362 LogRel2(("Guest Control: Symbolic link \"%s\" -> \"%s\" (file)\n",
1363 strEntryAbs.c_str(), pszPathReal));
1364 if (mSourceSpec.fFileCopyFlags & FileCopyFlag_FollowLinks)
1365 vrc = AddEntryFromHost(strEntry, &objInfo);
1366 }
1367 else
1368 vrc = VERR_NOT_SUPPORTED;
1369 }
1370
1371 if (RT_FAILURE(vrc))
1372 LogRel2(("Guest Control: Unable to query symbolic link info for \"%s\", vrc=%Rrc\n",
1373 pszPathReal, vrc));
1374 }
1375 else
1376 {
1377 LogRel2(("Guest Control: Unable to resolve symlink for \"%s\", vrc=%Rrc\n",
1378 strPathAbs.c_str(), vrc));
1379 if (vrc == VERR_FILE_NOT_FOUND) /* Broken symlink, skip. */
1380 vrc = VINF_SUCCESS;
1381 }
1382 break;
1383 }
1384
1385 default:
1386 break;
1387 }
1388
1389 } while (RT_SUCCESS(vrc));
1390
1391 RTDirClose(hDir);
1392 }
1393 }
1394 }
1395 else if (RTFS_IS_FILE(objInfo.Attr.fMode))
1396 vrc = VERR_IS_A_FILE;
1397 else if (RTFS_IS_SYMLINK(objInfo.Attr.fMode))
1398 vrc = VERR_IS_A_SYMLINK;
1399 else
1400 vrc = VERR_NOT_SUPPORTED;
1401 }
1402 else
1403 LogFlowFunc(("Unable to query \"%s\", vrc=%Rrc\n", strPathAbs.c_str(), vrc));
1404
1405 LogFlowFuncLeaveRC(vrc);
1406 return vrc;
1407}
1408
1409GuestSessionTaskOpen::GuestSessionTaskOpen(GuestSession *pSession, uint32_t uFlags, uint32_t uTimeoutMS)
1410 : GuestSessionTask(pSession)
1411 , mFlags(uFlags)
1412 , mTimeoutMS(uTimeoutMS)
1413{
1414 m_strTaskName = "gctlSesOpen";
1415}
1416
1417GuestSessionTaskOpen::~GuestSessionTaskOpen(void)
1418{
1419
1420}
1421
1422/** @copydoc GuestSessionTask::Run */
1423int GuestSessionTaskOpen::Run(void)
1424{
1425 LogFlowThisFuncEnter();
1426
1427 AutoCaller autoCaller(mSession);
1428 if (FAILED(autoCaller.hrc())) return autoCaller.hrc();
1429
1430 int vrc = mSession->i_startSession(NULL /*pvrcGuest*/);
1431 /* Nothing to do here anymore. */
1432
1433 LogFlowFuncLeaveRC(vrc);
1434 return vrc;
1435}
1436
1437GuestSessionCopyTask::GuestSessionCopyTask(GuestSession *pSession)
1438 : GuestSessionTask(pSession)
1439{
1440}
1441
1442GuestSessionCopyTask::~GuestSessionCopyTask()
1443{
1444 FsLists::iterator itList = mVecLists.begin();
1445 while (itList != mVecLists.end())
1446 {
1447 FsList *pFsList = (*itList);
1448 pFsList->Destroy();
1449 delete pFsList;
1450 mVecLists.erase(itList);
1451 itList = mVecLists.begin();
1452 }
1453
1454 Assert(mVecLists.empty());
1455}
1456
1457GuestSessionTaskCopyFrom::GuestSessionTaskCopyFrom(GuestSession *pSession, GuestSessionFsSourceSet const &vecSrc,
1458 const Utf8Str &strDest)
1459 : GuestSessionCopyTask(pSession)
1460{
1461 m_strTaskName = "gctlCpyFrm";
1462
1463 mSources = vecSrc;
1464 mDest = strDest;
1465}
1466
1467GuestSessionTaskCopyFrom::~GuestSessionTaskCopyFrom(void)
1468{
1469}
1470
1471/**
1472 * Initializes a copy-from-guest task.
1473 *
1474 * @returns HRESULT
1475 * @param strTaskDesc Friendly task description.
1476 */
1477HRESULT GuestSessionTaskCopyFrom::Init(const Utf8Str &strTaskDesc)
1478{
1479 setTaskDesc(strTaskDesc);
1480
1481 /* Create the progress object. */
1482 ComObjPtr<Progress> pProgress;
1483 HRESULT hrc = pProgress.createObject();
1484 if (FAILED(hrc))
1485 return hrc;
1486
1487 mProgress = pProgress;
1488
1489 int vrc = VINF_SUCCESS;
1490
1491 ULONG cOperations = 0;
1492 Utf8Str strErrorInfo;
1493
1494 /**
1495 * Note: We need to build up the file/directory here instead of GuestSessionTaskCopyFrom::Run
1496 * because the caller expects a ready-for-operation progress object on return.
1497 * The progress object will have a variable operation count, based on the elements to
1498 * be processed.
1499 */
1500
1501 if (mSources.empty())
1502 {
1503 strErrorInfo.printf(tr("No guest sources specified"));
1504 vrc = VERR_INVALID_PARAMETER;
1505 }
1506 else if (mDest.isEmpty())
1507 {
1508 strErrorInfo.printf(tr("Host destination must not be empty"));
1509 vrc = VERR_INVALID_PARAMETER;
1510 }
1511 else
1512 {
1513 GuestSessionFsSourceSet::iterator itSrc = mSources.begin();
1514 while (itSrc != mSources.end())
1515 {
1516 Utf8Str strSrc = itSrc->strSource;
1517 Utf8Str strDst = mDest;
1518
1519 bool fFollowSymlinks;
1520
1521 if (strSrc.isEmpty())
1522 {
1523 strErrorInfo.printf(tr("Guest source entry must not be empty"));
1524 vrc = VERR_INVALID_PARAMETER;
1525 break;
1526 }
1527
1528 if (itSrc->enmType == FsObjType_Directory)
1529 {
1530 fFollowSymlinks = itSrc->fDirCopyFlags & DirectoryCopyFlag_FollowLinks;
1531 }
1532 else
1533 {
1534 fFollowSymlinks = RT_BOOL(itSrc->fFileCopyFlags & FileCopyFlag_FollowLinks);
1535 }
1536
1537 LogFlowFunc(("strSrc=%s (path style is %s), strDst=%s, fFollowSymlinks=%RTbool\n",
1538 strSrc.c_str(), GuestBase::pathStyleToStr(itSrc->enmPathStyle), strDst.c_str(), fFollowSymlinks));
1539
1540 GuestFsObjData srcObjData;
1541 int vrcGuest = VERR_IPE_UNINITIALIZED_STATUS;
1542 vrc = mSession->i_fsObjQueryInfo(strSrc, fFollowSymlinks, srcObjData, &vrcGuest);
1543 if (RT_FAILURE(vrc))
1544 {
1545 if (vrc == VERR_GSTCTL_GUEST_ERROR)
1546 strErrorInfo = GuestBase::getErrorAsString(tr("Guest source lookup failed"),
1547 GuestErrorInfo(GuestErrorInfo::Type_Fs, vrcGuest, strSrc.c_str()));
1548 else
1549 strErrorInfo.printf(tr("Guest source lookup for \"%s\" failed: %Rrc"),
1550 strSrc.c_str(), vrc);
1551 break;
1552 }
1553
1554 if (srcObjData.mType == FsObjType_Directory)
1555 {
1556 if (itSrc->enmType != FsObjType_Directory)
1557 {
1558 strErrorInfo.printf(tr("Guest source is not a file: %s"), strSrc.c_str());
1559 vrc = VERR_NOT_A_FILE;
1560 break;
1561 }
1562 }
1563 else
1564 {
1565 if (itSrc->enmType != FsObjType_File)
1566 {
1567 strErrorInfo.printf(tr("Guest source is not a directory: %s"), strSrc.c_str());
1568 vrc = VERR_NOT_A_DIRECTORY;
1569 break;
1570 }
1571 }
1572
1573 FsList *pFsList = NULL;
1574 try
1575 {
1576 pFsList = new FsList(*this);
1577 vrc = pFsList->Init(strSrc, strDst, *itSrc);
1578 if (RT_SUCCESS(vrc))
1579 {
1580 switch (itSrc->enmType)
1581 {
1582 case FsObjType_Directory:
1583 {
1584 vrc = pFsList->AddDirFromGuest(strSrc);
1585 break;
1586 }
1587
1588 case FsObjType_File:
1589 /* The file name is already part of the actual list's source root (strSrc). */
1590 break;
1591
1592 default:
1593 LogRel2(("Guest Control: Warning: Unknown guest file system type %#x for source \"%s\", skipping\n",
1594 itSrc->enmType, strSrc.c_str()));
1595 break;
1596 }
1597 }
1598
1599 if (RT_FAILURE(vrc))
1600 {
1601 delete pFsList;
1602 strErrorInfo.printf(tr("Error adding guest source \"%s\" to list: %Rrc"),
1603 strSrc.c_str(), vrc);
1604 break;
1605 }
1606#ifdef DEBUG
1607 pFsList->DumpToLog();
1608#endif
1609 mVecLists.push_back(pFsList);
1610 }
1611 catch (std::bad_alloc &)
1612 {
1613 vrc = VERR_NO_MEMORY;
1614 break;
1615 }
1616
1617 AssertPtr(pFsList);
1618 cOperations += (ULONG)pFsList->mVecEntries.size();
1619
1620 itSrc++;
1621 }
1622 }
1623
1624 if (RT_SUCCESS(vrc))
1625 {
1626 /* When there are no entries in the first source list, this means the source only contains a single file
1627 * (see \a mSrcRootAbs of FsList). So use \a mSrcRootAbs directly. */
1628 Utf8Str const &strFirstOp = mVecLists[0]->mVecEntries.size() > 0
1629 ? mVecLists[0]->mVecEntries[0]->strPath : mVecLists[0]->mSrcRootAbs;
1630
1631 /* Now that we know how many objects we're handling, tweak the progress description so that it
1632 * reflects more accurately what the progress is actually doing. */
1633 if (cOperations > 1)
1634 {
1635 mDesc.printf(tr("Copying \"%s\" [and %zu %s] from guest to \"%s\" on the host ..."),
1636 strFirstOp.c_str(), cOperations - 1, cOperations > 2 ? tr("others") : tr("other"), mDest.c_str());
1637 }
1638 else
1639 mDesc.printf(tr("Copying \"%s\" from guest to \"%s\" on the host ..."), strFirstOp.c_str(), mDest.c_str());
1640
1641 hrc = pProgress->init(static_cast<IGuestSession*>(mSession), Bstr(mDesc).raw(),
1642 TRUE /* aCancelable */, cOperations + 1 /* Number of operations */, Bstr(strFirstOp).raw());
1643 }
1644 else /* On error we go with an "empty" progress object when will be used for error handling. */
1645 hrc = pProgress->init(static_cast<IGuestSession*>(mSession), Bstr(mDesc).raw(),
1646 TRUE /* aCancelable */, 1 /* cOperations */, Bstr(mDesc).raw());
1647
1648 if (FAILED(hrc)) /* Progress object creation failed -- we're doomed. */
1649 return hrc;
1650
1651 if (RT_FAILURE(vrc))
1652 {
1653 if (strErrorInfo.isEmpty())
1654 strErrorInfo.printf(tr("Failed with %Rrc"), vrc);
1655 setProgressErrorMsg(VBOX_E_IPRT_ERROR, strErrorInfo);
1656 }
1657
1658 LogFlowFunc(("Returning %Rhrc (%Rrc)\n", hrc, vrc));
1659 return hrc;
1660}
1661
1662/** @copydoc GuestSessionTask::Run */
1663int GuestSessionTaskCopyFrom::Run(void)
1664{
1665 LogFlowThisFuncEnter();
1666
1667 AutoCaller autoCaller(mSession);
1668 if (FAILED(autoCaller.hrc())) return autoCaller.hrc();
1669
1670 int vrc = VINF_SUCCESS;
1671
1672 FsLists::const_iterator itList = mVecLists.begin();
1673 while (itList != mVecLists.end())
1674 {
1675 FsList *pList = *itList;
1676 AssertPtr(pList);
1677
1678 LogFlowFunc(("List: srcRootAbs=%s, dstRootAbs=%s\n", pList->mSrcRootAbs.c_str(), pList->mDstRootAbs.c_str()));
1679
1680 Utf8Str strSrcRootAbs = pList->mSrcRootAbs;
1681 Utf8Str strDstRootAbs = pList->mDstRootAbs;
1682
1683 vrc = GuestPath::BuildDestinationPath(strSrcRootAbs, mSession->i_getGuestPathStyle() /* Source */,
1684 strDstRootAbs, PATH_STYLE_NATIVE /* Dest */);
1685 if (RT_FAILURE(vrc))
1686 {
1687 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1688 Utf8StrFmt(tr("Building host destination root path \"%s\" failed: %Rrc"),
1689 strDstRootAbs.c_str(), vrc));
1690 break;
1691 }
1692
1693 bool fCopyIntoExisting;
1694 bool fFollowSymlinks;
1695
1696 if (pList->mSourceSpec.enmType == FsObjType_Directory)
1697 {
1698 fCopyIntoExisting = RT_BOOL(pList->mSourceSpec.fDirCopyFlags & DirectoryCopyFlag_CopyIntoExisting);
1699 fFollowSymlinks = RT_BOOL(pList->mSourceSpec.fDirCopyFlags & DirectoryCopyFlag_FollowLinks);
1700 }
1701 else if (pList->mSourceSpec.enmType == FsObjType_File)
1702 {
1703 fCopyIntoExisting = !RT_BOOL(pList->mSourceSpec.fFileCopyFlags & FileCopyFlag_NoReplace);
1704 fFollowSymlinks = RT_BOOL(pList->mSourceSpec.fFileCopyFlags & FileCopyFlag_FollowLinks);
1705 }
1706 else
1707 AssertFailedBreakStmt(vrc = VERR_NOT_IMPLEMENTED);
1708
1709 uint32_t const fDirMode = 0700; /** @todo Play safe by default; implement ACLs. */
1710 uint32_t fDirCreate = 0;
1711
1712 bool fDstExists = true;
1713
1714 RTFSOBJINFO dstFsObjInfo;
1715 RT_ZERO(dstFsObjInfo);
1716 vrc = RTPathQueryInfoEx(strDstRootAbs.c_str(), &dstFsObjInfo, RTFSOBJATTRADD_NOTHING, RTPATH_F_ON_LINK /* fFlags */);
1717 if (RT_SUCCESS(vrc))
1718 {
1719 char szPathReal[RTPATH_MAX];
1720 vrc = RTPathReal(strDstRootAbs.c_str(), szPathReal, sizeof(szPathReal));
1721 if (RT_SUCCESS(vrc))
1722 {
1723 vrc = RTPathQueryInfoEx(szPathReal, &dstFsObjInfo, RTFSOBJATTRADD_NOTHING, RTPATH_F_FOLLOW_LINK /* fFlags */);
1724 if (RT_SUCCESS(vrc))
1725 {
1726 LogRel2(("Guest Control: Host destination is a symbolic link \"%s\" -> \"%s\" (%s)\n",
1727 strDstRootAbs.c_str(), szPathReal,
1728 GuestBase::fsObjTypeToStr(GuestBase::fileModeToFsObjType(dstFsObjInfo.Attr.fMode))));
1729 }
1730
1731 strDstRootAbs = szPathReal;
1732 }
1733 }
1734 else
1735 {
1736 if ( vrc == VERR_FILE_NOT_FOUND
1737 || vrc == VERR_PATH_NOT_FOUND)
1738 {
1739 fDstExists = false;
1740 vrc = VINF_SUCCESS;
1741 }
1742 else
1743 {
1744 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1745 Utf8StrFmt(tr("Host path lookup for \"%s\" failed: %Rrc"), strDstRootAbs.c_str(), vrc));
1746 break;
1747 }
1748 }
1749
1750 /* Create the root directory. */
1751 if (pList->mSourceSpec.enmType == FsObjType_Directory)
1752 {
1753 LogFlowFunc(("Directory: fDirCopyFlags=%#x, fCopyIntoExisting=%RTbool, fFollowSymlinks=%RTbool -> fDstExist=%RTbool (%s)\n",
1754 pList->mSourceSpec.fDirCopyFlags, fCopyIntoExisting, fFollowSymlinks,
1755 fDstExists, GuestBase::fsObjTypeToStr(GuestBase::fileModeToFsObjType(dstFsObjInfo.Attr.fMode))));
1756
1757 if (fDstExists)
1758 {
1759 switch (dstFsObjInfo.Attr.fMode & RTFS_TYPE_MASK)
1760 {
1761 case RTFS_TYPE_DIRECTORY:
1762 {
1763 if (!fCopyIntoExisting)
1764 {
1765 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1766 Utf8StrFmt(tr("Host root directory \"%s\" already exists"), strDstRootAbs.c_str()));
1767 vrc = VERR_ALREADY_EXISTS;
1768 break;
1769 }
1770 break;
1771 }
1772
1773 case RTFS_TYPE_FILE:
1774 {
1775 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1776 Utf8StrFmt(tr("Destination \"%s\" on the host already exists and is a file"), strDstRootAbs.c_str()));
1777 vrc = VERR_IS_A_FILE;
1778 break;
1779 }
1780
1781 default:
1782 {
1783 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1784 Utf8StrFmt(tr("Unknown object type (%#x) on host for \"%s\""),
1785 dstFsObjInfo.Attr.fMode & RTFS_TYPE_MASK, strDstRootAbs.c_str()));
1786 vrc = VERR_NOT_SUPPORTED;
1787 break;
1788 }
1789 }
1790 }
1791
1792 if (RT_FAILURE(vrc))
1793 break;
1794
1795 /* Make sure the destination root directory exists. */
1796 if (pList->mSourceSpec.fDryRun == false)
1797 {
1798 vrc = directoryCreateOnHost(strDstRootAbs, fDirMode, 0 /* fCreate */, true /* fCanExist */);
1799 if (RT_FAILURE(vrc))
1800 break;
1801 }
1802
1803 AssertBreakStmt(pList->mSourceSpec.enmType == FsObjType_Directory, vrc = VERR_NOT_SUPPORTED);
1804
1805 /* Walk the entries. */
1806 FsEntries::const_iterator itEntry = pList->mVecEntries.begin();
1807 while (itEntry != pList->mVecEntries.end())
1808 {
1809 FsEntry *pEntry = *itEntry;
1810 AssertPtr(pEntry);
1811
1812 Utf8Str strSrcAbs = strSrcRootAbs;
1813 Utf8Str strDstAbs = strDstRootAbs;
1814
1815 strSrcAbs += PATH_STYLE_SEP_STR(pList->mSourceSpec.enmPathStyle);
1816 strSrcAbs += pEntry->strPath;
1817
1818 strDstAbs += PATH_STYLE_SEP_STR(PATH_STYLE_NATIVE);
1819 strDstAbs += pEntry->strPath;
1820
1821 /* Clean up the final guest source path. */
1822 vrc = GuestPath::Translate(strSrcAbs, pList->mSourceSpec.enmPathStyle /* Source */,
1823 pList->mSourceSpec.enmPathStyle /* Dest */);
1824 if (RT_FAILURE(vrc))
1825 {
1826 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1827 Utf8StrFmt(tr("Translating guest source path \"%s\" failed: %Rrc"),
1828 strSrcAbs.c_str(), vrc));
1829 break;
1830 }
1831
1832 /* Translate the final host desitnation path. */
1833 vrc = GuestPath::Translate(strDstAbs, mSession->i_getGuestPathStyle() /* Source */, PATH_STYLE_NATIVE /* Dest */);
1834 if (RT_FAILURE(vrc))
1835 {
1836 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1837 Utf8StrFmt(tr("Translating host destination path \"%s\" failed: %Rrc"),
1838 strDstAbs.c_str(), vrc));
1839 break;
1840 }
1841
1842 mProgress->SetNextOperation(Bstr(strSrcAbs).raw(), 1);
1843
1844 switch (pEntry->fMode & RTFS_TYPE_MASK)
1845 {
1846 case RTFS_TYPE_DIRECTORY:
1847 if (!pList->mSourceSpec.fDryRun)
1848 vrc = directoryCreateOnHost(strDstAbs, fDirMode, fDirCreate, fCopyIntoExisting);
1849 break;
1850
1851 case RTFS_TYPE_FILE:
1852 RT_FALL_THROUGH();
1853 case RTFS_TYPE_SYMLINK:
1854 if (!pList->mSourceSpec.fDryRun)
1855 vrc = fileCopyFromGuest(strSrcAbs, strDstAbs, pList->mSourceSpec.fFileCopyFlags);
1856 break;
1857
1858 default:
1859 AssertFailed(); /* Should never happen (we already have a filtered list). */
1860 break;
1861 }
1862
1863 if (RT_FAILURE(vrc))
1864 break;
1865
1866 ++itEntry;
1867 }
1868 }
1869 else if (pList->mSourceSpec.enmType == FsObjType_File)
1870 {
1871 LogFlowFunc(("File: fFileCopyFlags=%#x, fCopyIntoExisting=%RTbool, fFollowSymlinks=%RTbool -> fDstExist=%RTbool (%s)\n",
1872 pList->mSourceSpec.fFileCopyFlags, fCopyIntoExisting, fFollowSymlinks,
1873 fDstExists, GuestBase::fsObjTypeToStr(GuestBase::fileModeToFsObjType(dstFsObjInfo.Attr.fMode))));
1874
1875 if (fDstExists)
1876 {
1877 switch (dstFsObjInfo.Attr.fMode & RTFS_TYPE_MASK)
1878 {
1879 case RTFS_TYPE_DIRECTORY:
1880 {
1881 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1882 Utf8StrFmt(tr("Destination \"%s\" on the host already exists and is a directory"),
1883 strDstRootAbs.c_str()));
1884 vrc = VERR_IS_A_DIRECTORY;
1885 break;
1886 }
1887
1888 case RTFS_TYPE_FILE:
1889 {
1890 if (!fCopyIntoExisting)
1891 {
1892 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1893 Utf8StrFmt(tr("Host file \"%s\" already exists"), strDstRootAbs.c_str()));
1894 vrc = VERR_ALREADY_EXISTS;
1895 }
1896 break;
1897 }
1898
1899 default:
1900 {
1901 /** @todo Resolve symlinks? */
1902 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1903 Utf8StrFmt(tr("Unknown object type (%#x) on host for \"%s\""),
1904 dstFsObjInfo.Attr.fMode & RTFS_TYPE_MASK, strDstRootAbs.c_str()));
1905 vrc = VERR_NOT_SUPPORTED;
1906 break;
1907 }
1908 }
1909 }
1910
1911 if (RT_SUCCESS(vrc))
1912 {
1913 /* Translate the final host destination file path. */
1914 vrc = GuestPath::Translate(strDstRootAbs,
1915 mSession->i_getGuestPathStyle() /* Dest */, PATH_STYLE_NATIVE /* Source */);
1916 if (RT_FAILURE(vrc))
1917 {
1918 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
1919 Utf8StrFmt(tr("Translating host destination path \"%s\" failed: %Rrc"),
1920 strDstRootAbs.c_str(), vrc));
1921 break;
1922 }
1923
1924 if (!pList->mSourceSpec.fDryRun)
1925 vrc = fileCopyFromGuest(strSrcRootAbs, strDstRootAbs, pList->mSourceSpec.fFileCopyFlags);
1926 }
1927 }
1928 else
1929 AssertFailedStmt(vrc = VERR_NOT_SUPPORTED);
1930
1931 if (RT_FAILURE(vrc))
1932 break;
1933
1934 ++itList;
1935 }
1936
1937 if (RT_SUCCESS(vrc))
1938 vrc = setProgressSuccess();
1939
1940 LogFlowFuncLeaveRC(vrc);
1941 return vrc;
1942}
1943
1944GuestSessionTaskCopyTo::GuestSessionTaskCopyTo(GuestSession *pSession, GuestSessionFsSourceSet const &vecSrc,
1945 const Utf8Str &strDest)
1946 : GuestSessionCopyTask(pSession)
1947{
1948 m_strTaskName = "gctlCpyTo";
1949
1950 mSources = vecSrc;
1951 mDest = strDest;
1952}
1953
1954GuestSessionTaskCopyTo::~GuestSessionTaskCopyTo(void)
1955{
1956}
1957
1958/**
1959 * Initializes a copy-to-guest task.
1960 *
1961 * @returns HRESULT
1962 * @param strTaskDesc Friendly task description.
1963 */
1964HRESULT GuestSessionTaskCopyTo::Init(const Utf8Str &strTaskDesc)
1965{
1966 LogFlowFuncEnter();
1967
1968 setTaskDesc(strTaskDesc);
1969
1970 /* Create the progress object. */
1971 ComObjPtr<Progress> pProgress;
1972 HRESULT hrc = pProgress.createObject();
1973 if (FAILED(hrc))
1974 return hrc;
1975
1976 mProgress = pProgress;
1977
1978 int vrc = VINF_SUCCESS;
1979
1980 ULONG cOperations = 0;
1981 Utf8Str strErrorInfo;
1982
1983 /*
1984 * Note: We need to build up the file/directory here instead of GuestSessionTaskCopyTo::Run
1985 * because the caller expects a ready-for-operation progress object on return.
1986 * The progress object will have a variable operation count, based on the elements to
1987 * be processed.
1988 */
1989
1990 if (mSources.empty())
1991 {
1992 strErrorInfo.printf(tr("No host sources specified"));
1993 vrc = VERR_INVALID_PARAMETER;
1994 }
1995 else if (mDest.isEmpty())
1996 {
1997 strErrorInfo.printf(tr("Guest destination must not be empty"));
1998 vrc = VERR_INVALID_PARAMETER;
1999 }
2000 else
2001 {
2002 GuestSessionFsSourceSet::iterator itSrc = mSources.begin();
2003 while (itSrc != mSources.end())
2004 {
2005 Utf8Str strSrc = itSrc->strSource;
2006 Utf8Str strDst = mDest;
2007
2008 bool fFollowSymlinks;
2009
2010 if (strSrc.isEmpty())
2011 {
2012 strErrorInfo.printf(tr("Host source entry must not be empty"));
2013 vrc = VERR_INVALID_PARAMETER;
2014 break;
2015 }
2016
2017 if (itSrc->enmType == FsObjType_Directory)
2018 {
2019 fFollowSymlinks = itSrc->fDirCopyFlags & DirectoryCopyFlag_FollowLinks;
2020 }
2021 else
2022 {
2023 fFollowSymlinks = RT_BOOL(itSrc->fFileCopyFlags & FileCopyFlag_FollowLinks);
2024 }
2025
2026 LogFlowFunc(("strSrc=%s (path style is %s), strDst=%s\n",
2027 strSrc.c_str(), GuestBase::pathStyleToStr(itSrc->enmPathStyle), strDst.c_str()));
2028
2029 RTFSOBJINFO srcFsObjInfo;
2030 vrc = RTPathQueryInfoEx(strSrc.c_str(), &srcFsObjInfo, RTFSOBJATTRADD_NOTHING, RTPATH_F_ON_LINK /* fFlags */);
2031 if (RT_FAILURE(vrc))
2032 {
2033 strErrorInfo.printf(tr("No such host file/directory: %s"), strSrc.c_str());
2034 break;
2035 }
2036
2037 switch (srcFsObjInfo.Attr.fMode & RTFS_TYPE_MASK)
2038 {
2039 case RTFS_TYPE_DIRECTORY:
2040 {
2041 if (itSrc->enmType != FsObjType_Directory)
2042 {
2043 strErrorInfo.printf(tr("Host source \"%s\" is not a file (is a directory)"), strSrc.c_str());
2044 vrc = VERR_NOT_A_FILE;
2045 }
2046 break;
2047 }
2048
2049 case RTFS_TYPE_FILE:
2050 {
2051 if (itSrc->enmType == FsObjType_Directory)
2052 {
2053 strErrorInfo.printf(tr("Host source \"%s\" is not a directory (is a file)"), strSrc.c_str());
2054 vrc = VERR_NOT_A_DIRECTORY;
2055 }
2056 break;
2057 }
2058
2059 case RTFS_TYPE_SYMLINK:
2060 {
2061 if (!fFollowSymlinks)
2062 {
2063 strErrorInfo.printf(tr("Host source \"%s\" is a symbolic link"), strSrc.c_str());
2064 vrc = VERR_IS_A_SYMLINK;
2065 break;
2066 }
2067
2068 char szPathReal[RTPATH_MAX];
2069 vrc = RTPathReal(strSrc.c_str(), szPathReal, sizeof(szPathReal));
2070 if (RT_SUCCESS(vrc))
2071 {
2072 vrc = RTPathQueryInfoEx(szPathReal, &srcFsObjInfo, RTFSOBJATTRADD_NOTHING, RTPATH_F_FOLLOW_LINK);
2073 if (RT_SUCCESS(vrc))
2074 {
2075 LogRel2(("Guest Control: Host source is a symbolic link \"%s\" -> \"%s\" (%s)\n",
2076 strSrc.c_str(), szPathReal,
2077 GuestBase::fsObjTypeToStr(GuestBase::fileModeToFsObjType(srcFsObjInfo.Attr.fMode))));
2078
2079 /* We want to keep the symbolic link name of the source instead of the target pointing to,
2080 * so don't touch the source's name here. */
2081 itSrc->enmType = GuestBase::fileModeToFsObjType(srcFsObjInfo.Attr.fMode);
2082 }
2083 else
2084 {
2085 strErrorInfo.printf(tr("Querying symbolic link info for host source \"%s\" failed"), strSrc.c_str());
2086 break;
2087 }
2088 }
2089 else
2090 {
2091 strErrorInfo.printf(tr("Resolving symbolic link for host source \"%s\" failed"), strSrc.c_str());
2092 break;
2093 }
2094 break;
2095 }
2096
2097 default:
2098 LogRel2(("Guest Control: Warning: Unknown host file system type %#x for source \"%s\", skipping\n",
2099 srcFsObjInfo.Attr.fMode & RTFS_TYPE_MASK, strSrc.c_str()));
2100 break;
2101 }
2102
2103 if (RT_FAILURE(vrc))
2104 break;
2105
2106 FsList *pFsList = NULL;
2107 try
2108 {
2109 pFsList = new FsList(*this);
2110 vrc = pFsList->Init(strSrc, strDst, *itSrc);
2111 if (RT_SUCCESS(vrc))
2112 {
2113 switch (itSrc->enmType)
2114 {
2115 case FsObjType_Directory:
2116 {
2117 char szPathReal[RTPATH_MAX];
2118 RTDIRENTRYEX DirEntry;
2119 vrc = pFsList->AddDirFromHost(strSrc /* strPath */, "" /* strSubDir */,
2120 szPathReal, sizeof(szPathReal), &DirEntry);
2121 break;
2122 }
2123
2124 case FsObjType_File:
2125 /* The file name is already part of the actual list's source root (strSrc). */
2126 break;
2127
2128 case FsObjType_Symlink:
2129 AssertFailed(); /* Should never get here, as we do the resolving above. */
2130 break;
2131
2132 default:
2133 LogRel2(("Guest Control: Warning: Unknown source type %#x for host source \"%s\", skipping\n",
2134 itSrc->enmType, strSrc.c_str()));
2135 break;
2136 }
2137 }
2138
2139 if (RT_FAILURE(vrc))
2140 {
2141 delete pFsList;
2142 strErrorInfo.printf(tr("Error adding host source \"%s\" to list: %Rrc"),
2143 strSrc.c_str(), vrc);
2144 break;
2145 }
2146#ifdef DEBUG
2147 pFsList->DumpToLog();
2148#endif
2149 mVecLists.push_back(pFsList);
2150 }
2151 catch (std::bad_alloc &)
2152 {
2153 vrc = VERR_NO_MEMORY;
2154 break;
2155 }
2156
2157 AssertPtr(pFsList);
2158 cOperations += (ULONG)pFsList->mVecEntries.size();
2159
2160 itSrc++;
2161 }
2162 }
2163
2164 if (RT_SUCCESS(vrc))
2165 {
2166 /* When there are no entries in the first source list, this means the source only contains a single file
2167 * (see \a mSrcRootAbs of FsList). So use \a mSrcRootAbs directly. */
2168 Utf8Str const &strFirstOp = mVecLists[0]->mVecEntries.size() > 0
2169 ? mVecLists[0]->mVecEntries[0]->strPath : mVecLists[0]->mSrcRootAbs;
2170
2171 /* Now that we know how many objects we're handling, tweak the progress description so that it
2172 * reflects more accurately what the progress is actually doing. */
2173 if (cOperations > 1)
2174 {
2175 mDesc.printf(tr("Copying \"%s\" [and %zu %s] from host to \"%s\" on the guest ..."),
2176 strFirstOp.c_str(), cOperations - 1, cOperations > 2 ? tr("others") : tr("other"), mDest.c_str());
2177 }
2178 else
2179 mDesc.printf(tr("Copying \"%s\" from host to \"%s\" on the guest ..."), strFirstOp.c_str(), mDest.c_str());
2180
2181 hrc = pProgress->init(static_cast<IGuestSession*>(mSession), Bstr(mDesc).raw(),
2182 TRUE /* aCancelable */, cOperations + 1/* Number of operations */,
2183 Bstr(strFirstOp).raw());
2184 }
2185 else /* On error we go with an "empty" progress object when will be used for error handling. */
2186 hrc = pProgress->init(static_cast<IGuestSession*>(mSession), Bstr(mDesc).raw(),
2187 TRUE /* aCancelable */, 1 /* cOperations */, Bstr(mDesc).raw());
2188
2189 if (FAILED(hrc)) /* Progress object creation failed -- we're doomed. */
2190 return hrc;
2191
2192 if (RT_FAILURE(vrc))
2193 {
2194 if (strErrorInfo.isEmpty())
2195 strErrorInfo.printf(tr("Failed with %Rrc"), vrc);
2196 setProgressErrorMsg(VBOX_E_IPRT_ERROR, strErrorInfo);
2197 }
2198
2199 LogFlowFunc(("Returning %Rhrc (%Rrc)\n", hrc, vrc));
2200 return hrc;
2201}
2202
2203/** @copydoc GuestSessionTask::Run */
2204int GuestSessionTaskCopyTo::Run(void)
2205{
2206 LogFlowThisFuncEnter();
2207
2208 AutoCaller autoCaller(mSession);
2209 if (FAILED(autoCaller.hrc())) return autoCaller.hrc();
2210
2211 int vrc = VINF_SUCCESS;
2212
2213 FsLists::const_iterator itList = mVecLists.begin();
2214 while (itList != mVecLists.end())
2215 {
2216 FsList *pList = *itList;
2217 AssertPtr(pList);
2218
2219 LogFlowFunc(("List: srcRootAbs=%s, dstRootAbs=%s\n", pList->mSrcRootAbs.c_str(), pList->mDstRootAbs.c_str()));
2220
2221 Utf8Str strSrcRootAbs = pList->mSrcRootAbs;
2222 Utf8Str strDstRootAbs = pList->mDstRootAbs;
2223
2224 vrc = GuestPath::BuildDestinationPath(strSrcRootAbs, PATH_STYLE_NATIVE /* Source */,
2225 strDstRootAbs, mSession->i_getGuestPathStyle() /* Dest */);
2226 if (RT_FAILURE(vrc))
2227 {
2228 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
2229 Utf8StrFmt(tr("Building guest destination root path \"%s\" failed: %Rrc"),
2230 strDstRootAbs.c_str(), vrc));
2231 break;
2232 }
2233
2234 bool fCopyIntoExisting;
2235 bool fFollowSymlinks;
2236
2237 if (pList->mSourceSpec.enmType == FsObjType_Directory)
2238 {
2239 fCopyIntoExisting = RT_BOOL(pList->mSourceSpec.fDirCopyFlags & DirectoryCopyFlag_CopyIntoExisting);
2240 fFollowSymlinks = RT_BOOL(pList->mSourceSpec.fDirCopyFlags & DirectoryCopyFlag_FollowLinks);
2241 }
2242 else if (pList->mSourceSpec.enmType == FsObjType_File)
2243 {
2244 fCopyIntoExisting = !RT_BOOL(pList->mSourceSpec.fFileCopyFlags & FileCopyFlag_NoReplace);
2245 fFollowSymlinks = RT_BOOL(pList->mSourceSpec.fFileCopyFlags & FileCopyFlag_FollowLinks);
2246 }
2247 else
2248 AssertFailedBreakStmt(vrc = VERR_NOT_IMPLEMENTED);
2249
2250 uint32_t const fDirMode = 0700; /** @todo Play safe by default; implement ACLs. */
2251
2252 bool fDstExists = true;
2253
2254 GuestFsObjData dstObjData;
2255 int vrcGuest;
2256 vrc = mSession->i_fsObjQueryInfo(strDstRootAbs, fFollowSymlinks, dstObjData, &vrcGuest);
2257 if (RT_FAILURE(vrc))
2258 {
2259 if (vrc == VERR_GSTCTL_GUEST_ERROR)
2260 {
2261 switch (vrcGuest)
2262 {
2263 case VERR_PATH_NOT_FOUND:
2264 RT_FALL_THROUGH();
2265 case VERR_FILE_NOT_FOUND:
2266 {
2267 fDstExists = false;
2268 vrc = VINF_SUCCESS;
2269 break;
2270 }
2271 default:
2272 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
2273 Utf8StrFmt(tr("Querying information on guest for \"%s\" failed: %Rrc"),
2274 strDstRootAbs.c_str(), vrcGuest));
2275 break;
2276 }
2277 }
2278 else
2279 {
2280 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
2281 Utf8StrFmt(tr("Querying information on guest for \"%s\" failed: %Rrc"),
2282 strDstRootAbs.c_str(), vrc));
2283 break;
2284 }
2285 }
2286
2287 if (pList->mSourceSpec.enmType == FsObjType_Directory)
2288 {
2289 LogFlowFunc(("Directory: fDirCopyFlags=%#x, fCopyIntoExisting=%RTbool, fFollowSymlinks=%RTbool -> fDstExist=%RTbool (%s)\n",
2290 pList->mSourceSpec.fDirCopyFlags, fCopyIntoExisting, fFollowSymlinks,
2291 fDstExists, GuestBase::fsObjTypeToStr(dstObjData.mType)));
2292
2293 if (fDstExists)
2294 {
2295 switch (dstObjData.mType)
2296 {
2297 case FsObjType_Directory:
2298 {
2299 if (!fCopyIntoExisting)
2300 {
2301 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
2302 Utf8StrFmt(tr("Guest root directory \"%s\" already exists"),
2303 strDstRootAbs.c_str()));
2304 vrc = VERR_ALREADY_EXISTS;
2305 }
2306 break;
2307 }
2308
2309 case FsObjType_File:
2310 {
2311 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
2312 Utf8StrFmt(tr("Destination \"%s\" on guest already exists and is a file"),
2313 strDstRootAbs.c_str()));
2314 vrc = VERR_IS_A_FILE;
2315 break;
2316 }
2317
2318 case FsObjType_Symlink:
2319 /** @todo Resolve symlinks? */
2320 break;
2321
2322 default:
2323 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
2324 Utf8StrFmt(tr("Unknown object type (%#x) on guest for \"%s\""),
2325 dstObjData.mType, strDstRootAbs.c_str()));
2326 vrc = VERR_NOT_SUPPORTED;
2327 break;
2328 }
2329 }
2330
2331 if (RT_FAILURE(vrc))
2332 break;
2333
2334 /* Make sure the destination root directory exists. */
2335 if (pList->mSourceSpec.fDryRun == false)
2336 {
2337 vrc = directoryCreateOnGuest(strDstRootAbs, fDirMode, DirectoryCreateFlag_None,
2338 fFollowSymlinks, fCopyIntoExisting);
2339 if (RT_FAILURE(vrc))
2340 break;
2341 }
2342
2343 /* Walk the entries. */
2344 FsEntries::const_iterator itEntry = pList->mVecEntries.begin();
2345 while ( RT_SUCCESS(vrc)
2346 && itEntry != pList->mVecEntries.end())
2347 {
2348 FsEntry *pEntry = *itEntry;
2349 AssertPtr(pEntry);
2350
2351 Utf8Str strSrcAbs = strSrcRootAbs;
2352 Utf8Str strDstAbs = strDstRootAbs;
2353
2354 strSrcAbs += PATH_STYLE_SEP_STR(PATH_STYLE_NATIVE);
2355 strSrcAbs += pEntry->strPath;
2356
2357 strDstAbs += PATH_STYLE_SEP_STR(mSession->i_getGuestPathStyle());
2358 strDstAbs += pEntry->strPath;
2359
2360 /* Clean up the final host source path. */
2361 vrc = GuestPath::Translate(strSrcAbs, pList->mSourceSpec.enmPathStyle /* Source */,
2362 pList->mSourceSpec.enmPathStyle /* Dest */);
2363 if (RT_FAILURE(vrc))
2364 {
2365 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
2366 Utf8StrFmt(tr("Translating host source path\"%s\" failed: %Rrc"),
2367 strSrcAbs.c_str(), vrc));
2368 break;
2369 }
2370
2371 /* Translate final guest destination path. */
2372 vrc = GuestPath::Translate(strDstAbs,
2373 PATH_STYLE_NATIVE /* Source */, mSession->i_getGuestPathStyle() /* Dest */);
2374 if (RT_FAILURE(vrc))
2375 {
2376 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
2377 Utf8StrFmt(tr("Translating guest destination path \"%s\" failed: %Rrc"),
2378 strDstAbs.c_str(), vrc));
2379 break;
2380 }
2381
2382 mProgress->SetNextOperation(Bstr(strSrcAbs).raw(), 1);
2383
2384 switch (pEntry->fMode & RTFS_TYPE_MASK)
2385 {
2386 case RTFS_TYPE_DIRECTORY:
2387 {
2388 LogRel2(("Guest Control: Copying directory \"%s\" from host to \"%s\" on guest ...\n",
2389 strSrcAbs.c_str(), strDstAbs.c_str()));
2390 if (!pList->mSourceSpec.fDryRun)
2391 vrc = directoryCreateOnGuest(strDstAbs, fDirMode, DirectoryCreateFlag_None,
2392 fFollowSymlinks, fCopyIntoExisting);
2393 break;
2394 }
2395
2396 case RTFS_TYPE_FILE:
2397 {
2398 if (!pList->mSourceSpec.fDryRun)
2399 vrc = fileCopyToGuest(strSrcAbs, strDstAbs, pList->mSourceSpec.fFileCopyFlags);
2400 break;
2401 }
2402
2403 default:
2404 LogRel2(("Guest Control: Warning: Host file system type 0x%x for \"%s\" is not supported, skipping\n",
2405 pEntry->fMode & RTFS_TYPE_MASK, strSrcAbs.c_str()));
2406 break;
2407 }
2408
2409 if (RT_FAILURE(vrc))
2410 break;
2411
2412 ++itEntry;
2413 }
2414 }
2415 else if (pList->mSourceSpec.enmType == FsObjType_File)
2416 {
2417 LogFlowFunc(("File: fFileCopyFlags=%#x, fCopyIntoExisting=%RTbool, fFollowSymlinks=%RTbool -> fDstExist=%RTbool (%s)\n",
2418 pList->mSourceSpec.fFileCopyFlags, fCopyIntoExisting, fFollowSymlinks,
2419 fDstExists, GuestBase::fsObjTypeToStr(dstObjData.mType)));
2420
2421 if (fDstExists)
2422 {
2423 switch (dstObjData.mType)
2424 {
2425 case FsObjType_Directory:
2426 {
2427 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
2428 Utf8StrFmt(tr("Destination \"%s\" on the guest already exists and is a directory"),
2429 strDstRootAbs.c_str()));
2430 vrc = VERR_IS_A_DIRECTORY;
2431 break;
2432 }
2433
2434 case FsObjType_File:
2435 {
2436 if (!fCopyIntoExisting)
2437 {
2438 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
2439 Utf8StrFmt(tr("Guest file \"%s\" already exists"), strDstRootAbs.c_str()));
2440 vrc = VERR_ALREADY_EXISTS;
2441 }
2442 break;
2443 }
2444
2445 default:
2446 {
2447 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
2448 Utf8StrFmt(tr("Unsupported guest file system type (%#x) for \"%s\""),
2449 dstObjData.mType, strDstRootAbs.c_str()));
2450 vrc = VERR_NOT_SUPPORTED;
2451 break;
2452 }
2453 }
2454 }
2455
2456 if (RT_SUCCESS(vrc))
2457 {
2458 /* Translate the final guest destination file path. */
2459 vrc = GuestPath::Translate(strDstRootAbs,
2460 PATH_STYLE_NATIVE /* Source */, mSession->i_getGuestPathStyle() /* Dest */);
2461 if (RT_FAILURE(vrc))
2462 {
2463 setProgressErrorMsg(VBOX_E_IPRT_ERROR,
2464 Utf8StrFmt(tr("Translating guest destination path \"%s\" failed: %Rrc"),
2465 strDstRootAbs.c_str(), vrc));
2466 break;
2467 }
2468
2469 if (!pList->mSourceSpec.fDryRun)
2470 vrc = fileCopyToGuest(strSrcRootAbs, strDstRootAbs, pList->mSourceSpec.fFileCopyFlags);
2471 }
2472 }
2473 else
2474 AssertFailedStmt(vrc = VERR_NOT_SUPPORTED);
2475
2476 if (RT_FAILURE(vrc))
2477 break;
2478
2479 ++itList;
2480 }
2481
2482 if (RT_SUCCESS(vrc))
2483 vrc = setProgressSuccess();
2484
2485 LogFlowFuncLeaveRC(vrc);
2486 return vrc;
2487}
2488
2489UpdateAdditionsProcess::~UpdateAdditionsProcess()
2490{
2491 /* Log any remainders if not done yet. */
2492 if (mLineStdOut.isNotEmpty())
2493 LogRel(("Guest Additions Update: %s\n", mLineStdOut.c_str()));
2494 if (mLineStdErr.isNotEmpty())
2495 LogRel(("Guest Additions Update: %s\n", mLineStdErr.c_str()));
2496}
2497
2498/**
2499 * Callback implementation to output guest update process stdout / stderr output to the release log.
2500 * Only complete lines will be logged for cosmetic reasons.
2501 *
2502 * @returns VBox status code.
2503 * @param uHandle Process output handle.
2504 * @param pbData Pointer to data.
2505 * @param cbData Size (in bytes) of \a pbData.
2506 *
2507 * @note Only stdout (handle ID 1) and stderr (handle ID 2) are implemented.
2508 */
2509int UpdateAdditionsProcess::onOutputCallback(uint32_t uHandle, const BYTE *pbData, size_t cbData)
2510{
2511 AssertReturn(RTStrValidateEncodingEx((const char *)pbData, cbData, RTSTR_VALIDATE_ENCODING_EXACT_LENGTH
2512 | RTSTR_VALIDATE_ENCODING_ZERO_TERMINATED),
2513 VERR_INVALID_PARAMETER);
2514
2515 Utf8Str *pstrLine = NULL;
2516
2517 switch (uHandle)
2518 {
2519 case GUEST_PROC_OUT_H_STDOUT:
2520 pstrLine = &mLineStdOut;
2521 break;
2522
2523 case GUEST_PROC_OUT_H_STDERR:
2524 pstrLine = &mLineStdErr;
2525 break;
2526
2527 default:
2528 /* Ignore. */
2529 break;
2530 }
2531
2532 int vrc = VINF_SUCCESS;
2533
2534 if (pstrLine)
2535 {
2536 const char *cch = (const char *)pbData;
2537 while (cbData)
2538 {
2539 if (*cch == '\n')
2540 break;
2541 pstrLine->append(*cch);
2542 cch++;
2543 cbData--;
2544 }
2545
2546 if (*cch == '\n')
2547 {
2548 LogRel(("Guest Additions Update: %s\n", pstrLine->c_str()));
2549 pstrLine->setNull();
2550 cch++;
2551 }
2552 }
2553
2554 return vrc;
2555}
2556
2557GuestSessionTaskUpdateAdditions::GuestSessionTaskUpdateAdditions(GuestSession *pSession,
2558 const Utf8Str &strSource,
2559 const ProcessArguments &aArguments,
2560 uint32_t fFlags)
2561 : GuestSessionTask(pSession)
2562{
2563 m_strTaskName = "gctlUpGA";
2564
2565 mSource = strSource;
2566 mArguments = aArguments;
2567 mFlags = fFlags;
2568}
2569
2570GuestSessionTaskUpdateAdditions::~GuestSessionTaskUpdateAdditions(void)
2571{
2572
2573}
2574
2575/**
2576 * Adds arguments to existing process arguments.
2577 * Identical / already existing arguments will be filtered out.
2578 *
2579 * @returns VBox status code.
2580 * @param aArgumentsDest Destination to add arguments to.
2581 * @param aArgumentsSource Arguments to add.
2582 */
2583int GuestSessionTaskUpdateAdditions::addProcessArguments(ProcessArguments &aArgumentsDest, const ProcessArguments &aArgumentsSource)
2584{
2585 try
2586 {
2587 /* Filter out arguments which already are in the destination to
2588 * not end up having them specified twice. Not the fastest method on the
2589 * planet but does the job. */
2590 ProcessArguments::const_iterator itSource = aArgumentsSource.begin();
2591 while (itSource != aArgumentsSource.end())
2592 {
2593 bool fFound = false;
2594 ProcessArguments::iterator itDest = aArgumentsDest.begin();
2595 while (itDest != aArgumentsDest.end())
2596 {
2597 if ((*itDest).equalsIgnoreCase((*itSource)))
2598 {
2599 fFound = true;
2600 break;
2601 }
2602 ++itDest;
2603 }
2604
2605 if (!fFound)
2606 aArgumentsDest.push_back((*itSource));
2607
2608 ++itSource;
2609 }
2610 }
2611 catch(std::bad_alloc &)
2612 {
2613 return VERR_NO_MEMORY;
2614 }
2615
2616 return VINF_SUCCESS;
2617}
2618
2619/**
2620 * Helper function to copy a file from a VISO to the guest.
2621 *
2622 * @returns VBox status code.
2623 * @param pSession Guest session to use.
2624 * @param hVfsIso VISO handle to use.
2625 * @param strFileSrc Source file path on VISO to copy.
2626 * @param strFileDst Destination file path on guest.
2627 * @param fOptional When set to \c true, the file is optional, i.e. can be skipped
2628 * when not found, \c false if not.
2629 */
2630int GuestSessionTaskUpdateAdditions::copyFileToGuest(GuestSession *pSession, RTVFS hVfsIso,
2631 Utf8Str const &strFileSrc, const Utf8Str &strFileDst, bool fOptional)
2632{
2633 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
2634 AssertReturn(hVfsIso != NIL_RTVFS, VERR_INVALID_POINTER);
2635
2636 RTVFSFILE hVfsFile = NIL_RTVFSFILE;
2637 int vrc = RTVfsFileOpen(hVfsIso, strFileSrc.c_str(), RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_WRITE, &hVfsFile);
2638 if (RT_SUCCESS(vrc))
2639 {
2640 uint64_t cbSrcSize = 0;
2641 vrc = RTVfsFileQuerySize(hVfsFile, &cbSrcSize);
2642 if (RT_SUCCESS(vrc))
2643 {
2644 LogRel(("Guest Additions Update: Copying installer file \"%s\" to \"%s\" on guest ...\n",
2645 strFileSrc.c_str(), strFileDst.c_str()));
2646
2647 GuestFileOpenInfo dstOpenInfo;
2648 dstOpenInfo.mFilename = strFileDst;
2649 dstOpenInfo.mOpenAction = FileOpenAction_CreateOrReplace;
2650 dstOpenInfo.mAccessMode = FileAccessMode_WriteOnly;
2651 dstOpenInfo.mSharingMode = FileSharingMode_All; /** @todo Use _Read when implemented. */
2652
2653 ComObjPtr<GuestFile> dstFile;
2654 int vrcGuest = VERR_IPE_UNINITIALIZED_STATUS;
2655 vrc = mSession->i_fileOpen(dstOpenInfo, dstFile, &vrcGuest);
2656 if (RT_FAILURE(vrc))
2657 {
2658 switch (vrc)
2659 {
2660 case VERR_GSTCTL_GUEST_ERROR:
2661 setUpdateErrorMsg(VBOX_E_GSTCTL_GUEST_ERROR,
2662 GuestFile::i_guestErrorToString(vrcGuest, strFileDst.c_str()));
2663 break;
2664
2665 default:
2666 setUpdateErrorMsg(VBOX_E_GSTCTL_GUEST_ERROR,
2667 Utf8StrFmt(tr("Guest file \"%s\" could not be opened: %Rrc"),
2668 strFileDst.c_str(), vrc));
2669 break;
2670 }
2671 }
2672 else
2673 {
2674 vrc = fileCopyToGuestInner(strFileSrc, hVfsFile, strFileDst, dstFile, FileCopyFlag_None, 0 /*offCopy*/, cbSrcSize);
2675
2676 int vrc2 = fileClose(dstFile);
2677 if (RT_SUCCESS(vrc))
2678 vrc = vrc2;
2679 }
2680 }
2681
2682 RTVfsFileRelease(hVfsFile);
2683 }
2684 else if (fOptional)
2685 vrc = VINF_SUCCESS;
2686
2687 return vrc;
2688}
2689
2690/**
2691 * Sets an update error message to the current progress object + logs to release log.
2692 *
2693 * @returns Returns \a hrc for convenience.
2694 * @param hrc Progress operation result to set.
2695 * @param strMsg Message to set.
2696 */
2697HRESULT GuestSessionTaskUpdateAdditions::setUpdateErrorMsg(HRESULT hrc, const Utf8Str &strMsg)
2698{
2699 Utf8Str const strLog = "Guest Additions Update failed: " + strMsg;
2700 LogRel(("%s\n", strLog.c_str()));
2701 return GuestSessionTask::setProgressErrorMsg(hrc, strLog);
2702}
2703
2704/**
2705 * Sets an update error message to the current progress object + logs to release log.
2706 *
2707 * @returns Returns \a hrc for convenience.
2708 * @param hrc Progress operation result to set.
2709 * @param strMsg Message to set.
2710 * @param guestErrorInfo Guest error info to use.
2711 */
2712HRESULT GuestSessionTaskUpdateAdditions::setUpdateErrorMsg(HRESULT hrc, const Utf8Str &strMsg, const GuestErrorInfo &guestErrorInfo)
2713{
2714 Utf8Str const strLog = strMsg + Utf8Str(": ") + GuestBase::getErrorAsString(guestErrorInfo);
2715 return GuestSessionTaskUpdateAdditions::setProgressErrorMsg(hrc, strLog);
2716}
2717
2718/**
2719 * Helper function to run (start) a file on the guest.
2720 *
2721 * @returns VBox status code.
2722 * @param pSession Guest session to use.
2723 * @param procInfo Guest process startup info to use.
2724 * @param fSilent Whether to set progress into failure state in case of error.
2725 */
2726int GuestSessionTaskUpdateAdditions::runFileOnGuest(GuestSession *pSession, GuestProcessStartupInfo &procInfo, bool fSilent)
2727{
2728 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
2729
2730#ifndef VBOX_WITH_GSTCTL_TOOLBOX_SUPPORT
2731 RT_NOREF(procInfo, fSilent);
2732 return VERR_NOT_SUPPORTED;
2733#else
2734 LogRel(("Guest Additions Update: Running \"%s\" ...\n", procInfo.mName.c_str()));
2735
2736 UpdateAdditionsProcess guestProc;
2737 int vrcGuest = VERR_IPE_UNINITIALIZED_STATUS;
2738 int vrc = guestProc.init(pSession, procInfo, false /* Async */, &vrcGuest);
2739 if (RT_SUCCESS(vrc))
2740 {
2741 if (RT_SUCCESS(vrcGuest))
2742 {
2743 vrc = guestProc.wait(&vrcGuest);
2744 if (RT_SUCCESS(vrc))
2745 vrc = guestProc.getTerminationStatus();
2746 else if (vrc == VERR_NOT_FOUND)
2747 /** @todo Linux Guest Additions terminate VBoxService when updating (via uninstall.sh),
2748 * which in turn terminates the Guest Control session this updater task was relying on.
2749 * This leads into a VERR_NOT_FOUND error, as the Guest Session is not around anymore.
2750 * Fend this off for now, but needs a clean(er) solution long-term. See @bugref{10776}. */
2751 vrc = VINF_SUCCESS;
2752 }
2753 }
2754
2755 if ( RT_FAILURE(vrc)
2756 && !fSilent)
2757 {
2758 Utf8Str cmdLine;
2759 for (size_t iArg = 0; iArg < procInfo.mArguments.size(); iArg++)
2760 {
2761 cmdLine.append(procInfo.mArguments.at(iArg));
2762 if (iArg < procInfo.mArguments.size() - 1)
2763 cmdLine.append(" ");
2764 }
2765
2766 switch (vrc)
2767 {
2768 case VERR_GSTCTL_PROCESS_EXIT_CODE:
2769 {
2770 int32_t iExitCode;
2771 vrc = guestProc.getTerminationStatus(&iExitCode);
2772 Assert(vrc == VERR_GSTCTL_PROCESS_EXIT_CODE);
2773 setUpdateErrorMsg(VBOX_E_GSTCTL_GUEST_ERROR,
2774 Utf8StrFmt(tr("Running update file \"%s\" on guest failed with exit code %d"),
2775 cmdLine.c_str(), iExitCode));
2776 break;
2777
2778 }
2779 case VERR_GSTCTL_GUEST_ERROR:
2780 setUpdateErrorMsg(VBOX_E_GSTCTL_GUEST_ERROR, tr("Running update file on guest failed"),
2781 GuestErrorInfo(GuestErrorInfo::Type_Process, vrcGuest, cmdLine.c_str()));
2782 break;
2783
2784 case VERR_INVALID_STATE: /** @todo Special guest control vrc needed! */
2785 setUpdateErrorMsg(VBOX_E_GSTCTL_GUEST_ERROR,
2786 Utf8StrFmt(tr("Update file \"%s\" reported invalid running state"),
2787 procInfo.mExecutable.c_str()));
2788 break;
2789
2790 default:
2791 setUpdateErrorMsg(VBOX_E_GSTCTL_GUEST_ERROR,
2792 Utf8StrFmt(tr("Error while running update command \"%s\" on guest: %Rrc"),
2793 cmdLine.c_str(), vrc));
2794 break;
2795 }
2796 }
2797
2798 return vrc;
2799#endif /* VBOX_WITH_GSTCTL_TOOLBOX_SUPPORT */
2800}
2801
2802/**
2803 * Helper function which checks Guest Additions installation status.
2804 *
2805 * @returns IPRT status code.
2806 * @param pSession Guest session to use.
2807 * @param osType Guest type.
2808 */
2809int GuestSessionTaskUpdateAdditions::checkGuestAdditionsStatus(GuestSession *pSession, eOSType osType)
2810{
2811 int vrc = VINF_SUCCESS;
2812 HRESULT hrc;
2813
2814 if (osType == eOSType_Linux)
2815 {
2816 const Utf8Str ksStatusScript = Utf8Str("/sbin/rcvboxadd");
2817
2818 /* Check if Guest Additions kernel modules were loaded. */
2819 GuestProcessStartupInfo procInfo;
2820 procInfo.mName = "Kernel modules status check";
2821 procInfo.mFlags = ProcessCreateFlag_None;
2822 procInfo.mExecutable = Utf8Str("/bin/sh");;
2823 procInfo.mArguments.push_back(procInfo.mExecutable); /* Set argv0. */
2824 procInfo.mArguments.push_back(ksStatusScript);
2825 procInfo.mArguments.push_back("status-kernel");
2826
2827 vrc = runFileOnGuest(pSession, procInfo, true /* fSilent */);
2828 if (RT_SUCCESS(vrc))
2829 {
2830 /* Replace the last argument with corresponding value and check
2831 * if Guest Additions user services were started. */
2832 procInfo.mName = "User services status check";
2833 procInfo.mArguments.pop_back();
2834 procInfo.mArguments.push_back("status-user");
2835
2836 vrc = runFileOnGuest(pSession, procInfo, true /* fSilent */);
2837 if (RT_FAILURE(vrc))
2838 hrc = setUpdateErrorMsg(VBOX_E_GSTCTL_GUEST_ERROR,
2839 Utf8StrFmt(tr("Files were installed, but user services were not reloaded automatically. "
2840 "Please consider rebooting the guest")));
2841 }
2842 else
2843 hrc = setUpdateErrorMsg(VBOX_E_GSTCTL_GUEST_ERROR,
2844 Utf8StrFmt(tr("Files were installed, but kernel modules were not reloaded automatically. "
2845 "Please consider rebooting the guest")));
2846 }
2847
2848 return vrc;
2849}
2850
2851/**
2852 * Helper function which waits until Guest Additions services started.
2853 *
2854 * Newly created guest session needs to be closed by caller.
2855 *
2856 * @returns 0 on success or VERR_TIMEOUT if guest services were not
2857 * started on time.
2858 * @param pGuest Guest interface to use.
2859 * @param osType Guest type.
2860 * @param pNewSession Output parameter for newly established guest type.
2861 */
2862int GuestSessionTaskUpdateAdditions::waitForGuestSession(ComObjPtr<Guest> pGuest, eOSType osType,
2863 ComObjPtr<GuestSession> &pNewSession)
2864{
2865 int vrc = VERR_GSTCTL_GUEST_ERROR;
2866 int vrcRet = VERR_TIMEOUT;
2867
2868 uint64_t tsStart = RTTimeSystemMilliTS();
2869 const uint64_t cMsTimeout = 10 * RT_MS_1MIN;
2870
2871 AssertReturn(!pGuest.isNull(), VERR_TIMEOUT);
2872
2873 do
2874 {
2875 GuestCredentials guestCreds;
2876 GuestSessionStartupInfo startupInfo;
2877
2878 startupInfo.mName = "Guest Additions connection check";
2879 startupInfo.mOpenTimeoutMS = 100;
2880
2881 vrc = pGuest->i_sessionCreate(startupInfo, guestCreds, pNewSession);
2882 if (RT_SUCCESS(vrc))
2883 {
2884 Assert(!pNewSession.isNull());
2885
2886 int vrcGuest = VERR_GSTCTL_GUEST_ERROR; /* unused. */
2887 vrc = pNewSession->i_startSession(&vrcGuest);
2888 if (RT_SUCCESS(vrc))
2889 {
2890 /* Wait for VBoxService to start. */
2891 GuestSessionWaitResult_T enmWaitResult = GuestSessionWaitResult_None;
2892 int vrcGuest2 = VINF_SUCCESS; /* unused. */
2893 vrc = pNewSession->i_waitFor(GuestSessionWaitForFlag_Start, 100 /* timeout, ms */, enmWaitResult, &vrcGuest2);
2894 if (RT_SUCCESS(vrc))
2895 {
2896 /* Make sure Guest Additions were reloaded on the guest side. */
2897 vrc = checkGuestAdditionsStatus(pNewSession, osType);
2898 if (RT_SUCCESS(vrc))
2899 LogRel(("Guest Additions Update: Guest Additions were successfully reloaded after installation\n"));
2900 else
2901 LogRel(("Guest Additions Update: Guest Additions were failed to reload after installation, please consider rebooting the guest\n"));
2902
2903 vrcRet = VINF_SUCCESS;
2904 break;
2905 }
2906 }
2907
2908 vrc = pNewSession->Close();
2909 }
2910
2911 RTThreadSleep(100);
2912
2913 } while ((RTTimeSystemMilliTS() - tsStart) < cMsTimeout);
2914
2915 return vrcRet;
2916}
2917
2918/**
2919 * Helper function which retrieves guest platform architecture information.
2920 *
2921 * @returns Platform architecture type or PlatformArchitecture_None if
2922 * architecture information cannot be retrieved.
2923 */
2924PlatformArchitecture_T GuestSessionTaskUpdateAdditions::getPlatformArch(void)
2925{
2926 HRESULT hrc;
2927 PlatformArchitecture_T enmArch = PlatformArchitecture_None;
2928
2929 ComObjPtr<GuestSession> pSession = mSession;
2930 Assert(!pSession.isNull());
2931
2932 ComObjPtr<Guest> pGuest(pSession->i_getParent());
2933 Assert(!pGuest.isNull());
2934
2935 ComObjPtr<Console> pConsole = pGuest->i_getConsole();
2936 Assert(!pConsole.isNull());
2937
2938 const ComPtr<IMachine> pMachine = pConsole->i_machine();
2939 Assert(!pMachine.isNull());
2940
2941 ComPtr<IPlatform> pPlatform;
2942
2943 hrc = pMachine->COMGETTER(Platform)(pPlatform.asOutParam());
2944 AssertComRCReturn(hrc, PlatformArchitecture_None);
2945
2946 hrc = pPlatform->COMGETTER(Architecture)(&enmArch);
2947 AssertComRCReturn(hrc, PlatformArchitecture_None);
2948
2949 return enmArch;
2950}
2951
2952/** @copydoc GuestSessionTask::Run */
2953int GuestSessionTaskUpdateAdditions::Run(void)
2954{
2955 LogFlowThisFuncEnter();
2956
2957 ComObjPtr<GuestSession> pSession = mSession;
2958 Assert(!pSession.isNull());
2959
2960 AutoCaller autoCaller(pSession);
2961 if (FAILED(autoCaller.hrc())) return autoCaller.hrc();
2962
2963 int vrc = setProgress(10);
2964 if (RT_FAILURE(vrc))
2965 return vrc;
2966
2967 HRESULT hrc = S_OK;
2968
2969 LogRel(("Guest Additions Update: Automatic update started, using \"%s\"\n", mSource.c_str()));
2970
2971 ComObjPtr<Guest> pGuest(mSession->i_getParent());
2972#if 0
2973 /*
2974 * Wait for the guest being ready within 30 seconds.
2975 */
2976 AdditionsRunLevelType_T addsRunLevel;
2977 uint64_t tsStart = RTTimeSystemMilliTS();
2978 while ( SUCCEEDED(hrc = pGuest->COMGETTER(AdditionsRunLevel)(&addsRunLevel))
2979 && ( addsRunLevel != AdditionsRunLevelType_Userland
2980 && addsRunLevel != AdditionsRunLevelType_Desktop))
2981 {
2982 if ((RTTimeSystemMilliTS() - tsStart) > GSTCTL_DEFAULT_TIMEOUT_MS)
2983 {
2984 vrc = VERR_TIMEOUT;
2985 break;
2986 }
2987
2988 RTThreadSleep(100); /* Wait a bit. */
2989 }
2990
2991 if (FAILED(hrc)) vrc = VERR_TIMEOUT;
2992 if (vrc == VERR_TIMEOUT)
2993 hrc = setUpdateErrorMsg(VBOX_E_NOT_SUPPORTED,
2994 Utf8StrFmt(tr("Guest Additions were not ready within time, giving up")));
2995#else
2996 /*
2997 * For use with the GUI we don't want to wait, just return so that the manual .ISO mounting
2998 * can continue.
2999 */
3000 AdditionsRunLevelType_T addsRunLevel;
3001 if ( FAILED(hrc = pGuest->COMGETTER(AdditionsRunLevel)(&addsRunLevel))
3002 || ( addsRunLevel != AdditionsRunLevelType_Userland
3003 && addsRunLevel != AdditionsRunLevelType_Desktop))
3004 {
3005 if (addsRunLevel == AdditionsRunLevelType_System)
3006 hrc = setUpdateErrorMsg(VBOX_E_NOT_SUPPORTED,
3007 Utf8StrFmt(tr("Guest Additions are installed but not fully loaded yet, aborting automatic update")));
3008 else
3009 hrc = setUpdateErrorMsg(VBOX_E_NOT_SUPPORTED,
3010 Utf8StrFmt(tr("Guest Additions not installed or ready, aborting automatic update")));
3011 vrc = VERR_NOT_SUPPORTED;
3012 }
3013#endif
3014
3015 if (RT_SUCCESS(vrc))
3016 {
3017 /*
3018 * Determine if we are able to update automatically. This only works
3019 * if there are recent Guest Additions installed already.
3020 */
3021 Utf8Str strAddsVer;
3022 vrc = getGuestProperty(pGuest, "/VirtualBox/GuestAdd/Version", strAddsVer);
3023 if ( RT_SUCCESS(vrc)
3024 && RTStrVersionCompare(strAddsVer.c_str(), "4.1") < 0)
3025 {
3026 hrc = setUpdateErrorMsg(VBOX_E_NOT_SUPPORTED,
3027 Utf8StrFmt(tr("Guest has too old Guest Additions (%s) installed for automatic updating, please update manually"),
3028 strAddsVer.c_str()));
3029 vrc = VERR_NOT_SUPPORTED;
3030 }
3031 }
3032
3033 Utf8Str strOSVer;
3034 eOSType osType = eOSType_Unknown;
3035 if (RT_SUCCESS(vrc))
3036 {
3037 /*
3038 * Determine guest OS type and the required installer image.
3039 */
3040/** @todo r=bird: Why are we using the guest properties for this instead of the
3041 * reported guest VBOXOSTYPE/ID? Since we've got guest properties, we must
3042 * have GAs, so the guest additions must've reported the guest OS type. That
3043 * would allow proper OS categorization by family ID instead of this ridiculous
3044 * naive code assuming anything that isn't windows or solaris must be linux. */
3045 Utf8Str strOSType;
3046 vrc = getGuestProperty(pGuest, "/VirtualBox/GuestInfo/OS/Product", strOSType);
3047 if (RT_SUCCESS(vrc))
3048 {
3049 if ( strOSType.contains(GUEST_OS_ID_STR_PARTIAL("Microsoft"), Utf8Str::CaseInsensitive)
3050 || strOSType.contains(GUEST_OS_ID_STR_PARTIAL("Windows"), Utf8Str::CaseInsensitive))
3051 {
3052 osType = eOSType_Windows;
3053
3054 /*
3055 * Determine guest OS version.
3056 */
3057 vrc = getGuestProperty(pGuest, "/VirtualBox/GuestInfo/OS/Release", strOSVer);
3058 if (RT_FAILURE(vrc))
3059 {
3060 hrc = setUpdateErrorMsg(VBOX_E_NOT_SUPPORTED,
3061 Utf8StrFmt(tr("Unable to detected guest OS version, please update manually")));
3062 vrc = VERR_NOT_SUPPORTED;
3063 }
3064
3065 /* Because Windows 2000 + XP and is bitching with WHQL popups even if we have signed drivers we
3066 * can't do automated updates here. */
3067 /* Windows XP 64-bit (5.2) is a Windows 2003 Server actually, so skip this here. */
3068 if ( RT_SUCCESS(vrc)
3069 && RTStrVersionCompare(strOSVer.c_str(), "5.0") >= 0)
3070 {
3071 if ( strOSVer.startsWith("5.0") /* Exclude the build number. */
3072 || strOSVer.startsWith("5.1") /* Exclude the build number. */)
3073 {
3074 /* If we don't have AdditionsUpdateFlag_WaitForUpdateStartOnly set we can't continue
3075 * because the Windows Guest Additions installer will fail because of WHQL popups. If the
3076 * flag is set this update routine ends successfully as soon as the installer was started
3077 * (and the user has to deal with it in the guest). */
3078 if (!(mFlags & AdditionsUpdateFlag_WaitForUpdateStartOnly))
3079 {
3080 hrc = setUpdateErrorMsg(VBOX_E_NOT_SUPPORTED,
3081 Utf8StrFmt(tr("Windows 2000 and XP are not supported for automatic updating due to WHQL interaction, please update manually")));
3082 vrc = VERR_NOT_SUPPORTED;
3083 }
3084 }
3085 }
3086 else
3087 {
3088 hrc = setUpdateErrorMsg(VBOX_E_NOT_SUPPORTED,
3089 Utf8StrFmt(tr("%s (%s) not supported for automatic updating, please update manually"),
3090 strOSType.c_str(), strOSVer.c_str()));
3091 vrc = VERR_NOT_SUPPORTED;
3092 }
3093 }
3094 else if (strOSType.contains(GUEST_OS_ID_STR_PARTIAL("Solaris"), Utf8Str::CaseInsensitive))
3095 {
3096 osType = eOSType_Solaris;
3097 }
3098 else /* Everything else hopefully means Linux :-). */
3099 osType = eOSType_Linux;
3100
3101 if ( RT_SUCCESS(vrc)
3102 && ( osType != eOSType_Windows
3103 && osType != eOSType_Linux))
3104 /** @todo Support Solaris. */
3105 {
3106 hrc = setUpdateErrorMsg(VBOX_E_NOT_SUPPORTED,
3107 Utf8StrFmt(tr("Detected guest OS (%s) does not support automatic Guest Additions updating, please update manually"),
3108 strOSType.c_str()));
3109 vrc = VERR_NOT_SUPPORTED;
3110 }
3111 }
3112 }
3113
3114 if (RT_SUCCESS(vrc))
3115 {
3116 /*
3117 * Try to open the .ISO file to extract all needed files.
3118 */
3119 RTVFSFILE hVfsFileIso;
3120 vrc = RTVfsFileOpenNormal(mSource.c_str(), RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_WRITE, &hVfsFileIso);
3121 if (RT_FAILURE(vrc))
3122 {
3123 hrc = setUpdateErrorMsg(VBOX_E_IPRT_ERROR,
3124 Utf8StrFmt(tr("Unable to open Guest Additions .ISO file \"%s\": %Rrc"),
3125 mSource.c_str(), vrc));
3126 }
3127 else
3128 {
3129 RTVFS hVfsIso;
3130 vrc = RTFsIso9660VolOpen(hVfsFileIso, 0 /*fFlags*/, &hVfsIso, NULL);
3131 if (RT_FAILURE(vrc))
3132 {
3133 hrc = setUpdateErrorMsg(VBOX_E_IPRT_ERROR,
3134 Utf8StrFmt(tr("Unable to open file as ISO 9660 file system volume: %Rrc"), vrc));
3135 }
3136 else
3137 {
3138 if (RT_SUCCESS(vrc))
3139 vrc = setProgress(5);
3140
3141 Utf8Str strUpdateDir;
3142
3143 /*
3144 * Prepare the update directory.
3145 */
3146 if (RT_SUCCESS(vrc))
3147 {
3148 /* Note: No fallback to unsafe guest locations! See @bugref{10625}. */
3149 int vrcGuest;
3150 vrc = pSession->i_fsCreateTemp("VBoxAutoUpdate-XXXXXXXXXXXX", "" /* Use default temp dir */,
3151 true /* fDirectory */, strUpdateDir, 755 /* Mode */, false /* fSecure */, &vrcGuest);
3152 if (RT_SUCCESS(vrc))
3153 {
3154 if (osType == eOSType_Windows)
3155 strUpdateDir.append("\\");
3156 else
3157 strUpdateDir.append("/");
3158
3159 LogRel(("Guest Additions Update: Update directory is '%s'\n", strUpdateDir.c_str()));
3160 }
3161 else
3162 {
3163 switch (vrc)
3164 {
3165 case VERR_GSTCTL_GUEST_ERROR:
3166 hrc = setUpdateErrorMsg(VBOX_E_IPRT_ERROR, tr("Creating update directory on guest failed"),
3167 GuestErrorInfo(GuestErrorInfo::Type_Directory, vrcGuest, strUpdateDir.c_str()));
3168 break;
3169
3170 default:
3171 hrc = setUpdateErrorMsg(VBOX_E_IPRT_ERROR,
3172 Utf8StrFmt(tr("Creating update directory \"%s\" on guest failed: %Rrc"),
3173 strUpdateDir.c_str(), vrc));
3174 break;
3175 }
3176 }
3177 }
3178
3179 if (RT_SUCCESS(vrc))
3180 vrc = setProgress(10);
3181
3182 if (RT_SUCCESS(vrc))
3183 {
3184 /* Prepare the file(s) we want to copy over to the guest and
3185 * (maybe) want to run. */
3186 switch (osType)
3187 {
3188 case eOSType_Windows:
3189 {
3190 /* Do we need to install our certificates? We do this for W2K and up. */
3191 bool fInstallCert = false;
3192
3193 /* Only Windows 2000 and up need certificates to be installed. */
3194 if (RTStrVersionCompare(strOSVer.c_str(), "5.0") >= 0)
3195 {
3196 fInstallCert = true;
3197 LogRel(("Guest Additions Update: Certificates for auto updating WHQL drivers will be installed\n"));
3198 }
3199 else
3200 LogRel(("Guest Additions Update: Skipping installation of certificates for WHQL drivers\n"));
3201
3202 if (fInstallCert)
3203 {
3204 static struct { const char *pszDst, *pszIso; } const s_aCertFiles[] =
3205 {
3206 { "vbox.cer", "/CERT/VBOX.CER" },
3207 { "vbox-sha1.cer", "/CERT/VBOX-SHA1.CER" },
3208 { "vbox-sha256.cer", "/CERT/VBOX-SHA256.CER" },
3209 { "vbox-sha256-r3.cer", "/CERT/VBOX-SHA256-R3.CER" },
3210 { "oracle-vbox.cer", "/CERT/ORACLE-VBOX.CER" },
3211 };
3212 uint32_t fCopyCertUtil = ISOFILE_FLAG_COPY_FROM_ISO;
3213 for (uint32_t i = 0; i < RT_ELEMENTS(s_aCertFiles); i++)
3214 {
3215 /* Skip if not present on the ISO. */
3216 RTFSOBJINFO ObjInfo;
3217 vrc = RTVfsQueryPathInfo(hVfsIso, s_aCertFiles[i].pszIso, &ObjInfo, RTFSOBJATTRADD_NOTHING,
3218 RTPATH_F_ON_LINK);
3219 if (RT_FAILURE(vrc))
3220 continue;
3221
3222 /* Copy the certificate certificate. */
3223 Utf8Str const strDstCert(strUpdateDir + s_aCertFiles[i].pszDst);
3224 mFiles.push_back(ISOFile(s_aCertFiles[i].pszIso,
3225 strDstCert,
3226 ISOFILE_FLAG_COPY_FROM_ISO | ISOFILE_FLAG_OPTIONAL));
3227
3228 /* Out certificate installation utility. */
3229 /* First pass: Copy over the file (first time only) + execute it to remove any
3230 * existing VBox certificates. */
3231 UpdateAdditionsStartupInfo siCertUtilRem;
3232 siCertUtilRem.mName = "VirtualBox Certificate Utility, removing old VirtualBox certificates";
3233 /* The argv[0] should contain full path to the executable module */
3234 siCertUtilRem.mArguments.push_back(strUpdateDir + "VBoxCertUtil.exe");
3235 siCertUtilRem.mArguments.push_back(Utf8Str("remove-trusted-publisher"));
3236 siCertUtilRem.mArguments.push_back(Utf8Str("--root")); /* Add root certificate as well. */
3237 siCertUtilRem.mArguments.push_back(strDstCert);
3238 siCertUtilRem.mArguments.push_back(strDstCert);
3239 mFiles.push_back(ISOFile("CERT/VBOXCERTUTIL.EXE",
3240 strUpdateDir + "VBoxCertUtil.exe",
3241 fCopyCertUtil | ISOFILE_FLAG_EXECUTE | ISOFILE_FLAG_OPTIONAL,
3242 siCertUtilRem));
3243 fCopyCertUtil = 0;
3244 /* Second pass: Only execute (but don't copy) again, this time installng the
3245 * recent certificates just copied over. */
3246 UpdateAdditionsStartupInfo siCertUtilAdd;
3247 siCertUtilAdd.mName = "VirtualBox Certificate Utility, installing VirtualBox certificates";
3248 /* The argv[0] should contain full path to the executable module */
3249 siCertUtilAdd.mArguments.push_back(strUpdateDir + "VBoxCertUtil.exe");
3250 siCertUtilAdd.mArguments.push_back(Utf8Str("add-trusted-publisher"));
3251 siCertUtilAdd.mArguments.push_back(Utf8Str("--root")); /* Add root certificate as well. */
3252 siCertUtilAdd.mArguments.push_back(strDstCert);
3253 siCertUtilAdd.mArguments.push_back(strDstCert);
3254 mFiles.push_back(ISOFile("CERT/VBOXCERTUTIL.EXE",
3255 strUpdateDir + "VBoxCertUtil.exe",
3256 ISOFILE_FLAG_EXECUTE | ISOFILE_FLAG_OPTIONAL,
3257 siCertUtilAdd));
3258 }
3259 }
3260 /* The installers in different flavors, as we don't know (and can't assume)
3261 * the guest's bitness. */
3262 mFiles.push_back(ISOFile("VBOXWINDOWSADDITIONS-X86.EXE",
3263 strUpdateDir + "VBoxWindowsAdditions-x86.exe",
3264 ISOFILE_FLAG_COPY_FROM_ISO));
3265 mFiles.push_back(ISOFile("VBOXWINDOWSADDITIONS-AMD64.EXE",
3266 strUpdateDir + "VBoxWindowsAdditions-amd64.exe",
3267 ISOFILE_FLAG_COPY_FROM_ISO));
3268 /* The stub loader which decides which flavor to run. */
3269 UpdateAdditionsStartupInfo siInstaller;
3270 siInstaller.mName = "VirtualBox Windows Guest Additions Installer";
3271 /* Set a running timeout of 5 minutes -- the Windows Guest Additions
3272 * setup can take quite a while, so be on the safe side. */
3273 siInstaller.mTimeoutMS = 5 * 60 * 1000;
3274
3275 /* The argv[0] should contain full path to the executable module */
3276 siInstaller.mArguments.push_back(strUpdateDir + "VBoxWindowsAdditions.exe");
3277 siInstaller.mArguments.push_back(Utf8Str("/S")); /* We want to install in silent mode. */
3278 siInstaller.mArguments.push_back(Utf8Str("/l")); /* ... and logging enabled. */
3279 /* Don't quit VBoxService during upgrade because it still is used for this
3280 * piece of code we're in right now (that is, here!) ... */
3281 siInstaller.mArguments.push_back(Utf8Str("/no_vboxservice_exit"));
3282 /* Tell the installer to report its current installation status
3283 * using a running VBoxTray instance via balloon messages in the
3284 * Windows taskbar. */
3285 siInstaller.mArguments.push_back(Utf8Str("/post_installstatus"));
3286 /* Add optional installer command line arguments from the API to the
3287 * installer's startup info. */
3288 vrc = addProcessArguments(siInstaller.mArguments, mArguments);
3289 AssertRC(vrc);
3290 /* If the caller does not want to wait for out guest update process to end,
3291 * complete the progress object now so that the caller can do other work. */
3292 if (mFlags & AdditionsUpdateFlag_WaitForUpdateStartOnly)
3293 siInstaller.mFlags |= ProcessCreateFlag_WaitForProcessStartOnly;
3294 mFiles.push_back(ISOFile("VBOXWINDOWSADDITIONS.EXE",
3295 strUpdateDir + "VBoxWindowsAdditions.exe",
3296 ISOFILE_FLAG_COPY_FROM_ISO | ISOFILE_FLAG_EXECUTE, siInstaller));
3297 break;
3298 }
3299 case eOSType_Linux:
3300 {
3301 bool fIsArm = getPlatformArch() == PlatformArchitecture_ARM;
3302
3303 const Utf8Str strInstallerBinUC("VBOXLINUXADDITIONS" + Utf8Str(fIsArm ? "-ARM64" : "") + ".RUN");
3304 const Utf8Str strInstallerBin ("VBoxLinuxAdditions" + Utf8Str(fIsArm ? "-arm64" : "") + ".run");
3305
3306 /* Copy over the installer to the guest but don't execute it.
3307 * Execution will be done by the shell instead. */
3308 mFiles.push_back(ISOFile(strInstallerBinUC, strUpdateDir + strInstallerBin, ISOFILE_FLAG_COPY_FROM_ISO));
3309
3310 UpdateAdditionsStartupInfo siInstaller;
3311 siInstaller.mName = "VirtualBox Linux Guest Additions Installer";
3312 /* Set a running timeout of 5 minutes -- compiling modules and stuff for the Linux Guest Additions
3313 * setup can take quite a while, so be on the safe side. */
3314 siInstaller.mTimeoutMS = 5 * 60 * 1000;
3315 /* The argv[0] should contain full path to the shell we're using to execute the installer. */
3316 siInstaller.mArguments.push_back("/bin/sh");
3317 /* Now add the stuff we need in order to execute the installer. */
3318 siInstaller.mArguments.push_back(strUpdateDir + strInstallerBin);
3319 /* Make sure to add "--nox11" to the makeself wrapper in order to not getting any blocking xterm
3320 * window spawned when doing any unattended Linux GA installations. */
3321 siInstaller.mArguments.push_back("--nox11");
3322 siInstaller.mArguments.push_back("--");
3323 /* Force the upgrade. Needed in order to skip the confirmation dialog about warning to upgrade. */
3324 siInstaller.mArguments.push_back("--force"); /** @todo We might want a dedicated "--silent" switch here. */
3325 /* If the caller does not want to wait for out guest update process to end,
3326 * complete the progress object now so that the caller can do other work. */
3327 if (mFlags & AdditionsUpdateFlag_WaitForUpdateStartOnly)
3328 siInstaller.mFlags |= ProcessCreateFlag_WaitForProcessStartOnly;
3329 mFiles.push_back(ISOFile("/bin/sh" /* Source */, "/bin/sh" /* Dest */,
3330 ISOFILE_FLAG_EXECUTE, siInstaller));
3331 break;
3332 }
3333 case eOSType_Solaris:
3334 /** @todo Add Solaris support. */
3335 break;
3336 default:
3337 AssertReleaseMsgFailed(("Unsupported guest type: %d\n", osType));
3338 break;
3339 }
3340 }
3341
3342 if (RT_SUCCESS(vrc))
3343 {
3344 /* We want to spend 40% total for all copying operations. So roughly
3345 * calculate the specific percentage step of each copied file. */
3346 uint8_t uOffset = 20; /* Start at 20%. */
3347 uint8_t uStep = 40 / (uint8_t)mFiles.size(); Assert(mFiles.size() <= 10);
3348
3349 LogRel(("Guest Additions Update: Copying over update files to the guest ...\n"));
3350
3351 std::vector<ISOFile>::const_iterator itFiles = mFiles.begin();
3352 while (itFiles != mFiles.end())
3353 {
3354 if (itFiles->fFlags & ISOFILE_FLAG_COPY_FROM_ISO)
3355 {
3356 bool fOptional = false;
3357 if (itFiles->fFlags & ISOFILE_FLAG_OPTIONAL)
3358 fOptional = true;
3359 vrc = copyFileToGuest(pSession, hVfsIso, itFiles->strSource, itFiles->strDest, fOptional);
3360 if (RT_FAILURE(vrc))
3361 {
3362 hrc = setUpdateErrorMsg(VBOX_E_IPRT_ERROR,
3363 Utf8StrFmt(tr("Error while copying file \"%s\" to \"%s\" on the guest: %Rrc"),
3364 itFiles->strSource.c_str(), itFiles->strDest.c_str(), vrc));
3365 break;
3366 }
3367 }
3368
3369 vrc = setProgress(uOffset);
3370 if (RT_FAILURE(vrc))
3371 break;
3372 uOffset += uStep;
3373
3374 ++itFiles;
3375 }
3376 }
3377
3378 /* Done copying, close .ISO file. */
3379 RTVfsRelease(hVfsIso);
3380
3381 if (RT_SUCCESS(vrc))
3382 {
3383 /* We want to spend 35% total for all copying operations. So roughly
3384 * calculate the specific percentage step of each copied file. */
3385 uint8_t uOffset = 60; /* Start at 60%. */
3386 uint8_t uStep = 35 / (uint8_t)mFiles.size(); Assert(mFiles.size() <= 10);
3387
3388 LogRel(("Guest Additions Update: Executing update files ...\n"));
3389
3390 std::vector<ISOFile>::iterator itFiles = mFiles.begin();
3391 while (itFiles != mFiles.end())
3392 {
3393 if (itFiles->fFlags & ISOFILE_FLAG_EXECUTE)
3394 {
3395 vrc = runFileOnGuest(pSession, itFiles->mProcInfo);
3396 if (RT_FAILURE(vrc))
3397 break;
3398 }
3399
3400 vrc = setProgress(uOffset);
3401 if (RT_FAILURE(vrc))
3402 break;
3403 uOffset += uStep;
3404
3405 ++itFiles;
3406 }
3407 }
3408
3409 if (RT_SUCCESS(vrc))
3410 {
3411 /* Linux Guest Additions will restart VBoxService during installation process.
3412 * In this case, connection to the guest will be temporary lost until new
3413 * kernel modules will be rebuilt, loaded and new VBoxService restarted.
3414 * Handle this case here: check if old connection was terminated and
3415 * new one has started. */
3416 if (osType == eOSType_Linux)
3417 {
3418 if (pSession->i_isTerminated())
3419 {
3420 LogRel(("Guest Additions Update: Old guest session has terminated, waiting updated guest services to start\n"));
3421
3422 /* Wait for VBoxService to restart and re-establish guest session. */
3423 vrc = waitForGuestSession(pSession->i_getParent(), osType, pSession);
3424 if (RT_FAILURE(vrc))
3425 hrc = setUpdateErrorMsg(VBOX_E_IPRT_ERROR,
3426 Utf8StrFmt(tr("Guest services were not restarted, please reinstall Guest Additions manually")));
3427 }
3428 else
3429 {
3430 vrc = VERR_TRY_AGAIN;
3431 hrc = setUpdateErrorMsg(VBOX_E_IPRT_ERROR,
3432 Utf8StrFmt(tr("Old guest session is still active, guest services were not restarted "
3433 "after installation, please reinstall Guest Additions manually")));
3434 }
3435 }
3436
3437 /* Remove temporary update files on the guest side before reporting completion.
3438 * Only enabled for Linux guest for now. Windows has issues w/ deletting temporary
3439 * installation directory. */
3440 if ((osType == eOSType_Linux) && !pSession->i_isTerminated())
3441 {
3442 hrc = pSession->i_directoryRemove(strUpdateDir, DIRREMOVEREC_FLAG_RECURSIVE | DIRREMOVEREC_FLAG_CONTENT_AND_DIR, &vrc);
3443 LogRel(("Cleanup Guest Additions update directory '%s', hrc=%Rrc, vrc=%Rrc\n",
3444 strUpdateDir.c_str(), hrc, vrc));
3445 }
3446
3447 if (RT_SUCCESS(vrc))
3448 {
3449 LogRel(("Guest Additions Update: Automatic update succeeded\n"));
3450 hrc = setProgressSuccess();
3451 }
3452 }
3453 }
3454
3455 RTVfsFileRelease(hVfsFileIso);
3456 }
3457 }
3458
3459 if (RT_FAILURE(vrc))
3460 {
3461 if (vrc == VERR_CANCELLED)
3462 {
3463 LogRel(("Guest Additions Update: Automatic update was canceled\n"));
3464 setUpdateErrorMsg(E_ABORT, Utf8StrFmt(tr("Operation was canceled")));
3465 }
3466 else if (vrc == VERR_TIMEOUT)
3467 {
3468 LogRel(("Guest Additions Update: Automatic update has timed out\n"));
3469 setUpdateErrorMsg(E_FAIL, Utf8StrFmt(tr("Operation has timed out")));
3470 }
3471 else
3472 {
3473 Utf8Str strError = Utf8StrFmt("No further error information available (%Rrc)", vrc);
3474 if (!mProgress.isNull()) /* Progress object is optional. */
3475 {
3476#ifdef VBOX_STRICT
3477 /* If we forgot to set the progress object accordingly, let us know. */
3478 LONG rcProgress;
3479 AssertMsg( SUCCEEDED(mProgress->COMGETTER(ResultCode(&rcProgress)))
3480 && FAILED(rcProgress), ("Task indicated an error (%Rrc), but progress did not indicate this (%Rhrc)\n",
3481 vrc, rcProgress));
3482#endif
3483 com::ProgressErrorInfo errorInfo(mProgress);
3484 if ( errorInfo.isFullAvailable()
3485 || errorInfo.isBasicAvailable())
3486 {
3487 strError = errorInfo.getText();
3488 }
3489 }
3490
3491 LogRel(("Guest Additions Update: Automatic update failed: %s (vrc=%Rrc, hrc=%Rhrc)\n",
3492 strError.c_str(), vrc, hrc));
3493 }
3494
3495 LogRel(("Guest Additions Update: An error has occurred (see above). Please install Guest Additions manually\n"));
3496 }
3497
3498 /** @todo Clean up copied / left over installation files. */
3499
3500 LogFlowFuncLeaveRC(vrc);
3501 return vrc;
3502}
3503
Note: See TracBrowser for help on using the repository browser.

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