HRESULT GuestDnD::adjustScreenCoordinates(ULONG uScreenId, ULONG *puX, ULONG *puY) const { /** @todo r=andy Save the current screen's shifting coordinates to speed things up. * Only query for new offsets when the screen ID has changed. */ /* For multi-monitor support we need to add shift values to the coordinates * (depending on the screen number). */ ComObjPtr<Console> pConsole = m_pGuest->i_getConsole(); ComPtr<IDisplay> pDisplay; HRESULT hr = pConsole->COMGETTER(Display)(pDisplay.asOutParam()); if (FAILED(hr)) return hr; ULONG dummy; LONG xShift, yShift; GuestMonitorStatus_T monitorStatus; hr = pDisplay->GetScreenResolution(uScreenId, &dummy, &dummy, &dummy, &xShift, &yShift, &monitorStatus); if (FAILED(hr)) return hr; if (puX) *puX += xShift; if (puY) *puY += yShift; LogFlowFunc(("uScreenId=%RU32, x=%RU32, y=%RU32\n", uScreenId, puX ? *puX : 0, puY ? *puY : 0)); return S_OK; }
int GuestObject::callbackAdd(GuestCtrlCallback *pCallback, uint32_t *puContextID) { const ComObjPtr<GuestSession> pSession(mObject.mSession); Assert(!pSession.isNull()); ULONG uSessionID = 0; pSession->COMGETTER(Id)(&uSessionID); /* Create a new context ID and assign it. */ int vrc = VERR_NOT_FOUND; ULONG uCount = mObject.mNextContextID++; ULONG uNewContextID = 0; ULONG uTries = 0; for (;;) { if (uCount == VBOX_GUESTCTRL_MAX_CONTEXTS) uCount = 0; /* Create a new context ID ... */ uNewContextID = VBOX_GUESTCTRL_CONTEXTID_MAKE(uSessionID, mObject.mObjectID, uCount); /* Is the context ID already used? Try next ID ... */ if (!callbackExists(uCount)) { /* Callback with context ID was not found. This means * we can use this context ID for our new callback we want * to add below. */ vrc = VINF_SUCCESS; break; } uCount++; if (++uTries == UINT32_MAX) break; /* Don't try too hard. */ } if (RT_SUCCESS(vrc)) { /* Add callback with new context ID to our callback map. * Note: This is *not* uNewContextID (which also includes * the session + process ID), just the context count * will be used here. */ mObject.mCallbacks[uCount] = pCallback; Assert(mObject.mCallbacks.size()); /* Report back new context ID. */ if (puContextID) *puContextID = uNewContextID; LogFlowThisFunc(("Added new callback (Session: %RU32, Object: %RU32, Count: %RU32) CID=%RU32\n", uSessionID, mObject.mObjectID, uCount, uNewContextID)); } return vrc; }
/* static */ HRESULT GuestTask::setProgressErrorInfo(HRESULT hr, ComObjPtr<Progress> pProgress, const char *pszText, ...) { BOOL fCanceled; BOOL fCompleted; if ( SUCCEEDED(pProgress->COMGETTER(Canceled(&fCanceled))) && !fCanceled && SUCCEEDED(pProgress->COMGETTER(Completed(&fCompleted))) && !fCompleted) { va_list va; va_start(va, pszText); HRESULT hr2 = pProgress->notifyCompleteV(hr, COM_IIDOF(IGuest), Guest::getStaticComponentName(), pszText, va); va_end(va); if (hr2 == S_OK) /* If unable to retrieve error, return input error. */ hr2 = hr; return hr2; } return S_OK; }
HRESULT Guest::taskUpdateGuestAdditions(GuestTask *aTask) { LogFlowFuncEnter(); AutoCaller autoCaller(this); if (FAILED(autoCaller.rc())) return autoCaller.rc(); /* * Do *not* take a write lock here since we don't (and won't) * touch any class-specific data (of IGuest) here - only the member functions * which get called here can do that. */ HRESULT rc = S_OK; BOOL fCompleted; BOOL fCanceled; try { ComObjPtr<Guest> pGuest = aTask->pGuest; aTask->pProgress->SetCurrentOperationProgress(10); /* * Determine guest OS type and the required installer image. * At the moment only Windows guests are supported. */ Utf8Str installerImage; Bstr osTypeId; if ( SUCCEEDED(pGuest->COMGETTER(OSTypeId(osTypeId.asOutParam()))) && !osTypeId.isEmpty()) { Utf8Str osTypeIdUtf8(osTypeId); /* Needed for .contains(). */ if ( osTypeIdUtf8.contains("Microsoft", Utf8Str::CaseInsensitive) || osTypeIdUtf8.contains("Windows", Utf8Str::CaseInsensitive)) { if (osTypeIdUtf8.contains("64", Utf8Str::CaseInsensitive)) installerImage = "VBOXWINDOWSADDITIONS_AMD64.EXE"; else installerImage = "VBOXWINDOWSADDITIONS_X86.EXE"; /* Since the installers are located in the root directory, * no further path processing needs to be done (yet). */ } else /* Everything else is not supported (yet). */ throw GuestTask::setProgressErrorInfo(VBOX_E_NOT_SUPPORTED, aTask->pProgress, Guest::tr("Detected guest OS (%s) does not support automatic Guest Additions updating, please update manually"), osTypeIdUtf8.c_str()); } else throw GuestTask::setProgressErrorInfo(VBOX_E_NOT_SUPPORTED, aTask->pProgress, Guest::tr("Could not detected guest OS type/version, please update manually")); Assert(!installerImage.isEmpty()); /* * Try to open the .ISO file and locate the specified installer. */ RTISOFSFILE iso; int vrc = RTIsoFsOpen(&iso, aTask->strSource.c_str()); if (RT_FAILURE(vrc)) { rc = GuestTask::setProgressErrorInfo(VBOX_E_FILE_ERROR, aTask->pProgress, Guest::tr("Invalid installation medium detected: \"%s\""), aTask->strSource.c_str()); } else { uint32_t cbOffset; size_t cbLength; vrc = RTIsoFsGetFileInfo(&iso, installerImage.c_str(), &cbOffset, &cbLength); if ( RT_SUCCESS(vrc) && cbOffset && cbLength) { vrc = RTFileSeek(iso.file, cbOffset, RTFILE_SEEK_BEGIN, NULL); if (RT_FAILURE(vrc)) rc = GuestTask::setProgressErrorInfo(VBOX_E_IPRT_ERROR, aTask->pProgress, Guest::tr("Could not seek to setup file on installation medium \"%s\" (%Rrc)"), aTask->strSource.c_str(), vrc); } else { switch (vrc) { case VERR_FILE_NOT_FOUND: rc = GuestTask::setProgressErrorInfo(VBOX_E_IPRT_ERROR, aTask->pProgress, Guest::tr("Setup file was not found on installation medium \"%s\""), aTask->strSource.c_str()); break; default: rc = GuestTask::setProgressErrorInfo(VBOX_E_IPRT_ERROR, aTask->pProgress, Guest::tr("An unknown error (%Rrc) occured while retrieving information of setup file on installation medium \"%s\""), vrc, aTask->strSource.c_str()); break; } } /* Specify the ouput path on the guest side. */ Utf8Str strInstallerPath = "%TEMP%\\VBoxWindowsAdditions.exe"; if (RT_SUCCESS(vrc)) { /* Okay, we're ready to start our copy routine on the guest! */ aTask->pProgress->SetCurrentOperationProgress(15); /* Prepare command line args. */ com::SafeArray<IN_BSTR> args; com::SafeArray<IN_BSTR> env; args.push_back(Bstr("--output").raw()); /* We want to write a file ... */ args.push_back(Bstr(strInstallerPath.c_str()).raw()); /* ... with this path. */ if (SUCCEEDED(rc)) { ComPtr<IProgress> progressCat; ULONG uPID; /* * Start built-in "vbox_cat" tool (inside VBoxService) to * copy over/pipe the data into a file on the guest (with * system rights, no username/password specified). */ rc = pGuest->executeProcessInternal(Bstr(VBOXSERVICE_TOOL_CAT).raw(), ExecuteProcessFlag_Hidden | ExecuteProcessFlag_WaitForProcessStartOnly, ComSafeArrayAsInParam(args), ComSafeArrayAsInParam(env), Bstr("").raw() /* Username. */, Bstr("").raw() /* Password */, 5 * 1000 /* Wait 5s for getting the process started. */, &uPID, progressCat.asOutParam(), &vrc); if (FAILED(rc)) { /* Errors which return VBOX_E_NOT_SUPPORTED can be safely skipped by the caller * to silently fall back to "normal" (old) .ISO mounting. */ /* Due to a very limited COM error range we use vrc for a more detailed error * lookup to figure out what went wrong. */ switch (vrc) { /* Guest execution service is not (yet) ready. This basically means that either VBoxService * is not running (yet) or that the Guest Additions are too old (because VBoxService does not * support the guest execution feature in this version). */ case VERR_NOT_FOUND: LogRel(("Guest Additions seem not to be installed yet\n")); rc = GuestTask::setProgressErrorInfo(VBOX_E_NOT_SUPPORTED, aTask->pProgress, Guest::tr("Guest Additions seem not to be installed or are not ready to update yet")); break; /* Getting back a VERR_INVALID_PARAMETER indicates that the installed Guest Additions are supporting the guest * execution but not the built-in "vbox_cat" tool of VBoxService (< 4.0). */ case VERR_INVALID_PARAMETER: LogRel(("Guest Additions are installed but don't supported automatic updating\n")); rc = GuestTask::setProgressErrorInfo(VBOX_E_NOT_SUPPORTED, aTask->pProgress, Guest::tr("Installed Guest Additions do not support automatic updating")); break; case VERR_TIMEOUT: LogRel(("Guest was unable to start copying the Guest Additions setup within time\n")); rc = GuestTask::setProgressErrorInfo(E_FAIL, aTask->pProgress, Guest::tr("Guest was unable to start copying the Guest Additions setup within time")); break; default: rc = GuestTask::setProgressErrorInfo(E_FAIL, aTask->pProgress, Guest::tr("Error copying Guest Additions setup file to guest path \"%s\" (%Rrc)"), strInstallerPath.c_str(), vrc); break; } } else { LogRel(("Automatic update of Guest Additions started, using \"%s\"\n", aTask->strSource.c_str())); LogRel(("Copying Guest Additions installer \"%s\" to \"%s\" on guest ...\n", installerImage.c_str(), strInstallerPath.c_str())); aTask->pProgress->SetCurrentOperationProgress(20); /* Wait for process to exit ... */ SafeArray<BYTE> aInputData(_64K); while ( SUCCEEDED(progressCat->COMGETTER(Completed(&fCompleted))) && !fCompleted) { size_t cbRead; /* cbLength contains remaining bytes of our installer file * opened above to read. */ size_t cbToRead = RT_MIN(cbLength, _64K); if (cbToRead) { vrc = RTFileRead(iso.file, (uint8_t*)aInputData.raw(), cbToRead, &cbRead); if ( cbRead && RT_SUCCESS(vrc)) { /* Resize buffer to reflect amount we just have read. */ if (cbRead > 0) aInputData.resize(cbRead); /* Did we reach the end of the content we want to transfer (last chunk)? */ ULONG uFlags = ProcessInputFlag_None; if ( (cbRead < _64K) /* Did we reach the last block which is exactly _64K? */ || (cbToRead - cbRead == 0) /* ... or does the user want to cancel? */ || ( SUCCEEDED(aTask->pProgress->COMGETTER(Canceled(&fCanceled))) && fCanceled) ) { uFlags |= ProcessInputFlag_EndOfFile; } /* Transfer the current chunk ... */ #ifdef DEBUG_andy LogRel(("Copying Guest Additions (%u bytes left) ...\n", cbLength)); #endif ULONG uBytesWritten; rc = pGuest->SetProcessInput(uPID, uFlags, 10 * 1000 /* Wait 10s for getting the input data transfered. */, ComSafeArrayAsInParam(aInputData), &uBytesWritten); if (FAILED(rc)) { rc = GuestTask::setProgressErrorInfo(rc, aTask->pProgress, pGuest); break; } /* If task was canceled above also cancel the process execution. */ if (fCanceled) progressCat->Cancel(); #ifdef DEBUG_andy LogRel(("Copying Guest Additions (%u bytes written) ...\n", uBytesWritten)); #endif Assert(cbLength >= uBytesWritten); cbLength -= uBytesWritten; } else if (RT_FAILURE(vrc)) { rc = GuestTask::setProgressErrorInfo(VBOX_E_IPRT_ERROR, aTask->pProgress, Guest::tr("Error while reading setup file \"%s\" (To read: %u, Size: %u) from installation medium (%Rrc)"), installerImage.c_str(), cbToRead, cbLength, vrc); } } /* Internal progress canceled? */ if ( SUCCEEDED(progressCat->COMGETTER(Canceled(&fCanceled))) && fCanceled) { aTask->pProgress->Cancel(); break; } } } } } RTIsoFsClose(&iso); if ( SUCCEEDED(rc) && ( SUCCEEDED(aTask->pProgress->COMGETTER(Canceled(&fCanceled))) && !fCanceled ) ) { /* * Installer was transferred successfully, so let's start it * (with system rights). */ LogRel(("Preparing to execute Guest Additions update ...\n")); aTask->pProgress->SetCurrentOperationProgress(66); /* Prepare command line args for installer. */ com::SafeArray<IN_BSTR> installerArgs; com::SafeArray<IN_BSTR> installerEnv; /** @todo Only Windows! */ installerArgs.push_back(Bstr(strInstallerPath).raw()); /* The actual (internal) installer image (as argv[0]). */ /* Note that starting at Windows Vista the lovely session 0 separation applies: * This means that if we run an application with the profile/security context * of VBoxService (system rights!) we're not able to show any UI. */ installerArgs.push_back(Bstr("/S").raw()); /* We want to install in silent mode. */ installerArgs.push_back(Bstr("/l").raw()); /* ... and logging enabled. */ /* Don't quit VBoxService during upgrade because it still is used for this * piece of code we're in right now (that is, here!) ... */ installerArgs.push_back(Bstr("/no_vboxservice_exit").raw()); /* Tell the installer to report its current installation status * using a running VBoxTray instance via balloon messages in the * Windows taskbar. */ installerArgs.push_back(Bstr("/post_installstatus").raw()); /* * Start the just copied over installer with system rights * in silent mode on the guest. Don't use the hidden flag since there * may be pop ups the user has to process. */ ComPtr<IProgress> progressInstaller; ULONG uPID; rc = pGuest->executeProcessInternal(Bstr(strInstallerPath).raw(), ExecuteProcessFlag_WaitForProcessStartOnly, ComSafeArrayAsInParam(installerArgs), ComSafeArrayAsInParam(installerEnv), Bstr("").raw() /* Username */, Bstr("").raw() /* Password */, 10 * 1000 /* Wait 10s for getting the process started */, &uPID, progressInstaller.asOutParam(), &vrc); if (SUCCEEDED(rc)) { LogRel(("Guest Additions update is running ...\n")); /* If the caller does not want to wait for out guest update process to end, * complete the progress object now so that the caller can do other work. */ if (aTask->uFlags & AdditionsUpdateFlag_WaitForUpdateStartOnly) aTask->pProgress->notifyComplete(S_OK); else aTask->pProgress->SetCurrentOperationProgress(70); /* Wait until the Guest Additions installer finishes ... */ while ( SUCCEEDED(progressInstaller->COMGETTER(Completed(&fCompleted))) && !fCompleted) { if ( SUCCEEDED(aTask->pProgress->COMGETTER(Canceled(&fCanceled))) && fCanceled) { progressInstaller->Cancel(); break; } /* Progress canceled by Main API? */ if ( SUCCEEDED(progressInstaller->COMGETTER(Canceled(&fCanceled))) && fCanceled) { break; } RTThreadSleep(100); } ExecuteProcessStatus_T retStatus; ULONG uRetExitCode, uRetFlags; rc = pGuest->GetProcessStatus(uPID, &uRetExitCode, &uRetFlags, &retStatus); if (SUCCEEDED(rc)) { if (fCompleted) { if (uRetExitCode == 0) { LogRel(("Guest Additions update successful!\n")); if ( SUCCEEDED(aTask->pProgress->COMGETTER(Completed(&fCompleted))) && !fCompleted) aTask->pProgress->notifyComplete(S_OK); } else { LogRel(("Guest Additions update failed (Exit code=%u, Status=%u, Flags=%u)\n", uRetExitCode, retStatus, uRetFlags)); rc = GuestTask::setProgressErrorInfo(VBOX_E_IPRT_ERROR, aTask->pProgress, Guest::tr("Guest Additions update failed with exit code=%u (status=%u, flags=%u)"), uRetExitCode, retStatus, uRetFlags); } } else if ( SUCCEEDED(progressInstaller->COMGETTER(Canceled(&fCanceled))) && fCanceled) { LogRel(("Guest Additions update was canceled\n")); rc = GuestTask::setProgressErrorInfo(VBOX_E_IPRT_ERROR, aTask->pProgress, Guest::tr("Guest Additions update was canceled by the guest with exit code=%u (status=%u, flags=%u)"), uRetExitCode, retStatus, uRetFlags); } else { LogRel(("Guest Additions update was canceled by the user\n")); } } else rc = GuestTask::setProgressErrorInfo(rc, aTask->pProgress, pGuest); } else rc = GuestTask::setProgressErrorInfo(rc, aTask->pProgress, pGuest); } } } catch (HRESULT aRC) { rc = aRC; } /* Clean up */ aTask->rc = rc; LogFlowFunc(("rc=%Rhrc\n", rc)); LogFlowFuncLeave(); return VINF_SUCCESS; }
STDMETHODIMP GuestDirectory::Read(IFsObjInfo **aInfo) { #ifndef VBOX_WITH_GUEST_CONTROL ReturnComNotImplemented(); #else LogFlowThisFuncEnter(); AutoCaller autoCaller(this); if (FAILED(autoCaller.rc())) return autoCaller.rc(); ComObjPtr<GuestProcess> pProcess = mData.mProcess; Assert(!pProcess.isNull()); GuestProcessStreamBlock streamBlock; GuestFsObjData objData; int rc = parseData(streamBlock); if ( RT_FAILURE(rc) || streamBlock.IsEmpty()) /* More data needed. */ { rc = pProcess->waitForStart(30 * 1000 /* 30s timeout */); } if (RT_SUCCESS(rc)) { BYTE byBuf[_64K]; size_t cbRead = 0; /** @todo Merge with GuestSession::queryFileInfoInternal. */ for (;RT_SUCCESS(rc);) { GuestProcessWaitResult waitRes; rc = pProcess->waitFor( ProcessWaitForFlag_Terminate | ProcessWaitForFlag_StdOut, 30 * 1000 /* Timeout */, waitRes); if ( RT_FAILURE(rc) || waitRes.mResult == ProcessWaitResult_Terminate || waitRes.mResult == ProcessWaitResult_Error || waitRes.mResult == ProcessWaitResult_Timeout) { if (RT_FAILURE(waitRes.mRC)) rc = waitRes.mRC; break; } rc = pProcess->readData(OUTPUT_HANDLE_ID_STDOUT, sizeof(byBuf), 30 * 1000 /* Timeout */, byBuf, sizeof(byBuf), &cbRead); if (RT_FAILURE(rc)) break; if (cbRead) { AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS); rc = mData.mStream.AddData(byBuf, cbRead); if (RT_FAILURE(rc)) break; LogFlowThisFunc(("rc=%Rrc, cbRead=%RU64, cbStreamOut=%RU32\n", rc, cbRead, mData.mStream.GetSize())); rc = parseData(streamBlock); if (RT_SUCCESS(rc)) { /* Parsing the current stream block succeeded so * we don't need more at the moment. */ break; } } } LogFlowThisFunc(("Reading done with rc=%Rrc, cbRead=%RU64, cbStream=%RU32\n", rc, cbRead, mData.mStream.GetSize())); if (RT_SUCCESS(rc)) { rc = parseData(streamBlock); if (rc == VERR_NO_DATA) /* Since this is the last parsing call, this is ok. */ rc = VINF_SUCCESS; } /* * Note: The guest process can still be around to serve the next * upcoming stream block next time. */ if (RT_SUCCESS(rc)) { /** @todo Move into common function. */ ProcessStatus_T procStatus = ProcessStatus_Undefined; LONG exitCode = 0; HRESULT hr2 = pProcess->COMGETTER(Status(&procStatus)); ComAssertComRC(hr2); hr2 = pProcess->COMGETTER(ExitCode(&exitCode)); ComAssertComRC(hr2); if ( ( procStatus != ProcessStatus_Started && procStatus != ProcessStatus_Paused && procStatus != ProcessStatus_Terminating ) && exitCode != 0) { rc = VERR_ACCESS_DENIED; } } } if (RT_SUCCESS(rc)) { if (streamBlock.GetCount()) /* Did we get content? */ { rc = objData.FromLs(streamBlock); if (RT_FAILURE(rc)) rc = VERR_PATH_NOT_FOUND; if (RT_SUCCESS(rc)) { /* Create the object. */ ComObjPtr<GuestFsObjInfo> pFsObjInfo; HRESULT hr2 = pFsObjInfo.createObject(); if (FAILED(hr2)) rc = VERR_COM_UNEXPECTED; if (RT_SUCCESS(rc)) rc = pFsObjInfo->init(objData); if (RT_SUCCESS(rc)) { /* Return info object to the caller. */ hr2 = pFsObjInfo.queryInterfaceTo(aInfo); if (FAILED(hr2)) rc = VERR_COM_UNEXPECTED; } } } else { /* Nothing to read anymore. Tell the caller. */ rc = VERR_NO_MORE_FILES; } } HRESULT hr = S_OK; if (RT_FAILURE(rc)) /** @todo Add more errors here. */ { switch (rc) { case VERR_ACCESS_DENIED: hr = setError(VBOX_E_IPRT_ERROR, tr("Reading directory \"%s\" failed: Unable to read / access denied"), mData.mName.c_str()); break; case VERR_PATH_NOT_FOUND: hr = setError(VBOX_E_IPRT_ERROR, tr("Reading directory \"%s\" failed: Path not found"), mData.mName.c_str()); break; case VERR_NO_MORE_FILES: hr = setError(VBOX_E_OBJECT_NOT_FOUND, tr("No more entries for directory \"%s\""), mData.mName.c_str()); break; default: hr = setError(VBOX_E_IPRT_ERROR, tr("Error while reading directory \"%s\": %Rrc\n"), mData.mName.c_str(), rc); break; } } LogFlowFuncLeaveRC(rc); return hr; #endif /* VBOX_WITH_GUEST_CONTROL */ }
int SessionTaskUpdateAdditions::runFile(GuestSession *pSession, GuestProcessStartupInfo &procInfo) { AssertPtrReturn(pSession, VERR_INVALID_POINTER); #ifdef VBOX_SERVICE_ENVARG_BUG GuestFsObjData objData; int rc = pSession->fileQueryInfoInternal(procInfo.mCommand, objData); if (RT_FAILURE(rc)) procInfo.mCommand = "C:\\Windows\\system32\\EMP" + procInfo.mCommand.substr(sizeof("%TEMP%\\") - sizeof(char)); #endif ComObjPtr<GuestProcess> pProcess; rc = pSession->processCreateExInteral(procInfo, pProcess); if (RT_SUCCESS(rc)) rc = pProcess->startProcess(); if (RT_SUCCESS(rc)) { LogRel(("Running %s ...\n", procInfo.mName.c_str())); GuestProcessWaitResult waitRes; rc = pProcess->waitFor(ProcessWaitForFlag_Terminate, 10 * 60 * 1000 /* 10 mins Timeout */, waitRes); if (waitRes.mResult == ProcessWaitResult_Terminate) { ProcessStatus_T procStatus; LONG exitCode; if ( ( SUCCEEDED(pProcess->COMGETTER(Status(&procStatus))) && procStatus != ProcessStatus_TerminatedNormally) || ( SUCCEEDED(pProcess->COMGETTER(ExitCode(&exitCode))) && exitCode != 0) ) { setProgressErrorMsg(VBOX_E_IPRT_ERROR, Utf8StrFmt(GuestSession::tr("Running %s failed with status %ld, exit code %ld"), procInfo.mName.c_str(), procStatus, exitCode)); rc = VERR_GENERAL_FAILURE; /* Fudge. */ } else /* Yay, success! */ { LogRel(("%s successfully completed\n", procInfo.mName.c_str())); } } else { if (RT_FAILURE(rc)) setProgressErrorMsg(VBOX_E_IPRT_ERROR, Utf8StrFmt(GuestSession::tr("Error while waiting running %s: %Rrc"), procInfo.mName.c_str(), rc)); else { setProgressErrorMsg(VBOX_E_IPRT_ERROR, pProcess->errorMsg()); rc = VERR_GENERAL_FAILURE; /* Fudge. */ } } } if (!pProcess.isNull()) pProcess->uninit(); return rc; }
int SessionTaskUpdateAdditions::copyFileToGuest(GuestSession *pSession, PRTISOFSFILE pISO, Utf8Str const &strFileSource, const Utf8Str &strFileDest, bool fOptional, uint32_t *pcbSize) { AssertPtrReturn(pSession, VERR_INVALID_POINTER); AssertPtrReturn(pISO, VERR_INVALID_POINTER); /* pcbSize is optional. */ uint32_t cbOffset; size_t cbSize; int rc = RTIsoFsGetFileInfo(pISO, strFileSource.c_str(), &cbOffset, &cbSize); if (RT_FAILURE(rc)) { if (fOptional) return VINF_SUCCESS; return rc; } Assert(cbOffset); Assert(cbSize); rc = RTFileSeek(pISO->file, cbOffset, RTFILE_SEEK_BEGIN, NULL); /* Copy over the Guest Additions file to the guest. */ if (RT_SUCCESS(rc)) { LogRel(("Copying Guest Additions installer file \"%s\" to \"%s\" on guest ...\n", strFileSource.c_str(), strFileDest.c_str())); if (RT_SUCCESS(rc)) { SessionTaskCopyTo *pTask = new SessionTaskCopyTo(pSession /* GuestSession */, &pISO->file, cbOffset, cbSize, strFileDest, CopyFileFlag_None); AssertPtrReturn(pTask, VERR_NO_MEMORY); ComObjPtr<Progress> pProgressCopyTo; rc = pSession->startTaskAsync(Utf8StrFmt(GuestSession::tr("Copying Guest Additions installer file \"%s\" to \"%s\" on guest"), mSource.c_str(), strFileDest.c_str()), pTask, pProgressCopyTo); if (RT_SUCCESS(rc)) { BOOL fCanceled = FALSE; HRESULT hr = pProgressCopyTo->WaitForCompletion(-1); if ( SUCCEEDED(pProgressCopyTo->COMGETTER(Canceled)(&fCanceled)) && fCanceled) { rc = VERR_GENERAL_FAILURE; /* Fudge. */ } else if (FAILED(hr)) { Assert(FAILED(hr)); rc = VERR_GENERAL_FAILURE; /* Fudge. */ } } } } /** @todo Note: Since there is no file locking involved at the moment, there can be modifications * between finished copying, the verification and the actual execution. */ /* Determine where the installer image ended up and if it has the correct size. */ if (RT_SUCCESS(rc)) { LogRel(("Verifying Guest Additions installer file \"%s\" ...\n", strFileDest.c_str())); GuestFsObjData objData; int64_t cbSizeOnGuest; rc = pSession->fileQuerySizeInternal(strFileDest, &cbSizeOnGuest); #ifdef VBOX_SERVICE_ENVARG_BUG if (RT_FAILURE(rc)) { /* Ugly hack: Because older Guest Additions have problems with environment variable expansion in parameters we have to check an alternative location on Windows. So check for "%TEMP%\" being "C:\\Windows\\system32\\EMP" actually. */ if (strFileDest.startsWith("%TEMP%\\", RTCString::CaseSensitive)) { Utf8Str strFileDestBug = "C:\\Windows\\system32\\EMP" + strFileDest.substr(sizeof("%TEMP%\\") - sizeof(char)); rc = pSession->fileQuerySizeInternal(strFileDestBug, &cbSizeOnGuest); } } #endif if ( RT_SUCCESS(rc) && cbSize == (uint64_t)cbSizeOnGuest) { LogRel(("Guest Additions installer file \"%s\" successfully verified\n", strFileDest.c_str())); } else { if (RT_SUCCESS(rc)) /* Size does not match. */ rc = VERR_BROKEN_PIPE; /** @todo FInd a better error. */ } if (RT_SUCCESS(rc)) { if (pcbSize) *pcbSize = cbSizeOnGuest; } } return rc; }
int SessionTaskCopyFrom::Run(void) { LogFlowThisFuncEnter(); ComObjPtr<GuestSession> pSession = mSession; Assert(!pSession.isNull()); AutoCaller autoCaller(pSession); if (FAILED(autoCaller.rc())) return autoCaller.rc(); /* * Note: There will be races between querying file size + reading the guest file's * content because we currently *do not* lock down the guest file when doing the * actual operations. ** @todo Implement guest file locking! */ GuestFsObjData objData; int rc = pSession->fileQueryInfoInternal(Utf8Str(mSource), objData); if (RT_FAILURE(rc)) { setProgressErrorMsg(VBOX_E_IPRT_ERROR, Utf8StrFmt(GuestSession::tr("Querying guest file information for \"%s\" failed: %Rrc"), mSource.c_str(), rc)); } else if (objData.mType != FsObjType_File) /* Only single files are supported at the moment. */ { rc = setProgressErrorMsg(VBOX_E_IPRT_ERROR, Utf8StrFmt(GuestSession::tr("Object \"%s\" on the guest is not a file"), mSource.c_str())); } if (RT_SUCCESS(rc)) { RTFILE fileDest; rc = RTFileOpen(&fileDest, mDest.c_str(), RTFILE_O_WRITE | RTFILE_O_OPEN_CREATE | RTFILE_O_DENY_WRITE); /** @todo Use the correct open modes! */ if (RT_FAILURE(rc)) { setProgressErrorMsg(VBOX_E_IPRT_ERROR, Utf8StrFmt(GuestSession::tr("Error opening destination file \"%s\": %Rrc"), mDest.c_str(), rc)); } else { GuestProcessStartupInfo procInfo; procInfo.mName = Utf8StrFmt(GuestSession::tr("Copying file \"%s\" from guest to the host to \"%s\" (%RI64 bytes)"), mSource.c_str(), mDest.c_str(), objData.mObjectSize); procInfo.mCommand = Utf8Str(VBOXSERVICE_TOOL_CAT); procInfo.mFlags = ProcessCreateFlag_Hidden | ProcessCreateFlag_WaitForStdOut; /* Set arguments.*/ procInfo.mArguments.push_back(mSource); /* Which file to output? */ /* Startup process. */ ComObjPtr<GuestProcess> pProcess; rc = pSession->processCreateExInteral(procInfo, pProcess); if (RT_SUCCESS(rc)) rc = pProcess->startProcess(); if (RT_FAILURE(rc)) { setProgressErrorMsg(VBOX_E_IPRT_ERROR, Utf8StrFmt(GuestSession::tr("Unable to start guest process for copying data from guest to host: %Rrc"), rc)); } else { GuestProcessWaitResult waitRes; BYTE byBuf[_64K]; BOOL fCanceled = FALSE; uint64_t cbWrittenTotal = 0; uint64_t cbToRead = objData.mObjectSize; for (;;) { rc = pProcess->waitFor(ProcessWaitForFlag_StdOut, 30 * 1000 /* Timeout */, waitRes); if ( waitRes.mResult == ProcessWaitResult_StdOut || waitRes.mResult == ProcessWaitResult_WaitFlagNotSupported) { /* If the guest does not support waiting for stdin, we now yield in * order to reduce the CPU load due to busy waiting. */ if (waitRes.mResult == ProcessWaitResult_WaitFlagNotSupported) RTThreadYield(); /* Optional, don't check rc. */ size_t cbRead; rc = pProcess->readData(OUTPUT_HANDLE_ID_STDOUT, sizeof(byBuf), 30 * 1000 /* Timeout */, byBuf, sizeof(byBuf), &cbRead); if (RT_FAILURE(rc)) { setProgressErrorMsg(VBOX_E_IPRT_ERROR, Utf8StrFmt(GuestSession::tr("Reading from file \"%s\" (offset %RU64) failed: %Rrc"), mSource.c_str(), cbWrittenTotal, rc)); break; } if (cbRead) { rc = RTFileWrite(fileDest, byBuf, cbRead, NULL /* No partial writes */); if (RT_FAILURE(rc)) { setProgressErrorMsg(VBOX_E_IPRT_ERROR, Utf8StrFmt(GuestSession::tr("Error writing to file \"%s\" (%RU64 bytes left): %Rrc"), mDest.c_str(), cbToRead, rc)); break; } /* Only subtract bytes reported written by the guest. */ Assert(cbToRead >= cbRead); cbToRead -= cbRead; /* Update total bytes written to the guest. */ cbWrittenTotal += cbRead; Assert(cbWrittenTotal <= (uint64_t)objData.mObjectSize); /* Did the user cancel the operation above? */ if ( SUCCEEDED(mProgress->COMGETTER(Canceled(&fCanceled))) && fCanceled) break; rc = setProgress((ULONG)(cbWrittenTotal / ((uint64_t)objData.mObjectSize / 100.0))); if (RT_FAILURE(rc)) break; } } else if ( RT_FAILURE(rc) || waitRes.mResult == ProcessWaitResult_Terminate || waitRes.mResult == ProcessWaitResult_Error || waitRes.mResult == ProcessWaitResult_Timeout) { if (RT_FAILURE(waitRes.mRC)) rc = waitRes.mRC; break; } } /* for */ LogFlowThisFunc(("rc=%Rrc, cbWrittenTotal=%RU64, cbSize=%RI64, cbToRead=%RU64\n", rc, cbWrittenTotal, objData.mObjectSize, cbToRead)); if ( !fCanceled || RT_SUCCESS(rc)) { /* * Even if we succeeded until here make sure to check whether we really transfered * everything. */ if ( objData.mObjectSize > 0 && cbWrittenTotal == 0) { /* If nothing was transfered but the file size was > 0 then "vbox_cat" wasn't able to write * to the destination -> access denied. */ setProgressErrorMsg(VBOX_E_IPRT_ERROR, Utf8StrFmt(GuestSession::tr("Access denied when copying file \"%s\" to \"%s\""), mSource.c_str(), mDest.c_str())); rc = VERR_GENERAL_FAILURE; /* Fudge. */ } else if (cbWrittenTotal < (uint64_t)objData.mObjectSize) { /* If we did not copy all let the user know. */ setProgressErrorMsg(VBOX_E_IPRT_ERROR, Utf8StrFmt(GuestSession::tr("Copying file \"%s\" failed (%RU64/%RI64 bytes transfered)"), mSource.c_str(), cbWrittenTotal, objData.mObjectSize)); rc = VERR_GENERAL_FAILURE; /* Fudge. */ } else { ProcessStatus_T procStatus; LONG exitCode; if ( ( SUCCEEDED(pProcess->COMGETTER(Status(&procStatus))) && procStatus != ProcessStatus_TerminatedNormally) || ( SUCCEEDED(pProcess->COMGETTER(ExitCode(&exitCode))) && exitCode != 0) ) { setProgressErrorMsg(VBOX_E_IPRT_ERROR, Utf8StrFmt(GuestSession::tr("Copying file \"%s\" failed with status %ld, exit code %d"), mSource.c_str(), procStatus, exitCode)); /**@todo Add stringify methods! */ rc = VERR_GENERAL_FAILURE; /* Fudge. */ } else /* Yay, success! */ rc = setProgressSuccess(); } } if (!pProcess.isNull()) pProcess->uninit(); } RTFileClose(fileDest); } } LogFlowFuncLeaveRC(rc); return rc; }
int SessionTaskCopyTo::Run(void) { LogFlowThisFuncEnter(); ComObjPtr<GuestSession> pSession = mSession; Assert(!pSession.isNull()); AutoCaller autoCaller(pSession); if (FAILED(autoCaller.rc())) return autoCaller.rc(); if (mCopyFileFlags) { setProgressErrorMsg(VBOX_E_IPRT_ERROR, Utf8StrFmt(GuestSession::tr("Copy flags (%#x) not implemented yet"), mCopyFileFlags)); return VERR_INVALID_PARAMETER; } int rc; RTFILE fileLocal; PRTFILE pFile = &fileLocal; if (!mSourceFile) { /* Does our source file exist? */ if (!RTFileExists(mSource.c_str())) { rc = setProgressErrorMsg(VBOX_E_IPRT_ERROR, Utf8StrFmt(GuestSession::tr("Source file \"%s\" does not exist or is not a file"), mSource.c_str())); } else { rc = RTFileOpen(pFile, mSource.c_str(), RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_WRITE); if (RT_FAILURE(rc)) { rc = setProgressErrorMsg(VBOX_E_IPRT_ERROR, Utf8StrFmt(GuestSession::tr("Could not open source file \"%s\" for reading: %Rrc"), mSource.c_str(), rc)); } else { rc = RTFileGetSize(*pFile, &mSourceSize); if (RT_FAILURE(rc)) { setProgressErrorMsg(VBOX_E_IPRT_ERROR, Utf8StrFmt(GuestSession::tr("Could not query file size of \"%s\": %Rrc"), mSource.c_str(), rc)); } } } } else { pFile = mSourceFile; /* Size + offset are optional. */ } GuestProcessStartupInfo procInfo; procInfo.mName = Utf8StrFmt(GuestSession::tr("Copying file \"%s\" to the guest to \"%s\" (%RU64 bytes)"), mSource.c_str(), mDest.c_str(), mSourceSize); procInfo.mCommand = Utf8Str(VBOXSERVICE_TOOL_CAT); procInfo.mFlags = ProcessCreateFlag_Hidden; /* Set arguments.*/ procInfo.mArguments.push_back(Utf8StrFmt("--output=%s", mDest.c_str())); /** @todo Do we need path conversion? */ /* Startup process. */ ComObjPtr<GuestProcess> pProcess; rc = pSession->processCreateExInteral(procInfo, pProcess); if (RT_SUCCESS(rc)) rc = pProcess->startProcess(); if (RT_FAILURE(rc)) { setProgressErrorMsg(VBOX_E_IPRT_ERROR, Utf8StrFmt(GuestSession::tr("Unable to start guest process: %Rrc"), rc)); } else { GuestProcessWaitResult waitRes; BYTE byBuf[_64K]; BOOL fCanceled = FALSE; uint64_t cbWrittenTotal = 0; uint64_t cbToRead = mSourceSize; for (;;) { rc = pProcess->waitFor(ProcessWaitForFlag_StdIn, 30 * 1000 /* Timeout */, waitRes); if ( RT_FAILURE(rc) || ( waitRes.mResult != ProcessWaitResult_StdIn && waitRes.mResult != ProcessWaitResult_WaitFlagNotSupported)) { break; } /* If the guest does not support waiting for stdin, we now yield in * order to reduce the CPU load due to busy waiting. */ if (waitRes.mResult == ProcessWaitResult_WaitFlagNotSupported) RTThreadYield(); /* Optional, don't check rc. */ size_t cbRead = 0; if (mSourceSize) /* If we have nothing to write, take a shortcut. */ { /** @todo Not very efficient, but works for now. */ rc = RTFileSeek(*pFile, mSourceOffset + cbWrittenTotal, RTFILE_SEEK_BEGIN, NULL /* poffActual */); if (RT_SUCCESS(rc)) { rc = RTFileRead(*pFile, (uint8_t*)byBuf, RT_MIN(cbToRead, sizeof(byBuf)), &cbRead); /* * Some other error occured? There might be a chance that RTFileRead * could not resolve/map the native error code to an IPRT code, so just * print a generic error. */ if (RT_FAILURE(rc)) { setProgressErrorMsg(VBOX_E_IPRT_ERROR, Utf8StrFmt(GuestSession::tr("Could not read from file \"%s\" (%Rrc)"), mSource.c_str(), rc)); break; } } else { setProgressErrorMsg(VBOX_E_IPRT_ERROR, Utf8StrFmt(GuestSession::tr("Seeking file \"%s\" offset %RU64 failed: %Rrc"), mSource.c_str(), cbWrittenTotal, rc)); break; } } uint32_t fFlags = ProcessInputFlag_None; /* Did we reach the end of the content we want to transfer (last chunk)? */ if ( (cbRead < sizeof(byBuf)) /* Did we reach the last block which is exactly _64K? */ || (cbToRead - cbRead == 0) /* ... or does the user want to cancel? */ || ( SUCCEEDED(mProgress->COMGETTER(Canceled(&fCanceled))) && fCanceled) ) { fFlags |= ProcessInputFlag_EndOfFile; } uint32_t cbWritten; Assert(sizeof(byBuf) >= cbRead); rc = pProcess->writeData(0 /* StdIn */, fFlags, byBuf, cbRead, 30 * 1000 /* Timeout */, &cbWritten); if (RT_FAILURE(rc)) { setProgressErrorMsg(VBOX_E_IPRT_ERROR, Utf8StrFmt(GuestSession::tr("Writing to file \"%s\" (offset %RU64) failed: %Rrc"), mDest.c_str(), cbWrittenTotal, rc)); break; } LogFlowThisFunc(("cbWritten=%RU32, cbToRead=%RU64, cbWrittenTotal=%RU64, cbFileSize=%RU64\n", cbWritten, cbToRead - cbWritten, cbWrittenTotal + cbWritten, mSourceSize)); /* Only subtract bytes reported written by the guest. */ Assert(cbToRead >= cbWritten); cbToRead -= cbWritten; /* Update total bytes written to the guest. */ cbWrittenTotal += cbWritten; Assert(cbWrittenTotal <= mSourceSize); /* Did the user cancel the operation above? */ if (fCanceled) break; /* Update the progress. * Watch out for division by zero. */ mSourceSize > 0 ? rc = setProgress((ULONG)(cbWrittenTotal * 100 / mSourceSize)) : rc = setProgress(100); if (RT_FAILURE(rc)) break; /* End of file reached? */ if (!cbToRead) break; } /* for */ if ( !fCanceled || RT_SUCCESS(rc)) { /* * Even if we succeeded until here make sure to check whether we really transfered * everything. */ if ( mSourceSize > 0 && cbWrittenTotal == 0) { /* If nothing was transfered but the file size was > 0 then "vbox_cat" wasn't able to write * to the destination -> access denied. */ rc = setProgressErrorMsg(VBOX_E_IPRT_ERROR, Utf8StrFmt(GuestSession::tr("Access denied when copying file \"%s\" to \"%s\""), mSource.c_str(), mDest.c_str())); } else if (cbWrittenTotal < mSourceSize) { /* If we did not copy all let the user know. */ rc = setProgressErrorMsg(VBOX_E_IPRT_ERROR, Utf8StrFmt(GuestSession::tr("Copying file \"%s\" failed (%RU64/%RU64 bytes transfered)"), mSource.c_str(), cbWrittenTotal, mSourceSize)); } else { rc = pProcess->waitFor(ProcessWaitForFlag_Terminate, 30 * 1000 /* Timeout */, waitRes); if ( RT_FAILURE(rc) || waitRes.mResult != ProcessWaitResult_Terminate) { if (RT_FAILURE(rc)) rc = setProgressErrorMsg(VBOX_E_IPRT_ERROR, Utf8StrFmt(GuestSession::tr("Waiting on termination for copying file \"%s\" failed: %Rrc"), mSource.c_str(), rc)); else rc = setProgressErrorMsg(VBOX_E_IPRT_ERROR, Utf8StrFmt(GuestSession::tr("Waiting on termination for copying file \"%s\" failed with wait result %ld"), mSource.c_str(), waitRes.mResult)); } if (RT_SUCCESS(rc)) { ProcessStatus_T procStatus; LONG exitCode; if ( ( SUCCEEDED(pProcess->COMGETTER(Status(&procStatus))) && procStatus != ProcessStatus_TerminatedNormally) || ( SUCCEEDED(pProcess->COMGETTER(ExitCode(&exitCode))) && exitCode != 0) ) { rc = setProgressErrorMsg(VBOX_E_IPRT_ERROR, Utf8StrFmt(GuestSession::tr("Copying file \"%s\" failed with status %ld, exit code %ld"), mSource.c_str(), procStatus, exitCode)); /**@todo Add stringify methods! */ } } if (RT_SUCCESS(rc)) rc = setProgressSuccess(); } } if (!pProcess.isNull()) pProcess->uninit(); } /* processCreateExInteral */ if (!mSourceFile) /* Only close locally opened files. */ RTFileClose(*pFile); LogFlowFuncLeaveRC(rc); return rc; }