VirtualBox

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

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

Guest Control/GuestSessionImplTasks: Logging nits.

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

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