VirtualBox

source: vbox/trunk/src/VBox/Main/src-client/GuestFileImpl.cpp@ 98282

Last change on this file since 98282 was 98282, checked in by vboxsync, 22 months ago

Main/Guest Control: Resolved a @todo in GuestFileImpl::i_setFileStatus().

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 61.3 KB
Line 
1/* $Id: GuestFileImpl.cpp 98282 2023-01-24 12:19:42Z vboxsync $ */
2/** @file
3 * VirtualBox Main - Guest file handling.
4 */
5
6/*
7 * Copyright (C) 2012-2023 Oracle and/or its affiliates.
8 *
9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.virtualbox.org.
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation, in version 3 of the
15 * License.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, see <https://www.gnu.org/licenses>.
24 *
25 * SPDX-License-Identifier: GPL-3.0-only
26 */
27
28
29/*********************************************************************************************************************************
30* Header Files *
31*********************************************************************************************************************************/
32#define LOG_GROUP LOG_GROUP_MAIN_GUESTFILE
33#include "LoggingNew.h"
34
35#ifndef VBOX_WITH_GUEST_CONTROL
36# error "VBOX_WITH_GUEST_CONTROL must defined in this file"
37#endif
38#include "GuestFileImpl.h"
39#include "GuestSessionImpl.h"
40#include "GuestCtrlImplPrivate.h"
41#include "ConsoleImpl.h"
42#include "VirtualBoxErrorInfoImpl.h"
43
44#include "Global.h"
45#include "AutoCaller.h"
46#include "VBoxEvents.h"
47
48#include <iprt/cpp/utils.h> /* For unconst(). */
49#include <iprt/file.h>
50
51#include <VBox/com/array.h>
52#include <VBox/com/listeners.h>
53#include <VBox/AssertGuest.h>
54
55
56/**
57 * Internal listener class to serve events in an
58 * active manner, e.g. without polling delays.
59 */
60class GuestFileListener
61{
62public:
63
64 GuestFileListener(void)
65 {
66 }
67
68 virtual ~GuestFileListener()
69 {
70 }
71
72 HRESULT init(GuestFile *pFile)
73 {
74 AssertPtrReturn(pFile, E_POINTER);
75 mFile = pFile;
76 return S_OK;
77 }
78
79 void uninit(void)
80 {
81 mFile = NULL;
82 }
83
84 STDMETHOD(HandleEvent)(VBoxEventType_T aType, IEvent *aEvent)
85 {
86 switch (aType)
87 {
88 case VBoxEventType_OnGuestFileStateChanged:
89 case VBoxEventType_OnGuestFileOffsetChanged:
90 case VBoxEventType_OnGuestFileRead:
91 case VBoxEventType_OnGuestFileWrite:
92 {
93 AssertPtrReturn(mFile, E_POINTER);
94 int vrc2 = mFile->signalWaitEvent(aType, aEvent);
95 RT_NOREF(vrc2);
96#ifdef DEBUG_andy
97 LogFlowFunc(("Signalling events of type=%RU32, file=%p resulted in vrc=%Rrc\n",
98 aType, mFile, vrc2));
99#endif
100 break;
101 }
102
103 default:
104 AssertMsgFailed(("Unhandled event %RU32\n", aType));
105 break;
106 }
107
108 return S_OK;
109 }
110
111private:
112
113 /** Weak pointer to the guest file object to listen for. */
114 GuestFile *mFile;
115};
116typedef ListenerImpl<GuestFileListener, GuestFile*> GuestFileListenerImpl;
117
118VBOX_LISTENER_DECLARE(GuestFileListenerImpl)
119
120// constructor / destructor
121/////////////////////////////////////////////////////////////////////////////
122
123DEFINE_EMPTY_CTOR_DTOR(GuestFile)
124
125HRESULT GuestFile::FinalConstruct(void)
126{
127 LogFlowThisFuncEnter();
128 return BaseFinalConstruct();
129}
130
131void GuestFile::FinalRelease(void)
132{
133 LogFlowThisFuncEnter();
134 uninit();
135 BaseFinalRelease();
136 LogFlowThisFuncLeave();
137}
138
139// public initializer/uninitializer for internal purposes only
140/////////////////////////////////////////////////////////////////////////////
141
142/**
143 * Initializes a file object but does *not* open the file on the guest
144 * yet. This is done in the dedidcated openFile call.
145 *
146 * @return IPRT status code.
147 * @param pConsole Pointer to console object.
148 * @param pSession Pointer to session object.
149 * @param aObjectID The object's ID.
150 * @param openInfo File opening information.
151 */
152int GuestFile::init(Console *pConsole, GuestSession *pSession,
153 ULONG aObjectID, const GuestFileOpenInfo &openInfo)
154{
155 LogFlowThisFunc(("pConsole=%p, pSession=%p, aObjectID=%RU32, strPath=%s\n",
156 pConsole, pSession, aObjectID, openInfo.mFilename.c_str()));
157
158 AssertPtrReturn(pConsole, VERR_INVALID_POINTER);
159 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
160
161 /* Enclose the state transition NotReady->InInit->Ready. */
162 AutoInitSpan autoInitSpan(this);
163 AssertReturn(autoInitSpan.isOk(), VERR_OBJECT_DESTROYED);
164
165 int vrc = bindToSession(pConsole, pSession, aObjectID);
166 if (RT_SUCCESS(vrc))
167 {
168 mSession = pSession;
169
170 mData.mOpenInfo = openInfo;
171 mData.mInitialSize = 0;
172 mData.mStatus = FileStatus_Undefined;
173 mData.mLastError = VINF_SUCCESS;
174 mData.mOffCurrent = 0;
175
176 unconst(mEventSource).createObject();
177 HRESULT hr = mEventSource->init();
178 if (FAILED(hr))
179 vrc = VERR_COM_UNEXPECTED;
180 }
181
182 if (RT_SUCCESS(vrc))
183 {
184 try
185 {
186 GuestFileListener *pListener = new GuestFileListener();
187 ComObjPtr<GuestFileListenerImpl> thisListener;
188 HRESULT hr = thisListener.createObject();
189 if (SUCCEEDED(hr))
190 hr = thisListener->init(pListener, this);
191
192 if (SUCCEEDED(hr))
193 {
194 com::SafeArray <VBoxEventType_T> eventTypes;
195 eventTypes.push_back(VBoxEventType_OnGuestFileStateChanged);
196 eventTypes.push_back(VBoxEventType_OnGuestFileOffsetChanged);
197 eventTypes.push_back(VBoxEventType_OnGuestFileRead);
198 eventTypes.push_back(VBoxEventType_OnGuestFileWrite);
199 hr = mEventSource->RegisterListener(thisListener,
200 ComSafeArrayAsInParam(eventTypes),
201 TRUE /* Active listener */);
202 if (SUCCEEDED(hr))
203 {
204 vrc = baseInit();
205 if (RT_SUCCESS(vrc))
206 {
207 mLocalListener = thisListener;
208 }
209 }
210 else
211 vrc = VERR_COM_UNEXPECTED;
212 }
213 else
214 vrc = VERR_COM_UNEXPECTED;
215 }
216 catch(std::bad_alloc &)
217 {
218 vrc = VERR_NO_MEMORY;
219 }
220 }
221
222 if (RT_SUCCESS(vrc))
223 {
224 /* Confirm a successful initialization when it's the case. */
225 autoInitSpan.setSucceeded();
226 }
227 else
228 autoInitSpan.setFailed();
229
230 LogFlowFuncLeaveRC(vrc);
231 return vrc;
232}
233
234/**
235 * Uninitializes the instance.
236 * Called from FinalRelease().
237 */
238void GuestFile::uninit(void)
239{
240 /* Enclose the state transition Ready->InUninit->NotReady. */
241 AutoUninitSpan autoUninitSpan(this);
242 if (autoUninitSpan.uninitDone())
243 return;
244
245 LogFlowThisFuncEnter();
246
247 baseUninit();
248 LogFlowThisFuncLeave();
249}
250
251// implementation of public getters/setters for attributes
252/////////////////////////////////////////////////////////////////////////////
253
254HRESULT GuestFile::getCreationMode(ULONG *aCreationMode)
255{
256 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
257
258 *aCreationMode = mData.mOpenInfo.mCreationMode;
259
260 return S_OK;
261}
262
263HRESULT GuestFile::getOpenAction(FileOpenAction_T *aOpenAction)
264{
265 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
266
267 *aOpenAction = mData.mOpenInfo.mOpenAction;
268
269 return S_OK;
270}
271
272HRESULT GuestFile::getEventSource(ComPtr<IEventSource> &aEventSource)
273{
274 /* No need to lock - lifetime constant. */
275 mEventSource.queryInterfaceTo(aEventSource.asOutParam());
276
277 return S_OK;
278}
279
280HRESULT GuestFile::getFilename(com::Utf8Str &aFilename)
281{
282 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
283
284 aFilename = mData.mOpenInfo.mFilename;
285
286 return S_OK;
287}
288
289HRESULT GuestFile::getId(ULONG *aId)
290{
291 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
292
293 *aId = mObjectID;
294
295 return S_OK;
296}
297
298HRESULT GuestFile::getInitialSize(LONG64 *aInitialSize)
299{
300 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
301
302 *aInitialSize = mData.mInitialSize;
303
304 return S_OK;
305}
306
307HRESULT GuestFile::getOffset(LONG64 *aOffset)
308{
309 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
310
311 /*
312 * This is updated by GuestFile::i_onFileNotify() when read, write and seek
313 * confirmation messages are recevied.
314 *
315 * Note! This will not be accurate with older (< 5.2.32, 6.0.0 - 6.0.9)
316 * Guest Additions when using writeAt, readAt or writing to a file
317 * opened in append mode.
318 */
319 *aOffset = mData.mOffCurrent;
320
321 return S_OK;
322}
323
324HRESULT GuestFile::getAccessMode(FileAccessMode_T *aAccessMode)
325{
326 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
327
328 *aAccessMode = mData.mOpenInfo.mAccessMode;
329
330 return S_OK;
331}
332
333HRESULT GuestFile::getStatus(FileStatus_T *aStatus)
334{
335 LogFlowThisFuncEnter();
336
337 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
338
339 *aStatus = mData.mStatus;
340
341 return S_OK;
342}
343
344// private methods
345/////////////////////////////////////////////////////////////////////////////
346
347/**
348 * Entry point for guest side file callbacks.
349 *
350 * @returns VBox status code.
351 * @param pCbCtx Host callback context.
352 * @param pSvcCb Host callback data.
353 */
354int GuestFile::i_callbackDispatcher(PVBOXGUESTCTRLHOSTCBCTX pCbCtx, PVBOXGUESTCTRLHOSTCALLBACK pSvcCb)
355{
356 AssertPtrReturn(pCbCtx, VERR_INVALID_POINTER);
357 AssertPtrReturn(pSvcCb, VERR_INVALID_POINTER);
358
359 LogFlowThisFunc(("strName=%s, uContextID=%RU32, uFunction=%RU32, pSvcCb=%p\n",
360 mData.mOpenInfo.mFilename.c_str(), pCbCtx->uContextID, pCbCtx->uMessage, pSvcCb));
361
362 int vrc;
363 switch (pCbCtx->uMessage)
364 {
365 case GUEST_MSG_DISCONNECTED:
366 vrc = i_onGuestDisconnected(pCbCtx, pSvcCb);
367 break;
368
369 case GUEST_MSG_FILE_NOTIFY:
370 vrc = i_onFileNotify(pCbCtx, pSvcCb);
371 break;
372
373 default:
374 /* Silently ignore not implemented functions. */
375 vrc = VERR_NOT_SUPPORTED;
376 break;
377 }
378
379#ifdef DEBUG
380 LogFlowFuncLeaveRC(vrc);
381#endif
382 return vrc;
383}
384
385/**
386 * Closes the file on the guest side and unregisters it.
387 *
388 * @returns VBox status code.
389 * @retval VERR_GSTCTL_GUEST_ERROR when an error from the guest side has been received.
390 * @param prcGuest Where to return the guest error when VERR_GSTCTL_GUEST_ERROR
391 * was returned.
392 */
393int GuestFile::i_closeFile(int *prcGuest)
394{
395 LogFlowThisFunc(("strFile=%s\n", mData.mOpenInfo.mFilename.c_str()));
396
397 int vrc;
398
399 GuestWaitEvent *pEvent = NULL;
400 GuestEventTypes eventTypes;
401 try
402 {
403 eventTypes.push_back(VBoxEventType_OnGuestFileStateChanged);
404
405 vrc = registerWaitEvent(eventTypes, &pEvent);
406 }
407 catch (std::bad_alloc &)
408 {
409 vrc = VERR_NO_MEMORY;
410 }
411
412 if (RT_FAILURE(vrc))
413 return vrc;
414
415 /* Prepare HGCM call. */
416 VBOXHGCMSVCPARM paParms[4];
417 int i = 0;
418 HGCMSvcSetU32(&paParms[i++], pEvent->ContextID());
419 HGCMSvcSetU32(&paParms[i++], mObjectID /* Guest file ID */);
420
421 vrc = sendMessage(HOST_MSG_FILE_CLOSE, i, paParms);
422 if (RT_SUCCESS(vrc))
423 vrc = i_waitForStatusChange(pEvent, 30 * 1000 /* Timeout in ms */,
424 NULL /* FileStatus */, prcGuest);
425 unregisterWaitEvent(pEvent);
426
427 /* Unregister the file object from the guest session. */
428 AssertPtr(mSession);
429 int vrc2 = mSession->i_fileUnregister(this);
430 if (RT_SUCCESS(vrc))
431 vrc = vrc2;
432
433 LogFlowFuncLeaveRC(vrc);
434 return vrc;
435}
436
437/**
438 * Converts a given guest file error to a string.
439 *
440 * @returns Error string.
441 * @param rcGuest Guest file error to return string for.
442 * @param pcszWhat Hint of what was involved when the error occurred.
443 */
444/* static */
445Utf8Str GuestFile::i_guestErrorToString(int rcGuest, const char *pcszWhat)
446{
447 AssertPtrReturn(pcszWhat, "");
448
449 Utf8Str strErr;
450 switch (rcGuest)
451 {
452#define CASE_MSG(a_iRc, ...) \
453 case a_iRc: strErr.printf(__VA_ARGS__); break;
454 CASE_MSG(VERR_ACCESS_DENIED , tr("Access to guest file \"%s\" denied"), pcszWhat);
455 CASE_MSG(VERR_ALREADY_EXISTS , tr("Guest file \"%s\" already exists"), pcszWhat);
456 CASE_MSG(VERR_FILE_NOT_FOUND , tr("Guest file \"%s\" not found"), pcszWhat);
457 CASE_MSG(VERR_NET_HOST_NOT_FOUND, tr("Host name \"%s\", not found"), pcszWhat);
458 CASE_MSG(VERR_SHARING_VIOLATION , tr("Sharing violation for guest file \"%s\""), pcszWhat);
459 default:
460 strErr.printf(tr("Error %Rrc for guest file \"%s\" occurred\n"), rcGuest, pcszWhat);
461 break;
462#undef CASE_MSG
463 }
464
465 return strErr;
466}
467
468/**
469 * Called when the guest side notifies the host of a file event.
470 *
471 * @returns VBox status code.
472 * @param pCbCtx Host callback context.
473 * @param pSvcCbData Host callback data.
474 */
475int GuestFile::i_onFileNotify(PVBOXGUESTCTRLHOSTCBCTX pCbCtx, PVBOXGUESTCTRLHOSTCALLBACK pSvcCbData)
476{
477 AssertPtrReturn(pCbCtx, VERR_INVALID_POINTER);
478 AssertPtrReturn(pSvcCbData, VERR_INVALID_POINTER);
479
480 LogFlowThisFuncEnter();
481
482 if (pSvcCbData->mParms < 3)
483 return VERR_INVALID_PARAMETER;
484
485 int idx = 1; /* Current parameter index. */
486 CALLBACKDATA_FILE_NOTIFY dataCb;
487 RT_ZERO(dataCb);
488 /* pSvcCb->mpaParms[0] always contains the context ID. */
489 HGCMSvcGetU32(&pSvcCbData->mpaParms[idx++], &dataCb.uType);
490 HGCMSvcGetU32(&pSvcCbData->mpaParms[idx++], &dataCb.rc);
491
492 int vrcGuest = (int)dataCb.rc; /* uint32_t vs. int. */
493
494 LogFlowThisFunc(("uType=%RU32, vrcGuest=%Rrc\n", dataCb.uType, vrcGuest));
495
496 if (RT_FAILURE(vrcGuest))
497 {
498 int vrc2 = i_setFileStatus(FileStatus_Error, vrcGuest);
499 AssertRC(vrc2);
500
501 /* Ignore return code, as the event to signal might not be there (anymore). */
502 signalWaitEventInternal(pCbCtx, vrcGuest, NULL /* pPayload */);
503 return VINF_SUCCESS; /* Report to the guest. */
504 }
505
506 AssertMsg(mObjectID == VBOX_GUESTCTRL_CONTEXTID_GET_OBJECT(pCbCtx->uContextID),
507 ("File ID %RU32 does not match object ID %RU32\n", mObjectID,
508 VBOX_GUESTCTRL_CONTEXTID_GET_OBJECT(pCbCtx->uContextID)));
509
510 int vrc = VERR_NOT_SUPPORTED; /* Play safe by default. */
511
512 switch (dataCb.uType)
513 {
514 case GUEST_FILE_NOTIFYTYPE_ERROR:
515 {
516 vrc = i_setFileStatus(FileStatus_Error, vrcGuest);
517 break;
518 }
519
520 case GUEST_FILE_NOTIFYTYPE_OPEN:
521 {
522 if (pSvcCbData->mParms == 4)
523 {
524 vrc = HGCMSvcGetU32(&pSvcCbData->mpaParms[idx++], &dataCb.u.open.uHandle);
525 if (RT_FAILURE(vrc))
526 break;
527
528 /* Set the process status. */
529 vrc = i_setFileStatus(FileStatus_Open, vrcGuest);
530 }
531 break;
532 }
533
534 case GUEST_FILE_NOTIFYTYPE_CLOSE:
535 {
536 vrc = i_setFileStatus(FileStatus_Closed, vrcGuest);
537 break;
538 }
539
540 case GUEST_FILE_NOTIFYTYPE_READ:
541 {
542 ASSERT_GUEST_MSG_STMT_BREAK(pSvcCbData->mParms == 4, ("mParms=%u\n", pSvcCbData->mParms),
543 vrc = VERR_WRONG_PARAMETER_COUNT);
544 ASSERT_GUEST_MSG_STMT_BREAK(pSvcCbData->mpaParms[idx].type == VBOX_HGCM_SVC_PARM_PTR,
545 ("type=%u\n", pSvcCbData->mpaParms[idx].type),
546 vrc = VERR_WRONG_PARAMETER_TYPE);
547
548 vrc = HGCMSvcGetPv(&pSvcCbData->mpaParms[idx++], &dataCb.u.read.pvData, &dataCb.u.read.cbData);
549 if (RT_FAILURE(vrc))
550 break;
551
552 const uint32_t cbRead = dataCb.u.read.cbData;
553 Log3ThisFunc(("cbRead=%RU32\n", cbRead));
554
555 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
556 mData.mOffCurrent += cbRead; /* Bogus for readAt, which is why we've got GUEST_FILE_NOTIFYTYPE_READ_OFFSET. */
557 alock.release();
558
559 try
560 {
561 com::SafeArray<BYTE> data((size_t)cbRead);
562 AssertBreakStmt(data.size() == cbRead, vrc = VERR_NO_MEMORY);
563 data.initFrom((BYTE *)dataCb.u.read.pvData, cbRead);
564 ::FireGuestFileReadEvent(mEventSource, mSession, this, mData.mOffCurrent, cbRead, ComSafeArrayAsInParam(data));
565 }
566 catch (std::bad_alloc &)
567 {
568 vrc = VERR_NO_MEMORY;
569 }
570 break;
571 }
572
573 case GUEST_FILE_NOTIFYTYPE_READ_OFFSET:
574 {
575 ASSERT_GUEST_MSG_STMT_BREAK(pSvcCbData->mParms == 5, ("mParms=%u\n", pSvcCbData->mParms),
576 vrc = VERR_WRONG_PARAMETER_COUNT);
577 ASSERT_GUEST_MSG_STMT_BREAK(pSvcCbData->mpaParms[idx].type == VBOX_HGCM_SVC_PARM_PTR,
578 ("type=%u\n", pSvcCbData->mpaParms[idx].type),
579 vrc = VERR_WRONG_PARAMETER_TYPE);
580 ASSERT_GUEST_MSG_STMT_BREAK(pSvcCbData->mpaParms[idx + 1].type == VBOX_HGCM_SVC_PARM_64BIT,
581 ("type=%u\n", pSvcCbData->mpaParms[idx + 1].type),
582 vrc = VERR_WRONG_PARAMETER_TYPE);
583 BYTE const * const pbData = (BYTE const *)pSvcCbData->mpaParms[idx].u.pointer.addr;
584 uint32_t const cbRead = pSvcCbData->mpaParms[idx].u.pointer.size;
585 int64_t offNew = (int64_t)pSvcCbData->mpaParms[idx + 1].u.uint64;
586 Log3ThisFunc(("cbRead=%RU32 offNew=%RI64 (%#RX64)\n", cbRead, offNew, offNew));
587
588 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
589 if (offNew < 0) /* non-seekable */
590 offNew = mData.mOffCurrent + cbRead;
591 mData.mOffCurrent = offNew;
592 alock.release();
593
594 try
595 {
596 com::SafeArray<BYTE> data((size_t)cbRead);
597 AssertBreakStmt(data.size() == cbRead, vrc = VERR_NO_MEMORY);
598 data.initFrom(pbData, cbRead);
599 ::FireGuestFileReadEvent(mEventSource, mSession, this, offNew, cbRead, ComSafeArrayAsInParam(data));
600 vrc = VINF_SUCCESS;
601 }
602 catch (std::bad_alloc &)
603 {
604 vrc = VERR_NO_MEMORY;
605 }
606 break;
607 }
608
609 case GUEST_FILE_NOTIFYTYPE_WRITE:
610 {
611 ASSERT_GUEST_MSG_STMT_BREAK(pSvcCbData->mParms == 4, ("mParms=%u\n", pSvcCbData->mParms),
612 vrc = VERR_WRONG_PARAMETER_COUNT);
613 ASSERT_GUEST_MSG_STMT_BREAK(pSvcCbData->mpaParms[idx].type == VBOX_HGCM_SVC_PARM_32BIT,
614 ("type=%u\n", pSvcCbData->mpaParms[idx].type),
615 vrc = VERR_WRONG_PARAMETER_TYPE);
616
617 uint32_t const cbWritten = pSvcCbData->mpaParms[idx].u.uint32;
618
619 Log3ThisFunc(("cbWritten=%RU32\n", cbWritten));
620
621 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
622 mData.mOffCurrent += cbWritten; /* Bogus for writeAt and append mode, thus GUEST_FILE_NOTIFYTYPE_WRITE_OFFSET. */
623 alock.release();
624
625 ::FireGuestFileWriteEvent(mEventSource, mSession, this, mData.mOffCurrent, cbWritten);
626 break;
627 }
628
629 case GUEST_FILE_NOTIFYTYPE_WRITE_OFFSET:
630 {
631 ASSERT_GUEST_MSG_STMT_BREAK(pSvcCbData->mParms == 5, ("mParms=%u\n", pSvcCbData->mParms),
632 vrc = VERR_WRONG_PARAMETER_COUNT);
633 ASSERT_GUEST_MSG_STMT_BREAK(pSvcCbData->mpaParms[idx].type == VBOX_HGCM_SVC_PARM_32BIT,
634 ("type=%u\n", pSvcCbData->mpaParms[idx].type),
635 vrc = VERR_WRONG_PARAMETER_TYPE);
636 ASSERT_GUEST_MSG_STMT_BREAK(pSvcCbData->mpaParms[idx + 1].type == VBOX_HGCM_SVC_PARM_64BIT,
637 ("type=%u\n", pSvcCbData->mpaParms[idx].type),
638 vrc = VERR_WRONG_PARAMETER_TYPE);
639 uint32_t const cbWritten = pSvcCbData->mpaParms[idx].u.uint32;
640 int64_t offNew = (int64_t)pSvcCbData->mpaParms[idx + 1].u.uint64;
641 Log3ThisFunc(("cbWritten=%RU32 offNew=%RI64 (%#RX64)\n", cbWritten, offNew, offNew));
642
643 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
644 if (offNew < 0) /* non-seekable */
645 offNew = mData.mOffCurrent + cbWritten;
646 mData.mOffCurrent = offNew;
647 alock.release();
648
649 HRESULT hrc2 = ::FireGuestFileWriteEvent(mEventSource, mSession, this, offNew, cbWritten);
650 vrc = SUCCEEDED(hrc2) ? VINF_SUCCESS : Global::vboxStatusCodeFromCOM(hrc2);
651 break;
652 }
653
654 case GUEST_FILE_NOTIFYTYPE_SEEK:
655 {
656 ASSERT_GUEST_MSG_STMT_BREAK(pSvcCbData->mParms == 4, ("mParms=%u\n", pSvcCbData->mParms),
657 vrc = VERR_WRONG_PARAMETER_COUNT);
658
659 vrc = HGCMSvcGetU64(&pSvcCbData->mpaParms[idx++], &dataCb.u.seek.uOffActual);
660 if (RT_FAILURE(vrc))
661 break;
662
663 Log3ThisFunc(("uOffActual=%RU64\n", dataCb.u.seek.uOffActual));
664
665 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
666 mData.mOffCurrent = dataCb.u.seek.uOffActual;
667 alock.release();
668
669 ::FireGuestFileOffsetChangedEvent(mEventSource, mSession, this, dataCb.u.seek.uOffActual, 0 /* Processed */);
670 break;
671 }
672
673 case GUEST_FILE_NOTIFYTYPE_TELL:
674 /* We don't issue any HOST_MSG_FILE_TELL, so we shouldn't get these notifications! */
675 AssertFailed();
676 break;
677
678 case GUEST_FILE_NOTIFYTYPE_SET_SIZE:
679 ASSERT_GUEST_MSG_STMT_BREAK(pSvcCbData->mParms == 4, ("mParms=%u\n", pSvcCbData->mParms),
680 vrc = VERR_WRONG_PARAMETER_COUNT);
681 ASSERT_GUEST_MSG_STMT_BREAK(pSvcCbData->mpaParms[idx].type == VBOX_HGCM_SVC_PARM_64BIT,
682 ("type=%u\n", pSvcCbData->mpaParms[idx].type),
683 vrc = VERR_WRONG_PARAMETER_TYPE);
684 dataCb.u.SetSize.cbSize = pSvcCbData->mpaParms[idx].u.uint64;
685 Log3ThisFunc(("cbSize=%RU64\n", dataCb.u.SetSize.cbSize));
686
687 ::FireGuestFileSizeChangedEvent(mEventSource, mSession, this, dataCb.u.SetSize.cbSize);
688 vrc = VINF_SUCCESS;
689 break;
690
691 default:
692 break;
693 }
694
695 try
696 {
697 if (RT_SUCCESS(vrc))
698 {
699 GuestWaitEventPayload payload(dataCb.uType, &dataCb, sizeof(dataCb));
700
701 /* Ignore return code, as the event to signal might not be there (anymore). */
702 signalWaitEventInternal(pCbCtx, vrcGuest, &payload);
703 }
704 else /* OOM situation, wrong HGCM parameters or smth. not expected. */
705 {
706 /* Ignore return code, as the event to signal might not be there (anymore). */
707 signalWaitEventInternalEx(pCbCtx, vrc, 0 /* guestRc */, NULL /* pPayload */);
708 }
709 }
710 catch (int vrcEx) /* Thrown by GuestWaitEventPayload constructor. */
711 {
712 /* Also try to signal the waiter, to let it know of the OOM situation.
713 * Ignore return code, as the event to signal might not be there (anymore). */
714 signalWaitEventInternalEx(pCbCtx, vrcEx, 0 /* guestRc */, NULL /* pPayload */);
715 vrc = vrcEx;
716 }
717
718 LogFlowThisFunc(("uType=%RU32, rcGuest=%Rrc, vrc=%Rrc\n", dataCb.uType, vrcGuest, vrc));
719 return vrc;
720}
721
722/**
723 * Called when the guest side of the file has been disconnected (closed, terminated, +++).
724 *
725 * @returns VBox status code.
726 * @param pCbCtx Host callback context.
727 * @param pSvcCbData Host callback data.
728 */
729int GuestFile::i_onGuestDisconnected(PVBOXGUESTCTRLHOSTCBCTX pCbCtx, PVBOXGUESTCTRLHOSTCALLBACK pSvcCbData)
730{
731 AssertPtrReturn(pCbCtx, VERR_INVALID_POINTER);
732 AssertPtrReturn(pSvcCbData, VERR_INVALID_POINTER);
733
734 int vrc = i_setFileStatus(FileStatus_Down, VINF_SUCCESS);
735
736 LogFlowFuncLeaveRC(vrc);
737 return vrc;
738}
739
740/**
741 * @copydoc GuestObject::i_onUnregister
742 */
743int GuestFile::i_onUnregister(void)
744{
745 LogFlowThisFuncEnter();
746
747 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
748
749 int vrc = VINF_SUCCESS;
750
751 /*
752 * Note: The event source stuff holds references to this object,
753 * so make sure that this is cleaned up *before* calling uninit().
754 */
755 if (!mEventSource.isNull())
756 {
757 mEventSource->UnregisterListener(mLocalListener);
758
759 mLocalListener.setNull();
760 unconst(mEventSource).setNull();
761 }
762
763 LogFlowFuncLeaveRC(vrc);
764 return vrc;
765}
766
767/**
768 * @copydoc GuestObject::i_onSessionStatusChange
769 */
770int GuestFile::i_onSessionStatusChange(GuestSessionStatus_T enmSessionStatus)
771{
772 LogFlowThisFuncEnter();
773
774 int vrc = VINF_SUCCESS;
775
776 /* If the session now is in a terminated state, set the file status
777 * to "down", as there is not much else we can do now. */
778 if (GuestSession::i_isTerminated(enmSessionStatus))
779 vrc = i_setFileStatus(FileStatus_Down, 0 /* fileRc, ignored */);
780
781 LogFlowFuncLeaveRC(vrc);
782 return vrc;
783}
784
785/**
786 * Opens the file on the guest.
787 *
788 * @returns VBox status code.
789 * @retval VERR_GSTCTL_GUEST_ERROR when an error from the guest side has been received.
790 * @param uTimeoutMS Timeout (in ms) to wait.
791 * @param prcGuest Where to return the guest error when VERR_GSTCTL_GUEST_ERROR
792 * was returned. Optional.
793 */
794int GuestFile::i_openFile(uint32_t uTimeoutMS, int *prcGuest)
795{
796 AssertReturn(mData.mOpenInfo.mFilename.isNotEmpty(), VERR_INVALID_PARAMETER);
797
798 LogFlowThisFuncEnter();
799
800 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
801
802 LogFlowThisFunc(("strFile=%s, enmAccessMode=%d, enmOpenAction=%d, uCreationMode=%o, mfOpenEx=%#x\n",
803 mData.mOpenInfo.mFilename.c_str(), mData.mOpenInfo.mAccessMode, mData.mOpenInfo.mOpenAction,
804 mData.mOpenInfo.mCreationMode, mData.mOpenInfo.mfOpenEx));
805
806 /* Validate and translate open action. */
807 const char *pszOpenAction = NULL;
808 switch (mData.mOpenInfo.mOpenAction)
809 {
810 case FileOpenAction_OpenExisting: pszOpenAction = "oe"; break;
811 case FileOpenAction_OpenOrCreate: pszOpenAction = "oc"; break;
812 case FileOpenAction_CreateNew: pszOpenAction = "ce"; break;
813 case FileOpenAction_CreateOrReplace: pszOpenAction = "ca"; break;
814 case FileOpenAction_OpenExistingTruncated: pszOpenAction = "ot"; break;
815 case FileOpenAction_AppendOrCreate:
816 pszOpenAction = "oa"; /** @todo get rid of this one and implement AppendOnly/AppendRead. */
817 break;
818 default:
819 return VERR_INVALID_PARAMETER;
820 }
821
822 /* Validate and translate access mode. */
823 const char *pszAccessMode = NULL;
824 switch (mData.mOpenInfo.mAccessMode)
825 {
826 case FileAccessMode_ReadOnly: pszAccessMode = "r"; break;
827 case FileAccessMode_WriteOnly: pszAccessMode = "w"; break;
828 case FileAccessMode_ReadWrite: pszAccessMode = "r+"; break;
829 case FileAccessMode_AppendOnly: pszAccessMode = "a"; break;
830 case FileAccessMode_AppendRead: pszAccessMode = "a+"; break;
831 default: return VERR_INVALID_PARAMETER;
832 }
833
834 /* Validate and translate sharing mode. */
835 const char *pszSharingMode = NULL;
836 switch (mData.mOpenInfo.mSharingMode)
837 {
838 case FileSharingMode_All: pszSharingMode = ""; break;
839 case FileSharingMode_Read: RT_FALL_THRU();
840 case FileSharingMode_Write: RT_FALL_THRU();
841 case FileSharingMode_ReadWrite: RT_FALL_THRU();
842 case FileSharingMode_Delete: RT_FALL_THRU();
843 case FileSharingMode_ReadDelete: RT_FALL_THRU();
844 case FileSharingMode_WriteDelete: return VERR_NOT_IMPLEMENTED;
845 default: return VERR_INVALID_PARAMETER;
846 }
847
848 int vrc;
849
850 GuestWaitEvent *pEvent = NULL;
851 GuestEventTypes eventTypes;
852 try
853 {
854 eventTypes.push_back(VBoxEventType_OnGuestFileStateChanged);
855
856 vrc = registerWaitEvent(eventTypes, &pEvent);
857 }
858 catch (std::bad_alloc &)
859 {
860 vrc = VERR_NO_MEMORY;
861 }
862
863 if (RT_FAILURE(vrc))
864 return vrc;
865
866 /* Prepare HGCM call. */
867 VBOXHGCMSVCPARM paParms[8];
868 int i = 0;
869 HGCMSvcSetU32(&paParms[i++], pEvent->ContextID());
870 HGCMSvcSetPv(&paParms[i++], (void*)mData.mOpenInfo.mFilename.c_str(),
871 (ULONG)mData.mOpenInfo.mFilename.length() + 1);
872 HGCMSvcSetStr(&paParms[i++], pszAccessMode);
873 HGCMSvcSetStr(&paParms[i++], pszOpenAction);
874 HGCMSvcSetStr(&paParms[i++], pszSharingMode);
875 HGCMSvcSetU32(&paParms[i++], mData.mOpenInfo.mCreationMode);
876 HGCMSvcSetU64(&paParms[i++], 0 /*unused offset*/);
877 /** @todo Next protocol version: add flags, replace strings, remove initial offset. */
878
879 alock.release(); /* Drop write lock before sending. */
880
881 vrc = sendMessage(HOST_MSG_FILE_OPEN, i, paParms);
882 if (RT_SUCCESS(vrc))
883 vrc = i_waitForStatusChange(pEvent, uTimeoutMS, NULL /* FileStatus */, prcGuest);
884
885 unregisterWaitEvent(pEvent);
886
887 LogFlowFuncLeaveRC(vrc);
888 return vrc;
889}
890
891/**
892 * Queries file system information from a guest file.
893 *
894 * @returns VBox status code.
895 * @retval VERR_GSTCTL_GUEST_ERROR when an error from the guest side has been received.
896 * @param objData Where to store the file system object data on success.
897 * @param prcGuest Where to return the guest error when VERR_GSTCTL_GUEST_ERROR
898 * was returned. Optional.
899 */
900int GuestFile::i_queryInfo(GuestFsObjData &objData, int *prcGuest)
901{
902 AssertPtr(mSession);
903 return mSession->i_fsQueryInfo(mData.mOpenInfo.mFilename, FALSE /* fFollowSymlinks */, objData, prcGuest);
904}
905
906/**
907 * Reads data from a guest file.
908 *
909 * @returns VBox status code.
910 * @retval VERR_GSTCTL_GUEST_ERROR when an error from the guest side has been received.
911 * @param uSize Size (in bytes) to read.
912 * @param uTimeoutMS Timeout (in ms) to wait.
913 * @param pvData Where to store the read data on success.
914 * @param cbData Size (in bytes) of \a pvData on input.
915 * @param pcbRead Where to return to size (in bytes) read on success.
916 * Optional.
917 */
918int GuestFile::i_readData(uint32_t uSize, uint32_t uTimeoutMS,
919 void* pvData, uint32_t cbData, uint32_t* pcbRead)
920{
921 AssertPtrReturn(pvData, VERR_INVALID_POINTER);
922 AssertReturn(cbData, VERR_INVALID_PARAMETER);
923
924 LogFlowThisFunc(("uSize=%RU32, uTimeoutMS=%RU32, pvData=%p, cbData=%zu\n",
925 uSize, uTimeoutMS, pvData, cbData));
926
927 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
928
929 int vrc;
930
931 GuestWaitEvent *pEvent = NULL;
932 GuestEventTypes eventTypes;
933 try
934 {
935 eventTypes.push_back(VBoxEventType_OnGuestFileStateChanged);
936 eventTypes.push_back(VBoxEventType_OnGuestFileRead);
937
938 vrc = registerWaitEvent(eventTypes, &pEvent);
939 }
940 catch (std::bad_alloc &)
941 {
942 vrc = VERR_NO_MEMORY;
943 }
944
945 if (RT_FAILURE(vrc))
946 return vrc;
947
948 /* Prepare HGCM call. */
949 VBOXHGCMSVCPARM paParms[4];
950 int i = 0;
951 HGCMSvcSetU32(&paParms[i++], pEvent->ContextID());
952 HGCMSvcSetU32(&paParms[i++], mObjectID /* File handle */);
953 HGCMSvcSetU32(&paParms[i++], uSize /* Size (in bytes) to read */);
954
955 alock.release(); /* Drop write lock before sending. */
956
957 vrc = sendMessage(HOST_MSG_FILE_READ, i, paParms);
958 if (RT_SUCCESS(vrc))
959 {
960 uint32_t cbRead = 0;
961 vrc = i_waitForRead(pEvent, uTimeoutMS, pvData, cbData, &cbRead);
962 if (RT_SUCCESS(vrc))
963 {
964 LogFlowThisFunc(("cbRead=%RU32\n", cbRead));
965 if (pcbRead)
966 *pcbRead = cbRead;
967 }
968 else if (pEvent->HasGuestError()) /* Return guest vrc if available. */
969 vrc = pEvent->GetGuestError();
970 }
971
972 unregisterWaitEvent(pEvent);
973
974 LogFlowFuncLeaveRC(vrc);
975 return vrc;
976}
977
978/**
979 * Reads data from a specific position from a guest file.
980 *
981 * @returns VBox status code.
982 * @retval VERR_GSTCTL_GUEST_ERROR when an error from the guest side has been received.
983 * @param uOffset Offset (in bytes) to start reading from.
984 * @param uSize Size (in bytes) to read.
985 * @param uTimeoutMS Timeout (in ms) to wait.
986 * @param pvData Where to store the read data on success.
987 * @param cbData Size (in bytes) of \a pvData on input.
988 * @param pcbRead Where to return to size (in bytes) read on success.
989 * Optional.
990 */
991int GuestFile::i_readDataAt(uint64_t uOffset, uint32_t uSize, uint32_t uTimeoutMS,
992 void* pvData, size_t cbData, size_t* pcbRead)
993{
994 LogFlowThisFunc(("uOffset=%RU64, uSize=%RU32, uTimeoutMS=%RU32, pvData=%p, cbData=%zu\n",
995 uOffset, uSize, uTimeoutMS, pvData, cbData));
996
997 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
998
999 int vrc;
1000
1001 GuestWaitEvent *pEvent = NULL;
1002 GuestEventTypes eventTypes;
1003 try
1004 {
1005 eventTypes.push_back(VBoxEventType_OnGuestFileStateChanged);
1006 eventTypes.push_back(VBoxEventType_OnGuestFileRead);
1007
1008 vrc = registerWaitEvent(eventTypes, &pEvent);
1009 }
1010 catch (std::bad_alloc &)
1011 {
1012 vrc = VERR_NO_MEMORY;
1013 }
1014
1015 if (RT_FAILURE(vrc))
1016 return vrc;
1017
1018 /* Prepare HGCM call. */
1019 VBOXHGCMSVCPARM paParms[4];
1020 int i = 0;
1021 HGCMSvcSetU32(&paParms[i++], pEvent->ContextID());
1022 HGCMSvcSetU32(&paParms[i++], mObjectID /* File handle */);
1023 HGCMSvcSetU64(&paParms[i++], uOffset /* Offset (in bytes) to start reading */);
1024 HGCMSvcSetU32(&paParms[i++], uSize /* Size (in bytes) to read */);
1025
1026 alock.release(); /* Drop write lock before sending. */
1027
1028 vrc = sendMessage(HOST_MSG_FILE_READ_AT, i, paParms);
1029 if (RT_SUCCESS(vrc))
1030 {
1031 uint32_t cbRead = 0;
1032 vrc = i_waitForRead(pEvent, uTimeoutMS, pvData, cbData, &cbRead);
1033 if (RT_SUCCESS(vrc))
1034 {
1035 LogFlowThisFunc(("cbRead=%RU32\n", cbRead));
1036
1037 if (pcbRead)
1038 *pcbRead = cbRead;
1039 }
1040 else if (pEvent->HasGuestError()) /* Return guest vrc if available. */
1041 vrc = pEvent->GetGuestError();
1042 }
1043
1044 unregisterWaitEvent(pEvent);
1045
1046 LogFlowFuncLeaveRC(vrc);
1047 return vrc;
1048}
1049
1050/**
1051 * Seeks a guest file to a specific position.
1052 *
1053 * @returns VBox status code.
1054 * @retval VERR_GSTCTL_GUEST_ERROR when an error from the guest side has been received.
1055 * @param iOffset Offset (in bytes) to seek.
1056 * @param eSeekType Seek type to use.
1057 * @param uTimeoutMS Timeout (in ms) to wait.
1058 * @param puOffset Where to return the new current file position (in bytes) on success.
1059 */
1060int GuestFile::i_seekAt(int64_t iOffset, GUEST_FILE_SEEKTYPE eSeekType,
1061 uint32_t uTimeoutMS, uint64_t *puOffset)
1062{
1063 LogFlowThisFunc(("iOffset=%RI64, uTimeoutMS=%RU32\n",
1064 iOffset, uTimeoutMS));
1065
1066 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1067
1068 int vrc;
1069
1070 GuestWaitEvent *pEvent = NULL;
1071 GuestEventTypes eventTypes;
1072 try
1073 {
1074 eventTypes.push_back(VBoxEventType_OnGuestFileStateChanged);
1075 eventTypes.push_back(VBoxEventType_OnGuestFileOffsetChanged);
1076
1077 vrc = registerWaitEvent(eventTypes, &pEvent);
1078 }
1079 catch (std::bad_alloc &)
1080 {
1081 vrc = VERR_NO_MEMORY;
1082 }
1083
1084 if (RT_FAILURE(vrc))
1085 return vrc;
1086
1087 /* Prepare HGCM call. */
1088 VBOXHGCMSVCPARM paParms[4];
1089 int i = 0;
1090 HGCMSvcSetU32(&paParms[i++], pEvent->ContextID());
1091 HGCMSvcSetU32(&paParms[i++], mObjectID /* File handle */);
1092 HGCMSvcSetU32(&paParms[i++], eSeekType /* Seek method */);
1093 /** @todo uint64_t vs. int64_t! */
1094 HGCMSvcSetU64(&paParms[i++], (uint64_t)iOffset /* Offset (in bytes) to start reading */);
1095
1096 alock.release(); /* Drop write lock before sending. */
1097
1098 vrc = sendMessage(HOST_MSG_FILE_SEEK, i, paParms);
1099 if (RT_SUCCESS(vrc))
1100 {
1101 uint64_t uOffset;
1102 vrc = i_waitForOffsetChange(pEvent, uTimeoutMS, &uOffset);
1103 if (RT_SUCCESS(vrc))
1104 {
1105 LogFlowThisFunc(("uOffset=%RU64\n", uOffset));
1106
1107 if (puOffset)
1108 *puOffset = uOffset;
1109 }
1110 else if (pEvent->HasGuestError()) /* Return guest vrc if available. */
1111 vrc = pEvent->GetGuestError();
1112 }
1113
1114 unregisterWaitEvent(pEvent);
1115
1116 LogFlowFuncLeaveRC(vrc);
1117 return vrc;
1118}
1119
1120/**
1121 * Sets the current internal file object status.
1122 *
1123 * @returns VBox status code.
1124 * @param fileStatus New file status to set.
1125 * @param vrcFile New result code to set.
1126 *
1127 * @note Takes the write lock.
1128 */
1129int GuestFile::i_setFileStatus(FileStatus_T fileStatus, int vrcFile)
1130{
1131 LogFlowThisFuncEnter();
1132
1133 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1134
1135 LogFlowThisFunc(("oldStatus=%RU32, newStatus=%RU32, vrcFile=%Rrc\n", mData.mStatus, fileStatus, vrcFile));
1136
1137#ifdef VBOX_STRICT
1138 if (fileStatus == FileStatus_Error)
1139 AssertMsg(RT_FAILURE(vrcFile), ("Guest vrc must be an error (%Rrc)\n", vrcFile));
1140 else
1141 AssertMsg(RT_SUCCESS(vrcFile), ("Guest vrc must not be an error (%Rrc)\n", vrcFile));
1142#endif
1143
1144 if (mData.mStatus != fileStatus)
1145 {
1146 mData.mStatus = fileStatus;
1147 mData.mLastError = vrcFile;
1148
1149 ComObjPtr<VirtualBoxErrorInfo> errorInfo;
1150 HRESULT hrc = errorInfo.createObject();
1151 ComAssertComRCRet(hrc, VERR_COM_UNEXPECTED);
1152 if (RT_FAILURE(vrcFile))
1153 {
1154 hrc = errorInfo->initEx(VBOX_E_GSTCTL_GUEST_ERROR, vrcFile,
1155 COM_IIDOF(IGuestFile), getComponentName(),
1156 i_guestErrorToString(vrcFile, mData.mOpenInfo.mFilename.c_str()));
1157 ComAssertComRCRet(hrc, VERR_COM_UNEXPECTED);
1158 }
1159 /* Note: On vrcFile success, errorInfo is set to S_OK and also sent via the event below. */
1160
1161 alock.release(); /* Release lock before firing off event. */
1162
1163 ::FireGuestFileStateChangedEvent(mEventSource, mSession, this, fileStatus, errorInfo);
1164 }
1165
1166 return VINF_SUCCESS;
1167}
1168
1169/**
1170 * Waits for a guest file offset change.
1171 *
1172 * @returns VBox status code.
1173 * @retval VERR_GSTCTL_GUEST_ERROR when an error from the guest side has been received.
1174 * @param pEvent Guest wait event to wait for.
1175 * @param uTimeoutMS Timeout (in ms) to wait.
1176 * @param puOffset Where to return the new offset (in bytes) on success.
1177 * Optional and can be NULL.
1178 */
1179int GuestFile::i_waitForOffsetChange(GuestWaitEvent *pEvent,
1180 uint32_t uTimeoutMS, uint64_t *puOffset)
1181{
1182 AssertPtrReturn(pEvent, VERR_INVALID_POINTER);
1183
1184 VBoxEventType_T evtType;
1185 ComPtr<IEvent> pIEvent;
1186 int vrc = waitForEvent(pEvent, uTimeoutMS,
1187 &evtType, pIEvent.asOutParam());
1188 if (RT_SUCCESS(vrc))
1189 {
1190 if (evtType == VBoxEventType_OnGuestFileOffsetChanged)
1191 {
1192 if (puOffset)
1193 {
1194 ComPtr<IGuestFileOffsetChangedEvent> pFileEvent = pIEvent;
1195 Assert(!pFileEvent.isNull());
1196
1197 HRESULT hr = pFileEvent->COMGETTER(Offset)((LONG64*)puOffset);
1198 ComAssertComRC(hr);
1199 }
1200 }
1201 else
1202 vrc = VWRN_GSTCTL_OBJECTSTATE_CHANGED;
1203 }
1204
1205 return vrc;
1206}
1207
1208/**
1209 * Waits for reading from a guest file.
1210 *
1211 * @returns VBox status code.
1212 * @retval VERR_GSTCTL_GUEST_ERROR when an error from the guest side has been received.
1213 * @param pEvent Guest wait event to wait for.
1214 * @param uTimeoutMS Timeout (in ms) to wait.
1215 * @param pvData Where to store read file data on success.
1216 * @param cbData Size (in bytes) of \a pvData.
1217 * @param pcbRead Where to return the actual bytes read on success.
1218 * Optional and can be NULL.
1219 */
1220int GuestFile::i_waitForRead(GuestWaitEvent *pEvent, uint32_t uTimeoutMS,
1221 void *pvData, size_t cbData, uint32_t *pcbRead)
1222{
1223 AssertPtrReturn(pEvent, VERR_INVALID_POINTER);
1224
1225 VBoxEventType_T evtType;
1226 ComPtr<IEvent> pIEvent;
1227 int vrc = waitForEvent(pEvent, uTimeoutMS,
1228 &evtType, pIEvent.asOutParam());
1229 if (RT_SUCCESS(vrc))
1230 {
1231 if (evtType == VBoxEventType_OnGuestFileRead)
1232 {
1233 vrc = VINF_SUCCESS;
1234
1235 ComPtr<IGuestFileReadEvent> pFileEvent = pIEvent;
1236 Assert(!pFileEvent.isNull());
1237
1238 if (pvData)
1239 {
1240 com::SafeArray <BYTE> data;
1241 HRESULT hrc1 = pFileEvent->COMGETTER(Data)(ComSafeArrayAsOutParam(data));
1242 ComAssertComRC(hrc1);
1243 const size_t cbRead = data.size();
1244 if (cbRead)
1245 {
1246 if (cbRead <= cbData)
1247 memcpy(pvData, data.raw(), cbRead);
1248 else
1249 vrc = VERR_BUFFER_OVERFLOW;
1250 }
1251 /* else: used to be VERR_NO_DATA, but that messes stuff up. */
1252
1253 if (pcbRead)
1254 {
1255 *pcbRead = (uint32_t)cbRead;
1256 Assert(*pcbRead == cbRead);
1257 }
1258 }
1259 else if (pcbRead)
1260 {
1261 *pcbRead = 0;
1262 HRESULT hrc2 = pFileEvent->COMGETTER(Processed)((ULONG *)pcbRead);
1263 ComAssertComRC(hrc2); NOREF(hrc2);
1264 }
1265 }
1266 else
1267 vrc = VWRN_GSTCTL_OBJECTSTATE_CHANGED;
1268 }
1269
1270 return vrc;
1271}
1272
1273/**
1274 * Waits for a guest file status change.
1275 *
1276 * @note Similar code in GuestProcess::i_waitForStatusChange() and
1277 * GuestSession::i_waitForStatusChange().
1278 *
1279 * @returns VBox status code.
1280 * @retval VERR_GSTCTL_GUEST_ERROR when an error from the guest side has been received.
1281 * @param pEvent Guest wait event to wait for.
1282 * @param uTimeoutMS Timeout (in ms) to wait.
1283 * @param pFileStatus Where to return the file status on success.
1284 * @param prcGuest Where to return the guest error when VERR_GSTCTL_GUEST_ERROR
1285 * was returned.
1286 */
1287int GuestFile::i_waitForStatusChange(GuestWaitEvent *pEvent, uint32_t uTimeoutMS,
1288 FileStatus_T *pFileStatus, int *prcGuest)
1289{
1290 AssertPtrReturn(pEvent, VERR_INVALID_POINTER);
1291 /* pFileStatus is optional. */
1292
1293 VBoxEventType_T evtType;
1294 ComPtr<IEvent> pIEvent;
1295 int vrc = waitForEvent(pEvent, uTimeoutMS,
1296 &evtType, pIEvent.asOutParam());
1297 if (RT_SUCCESS(vrc))
1298 {
1299 Assert(evtType == VBoxEventType_OnGuestFileStateChanged);
1300 ComPtr<IGuestFileStateChangedEvent> pFileEvent = pIEvent;
1301 Assert(!pFileEvent.isNull());
1302
1303 HRESULT hr;
1304 if (pFileStatus)
1305 {
1306 hr = pFileEvent->COMGETTER(Status)(pFileStatus);
1307 ComAssertComRC(hr);
1308 }
1309
1310 ComPtr<IVirtualBoxErrorInfo> errorInfo;
1311 hr = pFileEvent->COMGETTER(Error)(errorInfo.asOutParam());
1312 ComAssertComRC(hr);
1313
1314 LONG lGuestRc;
1315 hr = errorInfo->COMGETTER(ResultDetail)(&lGuestRc);
1316 ComAssertComRC(hr);
1317
1318 LogFlowThisFunc(("resultDetail=%RI32 (%Rrc)\n",
1319 lGuestRc, lGuestRc));
1320
1321 if (RT_FAILURE((int)lGuestRc))
1322 vrc = VERR_GSTCTL_GUEST_ERROR;
1323
1324 if (prcGuest)
1325 *prcGuest = (int)lGuestRc;
1326 }
1327 /* waitForEvent may also return VERR_GSTCTL_GUEST_ERROR like we do above, so make prcGuest is set. */
1328 /** @todo r=bird: Andy, you seem to have forgotten this scenario. Showed up occasionally when
1329 * using the wrong password with a copyto command in a debug build on windows, error info
1330 * contained "Unknown Status -858993460 (0xcccccccc)". As you know windows fills the stack frames
1331 * with 0xcccccccc in debug builds to highlight use of uninitialized data, so that's what happened
1332 * here. It's actually good you didn't initialize lGuest, as it would be heck to find otherwise.
1333 *
1334 * I'm still not very impressed with the error managment or the usuefullness of the documentation
1335 * in this code, though the latter is getting better! */
1336 else if (vrc == VERR_GSTCTL_GUEST_ERROR && prcGuest)
1337 *prcGuest = pEvent->GuestResult();
1338 Assert(vrc != VERR_GSTCTL_GUEST_ERROR || !prcGuest || *prcGuest != (int)0xcccccccc);
1339
1340 return vrc;
1341}
1342
1343int GuestFile::i_waitForWrite(GuestWaitEvent *pEvent,
1344 uint32_t uTimeoutMS, uint32_t *pcbWritten)
1345{
1346 AssertPtrReturn(pEvent, VERR_INVALID_POINTER);
1347
1348 VBoxEventType_T evtType;
1349 ComPtr<IEvent> pIEvent;
1350 int vrc = waitForEvent(pEvent, uTimeoutMS,
1351 &evtType, pIEvent.asOutParam());
1352 if (RT_SUCCESS(vrc))
1353 {
1354 if (evtType == VBoxEventType_OnGuestFileWrite)
1355 {
1356 if (pcbWritten)
1357 {
1358 ComPtr<IGuestFileWriteEvent> pFileEvent = pIEvent;
1359 Assert(!pFileEvent.isNull());
1360
1361 HRESULT hr = pFileEvent->COMGETTER(Processed)((ULONG*)pcbWritten);
1362 ComAssertComRC(hr);
1363 }
1364 }
1365 else
1366 vrc = VWRN_GSTCTL_OBJECTSTATE_CHANGED;
1367 }
1368
1369 return vrc;
1370}
1371
1372/**
1373 * Writes data to a guest file.
1374 *
1375 * @returns VBox status code.
1376 * @retval VERR_GSTCTL_GUEST_ERROR when an error from the guest side has been received.
1377 * @param uTimeoutMS Timeout (in ms) to wait.
1378 * @param pvData Data to write.
1379 * @param cbData Size (in bytes) of \a pvData to write.
1380 * @param pcbWritten Where to return to size (in bytes) written on success.
1381 * Optional.
1382 */
1383int GuestFile::i_writeData(uint32_t uTimeoutMS, const void *pvData, uint32_t cbData,
1384 uint32_t *pcbWritten)
1385{
1386 AssertPtrReturn(pvData, VERR_INVALID_POINTER);
1387 AssertReturn(cbData, VERR_INVALID_PARAMETER);
1388
1389 LogFlowThisFunc(("uTimeoutMS=%RU32, pvData=%p, cbData=%zu\n",
1390 uTimeoutMS, pvData, cbData));
1391
1392 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1393
1394 int vrc;
1395
1396 GuestWaitEvent *pEvent = NULL;
1397 GuestEventTypes eventTypes;
1398 try
1399 {
1400 eventTypes.push_back(VBoxEventType_OnGuestFileStateChanged);
1401 eventTypes.push_back(VBoxEventType_OnGuestFileWrite);
1402
1403 vrc = registerWaitEvent(eventTypes, &pEvent);
1404 }
1405 catch (std::bad_alloc &)
1406 {
1407 vrc = VERR_NO_MEMORY;
1408 }
1409
1410 if (RT_FAILURE(vrc))
1411 return vrc;
1412
1413 /* Prepare HGCM call. */
1414 VBOXHGCMSVCPARM paParms[8];
1415 int i = 0;
1416 HGCMSvcSetU32(&paParms[i++], pEvent->ContextID());
1417 HGCMSvcSetU32(&paParms[i++], mObjectID /* File handle */);
1418 HGCMSvcSetU32(&paParms[i++], cbData /* Size (in bytes) to write */);
1419 HGCMSvcSetPv (&paParms[i++], unconst(pvData), cbData);
1420
1421 alock.release(); /* Drop write lock before sending. */
1422
1423 vrc = sendMessage(HOST_MSG_FILE_WRITE, i, paParms);
1424 if (RT_SUCCESS(vrc))
1425 {
1426 uint32_t cbWritten = 0;
1427 vrc = i_waitForWrite(pEvent, uTimeoutMS, &cbWritten);
1428 if (RT_SUCCESS(vrc))
1429 {
1430 LogFlowThisFunc(("cbWritten=%RU32\n", cbWritten));
1431 if (pcbWritten)
1432 *pcbWritten = cbWritten;
1433 }
1434 else if (pEvent->HasGuestError()) /* Return guest vrc if available. */
1435 vrc = pEvent->GetGuestError();
1436 }
1437
1438 unregisterWaitEvent(pEvent);
1439
1440 LogFlowFuncLeaveRC(vrc);
1441 return vrc;
1442}
1443
1444
1445/**
1446 * Writes data to a specific position to a guest file.
1447 *
1448 * @returns VBox status code.
1449 * @retval VERR_GSTCTL_GUEST_ERROR when an error from the guest side has been received.
1450 * @param uOffset Offset (in bytes) to start writing at.
1451 * @param uTimeoutMS Timeout (in ms) to wait.
1452 * @param pvData Data to write.
1453 * @param cbData Size (in bytes) of \a pvData to write.
1454 * @param pcbWritten Where to return to size (in bytes) written on success.
1455 * Optional.
1456 */
1457int GuestFile::i_writeDataAt(uint64_t uOffset, uint32_t uTimeoutMS,
1458 const void *pvData, uint32_t cbData, uint32_t *pcbWritten)
1459{
1460 AssertPtrReturn(pvData, VERR_INVALID_POINTER);
1461 AssertReturn(cbData, VERR_INVALID_PARAMETER);
1462
1463 LogFlowThisFunc(("uOffset=%RU64, uTimeoutMS=%RU32, pvData=%p, cbData=%zu\n",
1464 uOffset, uTimeoutMS, pvData, cbData));
1465
1466 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1467
1468 int vrc;
1469
1470 GuestWaitEvent *pEvent = NULL;
1471 GuestEventTypes eventTypes;
1472 try
1473 {
1474 eventTypes.push_back(VBoxEventType_OnGuestFileStateChanged);
1475 eventTypes.push_back(VBoxEventType_OnGuestFileWrite);
1476
1477 vrc = registerWaitEvent(eventTypes, &pEvent);
1478 }
1479 catch (std::bad_alloc &)
1480 {
1481 vrc = VERR_NO_MEMORY;
1482 }
1483
1484 if (RT_FAILURE(vrc))
1485 return vrc;
1486
1487 /* Prepare HGCM call. */
1488 VBOXHGCMSVCPARM paParms[8];
1489 int i = 0;
1490 HGCMSvcSetU32(&paParms[i++], pEvent->ContextID());
1491 HGCMSvcSetU32(&paParms[i++], mObjectID /* File handle */);
1492 HGCMSvcSetU64(&paParms[i++], uOffset /* Offset where to starting writing */);
1493 HGCMSvcSetU32(&paParms[i++], cbData /* Size (in bytes) to write */);
1494 HGCMSvcSetPv (&paParms[i++], unconst(pvData), cbData);
1495
1496 alock.release(); /* Drop write lock before sending. */
1497
1498 vrc = sendMessage(HOST_MSG_FILE_WRITE_AT, i, paParms);
1499 if (RT_SUCCESS(vrc))
1500 {
1501 uint32_t cbWritten = 0;
1502 vrc = i_waitForWrite(pEvent, uTimeoutMS, &cbWritten);
1503 if (RT_SUCCESS(vrc))
1504 {
1505 LogFlowThisFunc(("cbWritten=%RU32\n", cbWritten));
1506 if (pcbWritten)
1507 *pcbWritten = cbWritten;
1508 }
1509 else if (pEvent->HasGuestError()) /* Return guest vrc if available. */
1510 vrc = pEvent->GetGuestError();
1511 }
1512
1513 unregisterWaitEvent(pEvent);
1514
1515 LogFlowFuncLeaveRC(vrc);
1516 return vrc;
1517}
1518
1519// Wrapped IGuestFile methods
1520/////////////////////////////////////////////////////////////////////////////
1521HRESULT GuestFile::close()
1522{
1523 AutoCaller autoCaller(this);
1524 if (FAILED(autoCaller.hrc())) return autoCaller.hrc();
1525
1526 LogFlowThisFuncEnter();
1527
1528 /* Close file on guest. */
1529 int vrcGuest = VERR_IPE_UNINITIALIZED_STATUS;
1530 int vrc = i_closeFile(&vrcGuest);
1531 if (RT_FAILURE(vrc))
1532 {
1533 if (vrc == VERR_GSTCTL_GUEST_ERROR)
1534 {
1535 GuestErrorInfo ge(GuestErrorInfo::Type_File, vrcGuest, mData.mOpenInfo.mFilename.c_str());
1536 return setErrorBoth(VBOX_E_IPRT_ERROR, vrcGuest, tr("Closing guest file failed: %s"),
1537 GuestBase::getErrorAsString(ge).c_str());
1538 }
1539 return setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("Closing guest file \"%s\" failed with %Rrc\n"),
1540 mData.mOpenInfo.mFilename.c_str(), vrc);
1541 }
1542
1543 LogFlowThisFunc(("Returning S_OK / vrc=%Rrc\n", vrc));
1544 return S_OK;
1545}
1546
1547HRESULT GuestFile::queryInfo(ComPtr<IFsObjInfo> &aObjInfo)
1548{
1549 AutoCaller autoCaller(this);
1550 if (FAILED(autoCaller.hrc())) return autoCaller.hrc();
1551
1552 LogFlowThisFuncEnter();
1553
1554 HRESULT hrc = S_OK;
1555
1556 GuestFsObjData fsObjData;
1557 int vrcGuest = VERR_IPE_UNINITIALIZED_STATUS;
1558 int vrc = i_queryInfo(fsObjData, &vrcGuest);
1559 if (RT_SUCCESS(vrc))
1560 {
1561 ComObjPtr<GuestFsObjInfo> ptrFsObjInfo;
1562 hrc = ptrFsObjInfo.createObject();
1563 if (SUCCEEDED(hrc))
1564 {
1565 vrc = ptrFsObjInfo->init(fsObjData);
1566 if (RT_SUCCESS(vrc))
1567 hrc = ptrFsObjInfo.queryInterfaceTo(aObjInfo.asOutParam());
1568 else
1569 hrc = setErrorVrc(vrc,
1570 tr("Initialization of guest file object for \"%s\" failed: %Rrc"),
1571 mData.mOpenInfo.mFilename.c_str(), vrc);
1572 }
1573 }
1574 else
1575 {
1576 if (GuestProcess::i_isGuestError(vrc))
1577 {
1578#ifndef VBOX_WITH_GSTCTL_NO_TOOLBOX
1579 GuestErrorInfo ge(GuestErrorInfo::Type_ToolStat, vrcGuest, mData.mOpenInfo.mFilename.c_str());
1580 hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrcGuest, tr("Querying guest file information failed: %s"),
1581 GuestBase::getErrorAsString(ge).c_str());
1582#endif
1583 }
1584 else
1585 hrc = setErrorVrc(vrc,
1586 tr("Querying guest file information for \"%s\" failed: %Rrc"), mData.mOpenInfo.mFilename.c_str(), vrc);
1587 }
1588
1589 LogFlowFuncLeaveRC(vrc);
1590 return hrc;
1591}
1592
1593HRESULT GuestFile::querySize(LONG64 *aSize)
1594{
1595 AutoCaller autoCaller(this);
1596 if (FAILED(autoCaller.hrc())) return autoCaller.hrc();
1597
1598 LogFlowThisFuncEnter();
1599
1600 HRESULT hrc = S_OK;
1601
1602 GuestFsObjData fsObjData;
1603 int vrcGuest = VERR_IPE_UNINITIALIZED_STATUS;
1604 int vrc = i_queryInfo(fsObjData, &vrcGuest);
1605 if (RT_SUCCESS(vrc))
1606 {
1607 *aSize = fsObjData.mObjectSize;
1608 }
1609 else
1610 {
1611 if (GuestProcess::i_isGuestError(vrc))
1612 {
1613#ifndef VBOX_WITH_GSTCTL_NO_TOOLBOX
1614 GuestErrorInfo ge(GuestErrorInfo::Type_ToolStat, vrcGuest, mData.mOpenInfo.mFilename.c_str());
1615 hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrcGuest, tr("Querying guest file size failed: %s"),
1616 GuestBase::getErrorAsString(ge).c_str());
1617#endif
1618 }
1619 else
1620 hrc = setErrorVrc(vrc, tr("Querying guest file size for \"%s\" failed: %Rrc"), mData.mOpenInfo.mFilename.c_str(), vrc);
1621 }
1622
1623 LogFlowFuncLeaveRC(vrc);
1624 return hrc;
1625}
1626
1627HRESULT GuestFile::read(ULONG aToRead, ULONG aTimeoutMS, std::vector<BYTE> &aData)
1628{
1629 AutoCaller autoCaller(this);
1630 if (FAILED(autoCaller.hrc())) return autoCaller.hrc();
1631
1632 if (aToRead == 0)
1633 return setError(E_INVALIDARG, tr("The size to read is zero"));
1634
1635 LogFlowThisFuncEnter();
1636
1637 /* Cap the read at 1MiB because that's all the guest will return anyway. */
1638 if (aToRead > _1M)
1639 aToRead = _1M;
1640
1641 HRESULT hrc = S_OK;
1642
1643 int vrc;
1644 try
1645 {
1646 aData.resize(aToRead);
1647
1648 uint32_t cbRead;
1649 vrc = i_readData(aToRead, aTimeoutMS,
1650 &aData.front(), aToRead, &cbRead);
1651
1652 if (RT_SUCCESS(vrc))
1653 {
1654 if (aData.size() != cbRead)
1655 aData.resize(cbRead);
1656 }
1657 else
1658 {
1659 aData.resize(0);
1660 }
1661 }
1662 catch (std::bad_alloc &)
1663 {
1664 vrc = VERR_NO_MEMORY;
1665 }
1666
1667 if (RT_FAILURE(vrc))
1668 hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("Reading from file \"%s\" failed: %Rrc"),
1669 mData.mOpenInfo.mFilename.c_str(), vrc);
1670
1671 LogFlowFuncLeaveRC(vrc);
1672 return hrc;
1673}
1674
1675HRESULT GuestFile::readAt(LONG64 aOffset, ULONG aToRead, ULONG aTimeoutMS, std::vector<BYTE> &aData)
1676{
1677 AutoCaller autoCaller(this);
1678 if (FAILED(autoCaller.hrc())) return autoCaller.hrc();
1679
1680 if (aToRead == 0)
1681 return setError(E_INVALIDARG, tr("The size to read for guest file \"%s\" is zero"), mData.mOpenInfo.mFilename.c_str());
1682
1683 LogFlowThisFuncEnter();
1684
1685 /* Cap the read at 1MiB because that's all the guest will return anyway. */
1686 if (aToRead > _1M)
1687 aToRead = _1M;
1688
1689 HRESULT hrc = S_OK;
1690
1691 int vrc;
1692 try
1693 {
1694 aData.resize(aToRead);
1695
1696 size_t cbRead;
1697 vrc = i_readDataAt(aOffset, aToRead, aTimeoutMS,
1698 &aData.front(), aToRead, &cbRead);
1699 if (RT_SUCCESS(vrc))
1700 {
1701 if (aData.size() != cbRead)
1702 aData.resize(cbRead);
1703 }
1704 else
1705 {
1706 aData.resize(0);
1707 }
1708 }
1709 catch (std::bad_alloc &)
1710 {
1711 vrc = VERR_NO_MEMORY;
1712 }
1713
1714 if (RT_FAILURE(vrc))
1715 hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("Reading from file \"%s\" (at offset %RU64) failed: %Rrc"),
1716 mData.mOpenInfo.mFilename.c_str(), aOffset, vrc);
1717
1718 LogFlowFuncLeaveRC(vrc);
1719 return hrc;
1720}
1721
1722HRESULT GuestFile::seek(LONG64 aOffset, FileSeekOrigin_T aWhence, LONG64 *aNewOffset)
1723{
1724 AutoCaller autoCaller(this);
1725 if (FAILED(autoCaller.hrc())) return autoCaller.hrc();
1726
1727 HRESULT hrc = S_OK;
1728
1729 GUEST_FILE_SEEKTYPE eSeekType;
1730 switch (aWhence)
1731 {
1732 case FileSeekOrigin_Begin:
1733 eSeekType = GUEST_FILE_SEEKTYPE_BEGIN;
1734 break;
1735
1736 case FileSeekOrigin_Current:
1737 eSeekType = GUEST_FILE_SEEKTYPE_CURRENT;
1738 break;
1739
1740 case FileSeekOrigin_End:
1741 eSeekType = GUEST_FILE_SEEKTYPE_END;
1742 break;
1743
1744 default:
1745 return setError(E_INVALIDARG, tr("Invalid seek type for guest file \"%s\" specified"),
1746 mData.mOpenInfo.mFilename.c_str());
1747 }
1748
1749 LogFlowThisFuncEnter();
1750
1751 uint64_t uNewOffset;
1752 int vrc = i_seekAt(aOffset, eSeekType,
1753 30 * 1000 /* 30s timeout */, &uNewOffset);
1754 if (RT_SUCCESS(vrc))
1755 *aNewOffset = RT_MIN(uNewOffset, (uint64_t)INT64_MAX);
1756 else
1757 hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("Seeking file \"%s\" (to offset %RI64) failed: %Rrc"),
1758 mData.mOpenInfo.mFilename.c_str(), aOffset, vrc);
1759
1760 LogFlowFuncLeaveRC(vrc);
1761 return hrc;
1762}
1763
1764HRESULT GuestFile::setACL(const com::Utf8Str &aAcl, ULONG aMode)
1765{
1766 RT_NOREF(aAcl, aMode);
1767 ReturnComNotImplemented();
1768}
1769
1770HRESULT GuestFile::setSize(LONG64 aSize)
1771{
1772 LogFlowThisFuncEnter();
1773
1774 /*
1775 * Validate.
1776 */
1777 if (aSize < 0)
1778 return setError(E_INVALIDARG, tr("The size (%RI64) for guest file \"%s\" cannot be a negative value"),
1779 aSize, mData.mOpenInfo.mFilename.c_str());
1780
1781 /*
1782 * Register event callbacks.
1783 */
1784 int vrc;
1785 GuestWaitEvent *pWaitEvent = NULL;
1786 GuestEventTypes lstEventTypes;
1787 try
1788 {
1789 lstEventTypes.push_back(VBoxEventType_OnGuestFileStateChanged);
1790 lstEventTypes.push_back(VBoxEventType_OnGuestFileSizeChanged);
1791 }
1792 catch (std::bad_alloc &)
1793 {
1794 return E_OUTOFMEMORY;
1795 }
1796
1797 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1798
1799 vrc = registerWaitEvent(lstEventTypes, &pWaitEvent);
1800 if (RT_SUCCESS(vrc))
1801 {
1802 /*
1803 * Send of the HGCM message.
1804 */
1805 VBOXHGCMSVCPARM aParms[3];
1806 HGCMSvcSetU32(&aParms[0], pWaitEvent->ContextID());
1807 HGCMSvcSetU32(&aParms[1], mObjectID /* File handle */);
1808 HGCMSvcSetU64(&aParms[2], aSize);
1809
1810 alock.release(); /* Drop write lock before sending. */
1811
1812 vrc = sendMessage(HOST_MSG_FILE_SET_SIZE, RT_ELEMENTS(aParms), aParms);
1813 if (RT_SUCCESS(vrc))
1814 {
1815 /*
1816 * Wait for the event.
1817 */
1818 VBoxEventType_T enmEvtType;
1819 ComPtr<IEvent> pIEvent;
1820 vrc = waitForEvent(pWaitEvent, RT_MS_1MIN / 2, &enmEvtType, pIEvent.asOutParam());
1821 if (RT_SUCCESS(vrc))
1822 {
1823 if (enmEvtType == VBoxEventType_OnGuestFileSizeChanged)
1824 vrc = VINF_SUCCESS;
1825 else
1826 vrc = VWRN_GSTCTL_OBJECTSTATE_CHANGED;
1827 }
1828 if (RT_FAILURE(vrc) && pWaitEvent->HasGuestError()) /* Return guest vrc if available. */
1829 vrc = pWaitEvent->GetGuestError();
1830 }
1831
1832 /*
1833 * Unregister the wait event and deal with error reporting if needed.
1834 */
1835 unregisterWaitEvent(pWaitEvent);
1836 }
1837 HRESULT hrc;
1838 if (RT_SUCCESS(vrc))
1839 hrc = S_OK;
1840 else
1841 hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc,
1842 tr("Setting the guest file size of \"%s\" to %RU64 (%#RX64) bytes failed: %Rrc", "", aSize),
1843 mData.mOpenInfo.mFilename.c_str(), aSize, aSize, vrc);
1844 LogFlowFuncLeaveRC(vrc);
1845 return hrc;
1846}
1847
1848HRESULT GuestFile::write(const std::vector<BYTE> &aData, ULONG aTimeoutMS, ULONG *aWritten)
1849{
1850 AutoCaller autoCaller(this);
1851 if (FAILED(autoCaller.hrc())) return autoCaller.hrc();
1852
1853 if (aData.size() == 0)
1854 return setError(E_INVALIDARG, tr("No data to write specified"), mData.mOpenInfo.mFilename.c_str());
1855
1856 LogFlowThisFuncEnter();
1857
1858 HRESULT hrc = S_OK;
1859
1860 const uint32_t cbData = (uint32_t)aData.size();
1861 const void *pvData = (void *)&aData.front();
1862 int vrc = i_writeData(aTimeoutMS, pvData, cbData, (uint32_t*)aWritten);
1863 if (RT_FAILURE(vrc))
1864 hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("Writing %zu bytes to guest file \"%s\" failed: %Rrc", "", aData.size()),
1865 aData.size(), mData.mOpenInfo.mFilename.c_str(), vrc);
1866
1867 LogFlowFuncLeaveRC(vrc);
1868 return hrc;
1869}
1870
1871HRESULT GuestFile::writeAt(LONG64 aOffset, const std::vector<BYTE> &aData, ULONG aTimeoutMS, ULONG *aWritten)
1872{
1873 AutoCaller autoCaller(this);
1874 if (FAILED(autoCaller.hrc())) return autoCaller.hrc();
1875
1876 if (aData.size() == 0)
1877 return setError(E_INVALIDARG, tr("No data to write at for guest file \"%s\" specified"), mData.mOpenInfo.mFilename.c_str());
1878
1879 LogFlowThisFuncEnter();
1880
1881 HRESULT hrc = S_OK;
1882
1883 const uint32_t cbData = (uint32_t)aData.size();
1884 const void *pvData = (void *)&aData.front();
1885 int vrc = i_writeDataAt(aOffset, aTimeoutMS, pvData, cbData, (uint32_t*)aWritten);
1886 if (RT_FAILURE(vrc))
1887 hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc,
1888 tr("Writing %zu bytes to file \"%s\" (at offset %RU64) failed: %Rrc", "", aData.size()),
1889 aData.size(), mData.mOpenInfo.mFilename.c_str(), aOffset, vrc);
1890
1891 LogFlowFuncLeaveRC(vrc);
1892 return hrc;
1893}
1894
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