VirtualBox

source: vbox/trunk/src/VBox/Main/src-client/GuestDirectoryImpl.cpp@ 99085

Last change on this file since 99085 was 99085, checked in by vboxsync, 20 months ago

Guest Control: Added directory listing support via IDirectory::list(). Added (randomized) testcase support for it. bugref:9783

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 54.4 KB
Line 
1/* $Id: GuestDirectoryImpl.cpp 99085 2023-03-21 12:15:00Z vboxsync $ */
2/** @file
3 * VirtualBox Main - Guest directory 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_GUESTDIRECTORY
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 "GuestImpl.h"
39#include "GuestDirectoryImpl.h"
40#include "GuestSessionImpl.h"
41#include "GuestCtrlImplPrivate.h"
42#include "VirtualBoxErrorInfoImpl.h"
43
44#include "Global.h"
45#include "AutoCaller.h"
46#include "VBoxEvents.h"
47
48#include <VBox/com/array.h>
49#include <VBox/com/listeners.h>
50#include <VBox/AssertGuest.h>
51
52
53/**
54 * Internal listener class to serve events in an
55 * active manner, e.g. without polling delays.
56 */
57class GuestDirectoryListener
58{
59public:
60
61 GuestDirectoryListener(void)
62 {
63 }
64
65 virtual ~GuestDirectoryListener()
66 {
67 }
68
69 HRESULT init(GuestDirectory *pDir)
70 {
71 AssertPtrReturn(pDir, E_POINTER);
72 mDir = pDir;
73 return S_OK;
74 }
75
76 void uninit(void)
77 {
78 mDir = NULL;
79 }
80
81 STDMETHOD(HandleEvent)(VBoxEventType_T aType, IEvent *aEvent)
82 {
83 switch (aType)
84 {
85 case VBoxEventType_OnGuestDirectoryStateChanged:
86 RT_FALL_THROUGH();
87 case VBoxEventType_OnGuestDirectoryRead:
88 {
89 AssertPtrReturn(mDir, E_POINTER);
90 int vrc2 = mDir->signalWaitEvent(aType, aEvent);
91 RT_NOREF(vrc2);
92#ifdef DEBUG_andy
93 LogFlowFunc(("Signalling events of type=%RU32, dir=%p resulted in vrc=%Rrc\n",
94 aType, mDir, vrc2));
95#endif
96 break;
97 }
98
99 default:
100 AssertMsgFailed(("Unhandled event %RU32\n", aType));
101 break;
102 }
103
104 return S_OK;
105 }
106
107private:
108
109 /** Weak pointer to the guest directory object to listen for. */
110 GuestDirectory *mDir;
111};
112typedef ListenerImpl<GuestDirectoryListener, GuestDirectory *> GuestDirectoryListenerImpl;
113
114VBOX_LISTENER_DECLARE(GuestDirectoryListenerImpl)
115
116// constructor / destructor
117/////////////////////////////////////////////////////////////////////////////
118
119DEFINE_EMPTY_CTOR_DTOR(GuestDirectory)
120
121HRESULT GuestDirectory::FinalConstruct(void)
122{
123 LogFlowThisFunc(("\n"));
124 return BaseFinalConstruct();
125}
126
127void GuestDirectory::FinalRelease(void)
128{
129 LogFlowThisFuncEnter();
130 uninit();
131 BaseFinalRelease();
132 LogFlowThisFuncLeave();
133}
134
135// public initializer/uninitializer for internal purposes only
136/////////////////////////////////////////////////////////////////////////////
137
138int GuestDirectory::init(Console *pConsole, GuestSession *pSession, ULONG aObjectID, const GuestDirectoryOpenInfo &openInfo)
139{
140 LogFlowThisFunc(("pConsole=%p, pSession=%p, aObjectID=%RU32, strPath=%s, enmFilter=%#x, fFlags=%x\n",
141 pConsole, pSession, aObjectID, openInfo.mPath.c_str(), openInfo.menmFilter, openInfo.mFlags));
142
143 AssertPtrReturn(pConsole, VERR_INVALID_POINTER);
144 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
145
146 /* Enclose the state transition NotReady->InInit->Ready. */
147 AutoInitSpan autoInitSpan(this);
148 AssertReturn(autoInitSpan.isOk(), VERR_OBJECT_DESTROYED);
149
150 int vrc = bindToSession(pConsole, pSession, aObjectID);
151 if (RT_SUCCESS(vrc))
152 {
153 mSession = pSession;
154 mObjectID = aObjectID;
155
156 mData.mOpenInfo = openInfo;
157 mData.mStatus = DirectoryStatus_Undefined;
158 mData.mLastError = VINF_SUCCESS;
159
160 unconst(mEventSource).createObject();
161 HRESULT hr = mEventSource->init();
162 if (FAILED(hr))
163 vrc = VERR_COM_UNEXPECTED;
164 }
165
166 if (RT_SUCCESS(vrc))
167 {
168 try
169 {
170 GuestDirectoryListener *pListener = new GuestDirectoryListener();
171 ComObjPtr<GuestDirectoryListenerImpl> thisListener;
172 HRESULT hr = thisListener.createObject();
173 if (SUCCEEDED(hr))
174 hr = thisListener->init(pListener, this);
175
176 if (SUCCEEDED(hr))
177 {
178 com::SafeArray <VBoxEventType_T> eventTypes;
179 eventTypes.push_back(VBoxEventType_OnGuestDirectoryStateChanged);
180 eventTypes.push_back(VBoxEventType_OnGuestDirectoryRead);
181 hr = mEventSource->RegisterListener(thisListener,
182 ComSafeArrayAsInParam(eventTypes),
183 TRUE /* Active listener */);
184 if (SUCCEEDED(hr))
185 {
186 vrc = baseInit();
187 if (RT_SUCCESS(vrc))
188 {
189 mLocalListener = thisListener;
190 }
191 }
192 else
193 vrc = VERR_COM_UNEXPECTED;
194 }
195 else
196 vrc = VERR_COM_UNEXPECTED;
197 }
198 catch(std::bad_alloc &)
199 {
200 vrc = VERR_NO_MEMORY;
201 }
202 }
203
204 /* Confirm a successful initialization when it's the case. */
205 if (RT_SUCCESS(vrc))
206 autoInitSpan.setSucceeded();
207 else
208 autoInitSpan.setFailed();
209
210 LogFlowFuncLeaveRC(vrc);
211 return vrc;
212}
213
214/**
215 * Uninitializes the instance.
216 * Called from FinalRelease().
217 */
218void GuestDirectory::uninit(void)
219{
220 LogFlowThisFuncEnter();
221
222 /* Enclose the state transition Ready->InUninit->NotReady. */
223 AutoUninitSpan autoUninitSpan(this);
224 if (autoUninitSpan.uninitDone())
225 return;
226
227 LogFlowThisFuncLeave();
228}
229
230// implementation of private wrapped getters/setters for attributes
231/////////////////////////////////////////////////////////////////////////////
232
233HRESULT GuestDirectory::getDirectoryName(com::Utf8Str &aDirectoryName)
234{
235 LogFlowThisFuncEnter();
236
237 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
238
239 aDirectoryName = mData.mOpenInfo.mPath;
240
241 return S_OK;
242}
243
244HRESULT GuestDirectory::getEventSource(ComPtr<IEventSource> &aEventSource)
245{
246 /* No need to lock - lifetime constant. */
247 mEventSource.queryInterfaceTo(aEventSource.asOutParam());
248
249 return S_OK;
250}
251
252HRESULT GuestDirectory::getFilter(com::Utf8Str &aFilter)
253{
254 LogFlowThisFuncEnter();
255
256 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
257
258 aFilter = mData.mOpenInfo.mFilter;
259
260 return S_OK;
261}
262
263HRESULT GuestDirectory::getId(ULONG *aId)
264{
265 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
266
267 *aId = mObjectID;
268
269 return S_OK;
270}
271
272HRESULT GuestDirectory::getStatus(DirectoryStatus_T *aStatus)
273{
274 LogFlowThisFuncEnter();
275
276 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
277
278 *aStatus = mData.mStatus;
279
280 return S_OK;
281}
282
283// private methods
284/////////////////////////////////////////////////////////////////////////////
285
286/**
287 * Entry point for guest side directory callbacks.
288 *
289 * @returns VBox status code.
290 * @param pCbCtx Host callback context.
291 * @param pSvcCb Host callback data.
292 */
293int GuestDirectory::i_callbackDispatcher(PVBOXGUESTCTRLHOSTCBCTX pCbCtx, PVBOXGUESTCTRLHOSTCALLBACK pSvcCb)
294{
295 AssertPtrReturn(pCbCtx, VERR_INVALID_POINTER);
296 AssertPtrReturn(pSvcCb, VERR_INVALID_POINTER);
297
298 LogFlowThisFunc(("strPath=%s, uContextID=%RU32, uMessage=%RU32, pSvcCb=%p\n",
299 mData.mOpenInfo.mPath.c_str(), pCbCtx->uContextID, pCbCtx->uMessage, pSvcCb));
300
301 int vrc;
302 switch (pCbCtx->uMessage)
303 {
304 case GUEST_MSG_DISCONNECTED:
305 /** @todo vrc = i_onGuestDisconnected(pCbCtx, pSvcCb); */
306 vrc = VINF_SUCCESS; /// @todo To be implemented
307 break;
308
309 case GUEST_MSG_DIR_NOTIFY:
310 {
311 vrc = i_onDirNotify(pCbCtx, pSvcCb);
312 break;
313 }
314
315 default:
316 /* Silently ignore not implemented functions. */
317 vrc = VERR_NOT_SUPPORTED;
318 break;
319 }
320
321 LogFlowFuncLeaveRC(vrc);
322 return vrc;
323}
324
325/**
326 * Opens the directory on the guest side.
327 *
328 * @return VBox status code.
329 * @param pvrcGuest Where to store the guest result code in case VERR_GSTCTL_GUEST_ERROR is returned.
330 */
331int GuestDirectory::i_open(int *pvrcGuest)
332{
333 int vrc;
334#ifdef VBOX_WITH_GSTCTL_TOOLBOX_AS_CMDS
335 if ((mSession->i_getParent()->i_getGuestControlFeatures0() & VBOX_GUESTCTRL_GF_0_TOOLBOX_AS_CMDS))
336 {
337 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
338
339 GuestWaitEvent *pEvent = NULL;
340 GuestEventTypes eventTypes;
341 try
342 {
343 eventTypes.push_back(VBoxEventType_OnGuestDirectoryStateChanged);
344
345 vrc = registerWaitEvent(eventTypes, &pEvent);
346 }
347 catch (std::bad_alloc &)
348 {
349 vrc = VERR_NO_MEMORY;
350 }
351
352 if (RT_FAILURE(vrc))
353 return vrc;
354
355 /* Prepare HGCM call. */
356 VBOXHGCMSVCPARM paParms[8];
357 int i = 0;
358 HGCMSvcSetU32(&paParms[i++], pEvent->ContextID());
359 HGCMSvcSetStr(&paParms[i++], mData.mOpenInfo.mPath.c_str());
360 HGCMSvcSetU32(&paParms[i++], mData.mOpenInfo.menmFilter);
361 HGCMSvcSetU32(&paParms[i++], mData.mOpenInfo.mFlags);
362 HGCMSvcSetU32(&paParms[i++], GSTCTLFSOBJATTRADD_UNIX /* Implicit */);
363 HGCMSvcSetU32(&paParms[i++], GSTCTL_PATH_F_ON_LINK /* Ditto */ );
364
365 alock.release(); /* Drop lock before sending. */
366
367 vrc = sendMessage(HOST_MSG_DIR_OPEN, i, paParms);
368 if (RT_SUCCESS(vrc))
369 vrc = i_waitForStatusChange(pEvent, 30 * 1000, NULL /* FileStatus */, pvrcGuest);
370 }
371 else
372#endif /* VBOX_WITH_GSTCTL_TOOLBOX_AS_CMDS */
373 {
374 vrc = i_openViaToolbox(pvrcGuest);
375 }
376
377 return vrc;
378}
379
380#ifdef VBOX_WITH_GSTCTL_TOOLBOX_SUPPORT
381/**
382 * Opens the directory on the guest side (legacy version).
383 *
384 * @returns VBox status code.
385 * @param pvrcGuest Where to store the guest result code in case VERR_GSTCTL_GUEST_ERROR is returned.
386 *
387 * @note This uses an own guest process via the built-in toolbox in VBoxSerivce.
388 */
389int GuestDirectory::i_openViaToolbox(int *pvrcGuest)
390{
391 /* Start the directory process on the guest. */
392 GuestProcessStartupInfo procInfo;
393 procInfo.mName.printf(tr("Opening directory \"%s\""), mData.mOpenInfo.mPath.c_str());
394 procInfo.mTimeoutMS = 5 * 60 * 1000; /* 5 minutes timeout. */
395 procInfo.mFlags = ProcessCreateFlag_WaitForStdOut;
396 procInfo.mExecutable= Utf8Str(VBOXSERVICE_TOOL_LS);
397
398 procInfo.mArguments.push_back(procInfo.mExecutable);
399 procInfo.mArguments.push_back(Utf8Str("--machinereadable"));
400 /* We want the long output format which contains all the object details. */
401 procInfo.mArguments.push_back(Utf8Str("-l"));
402 /* Always dereference symlinks by default when opening directories, as we want to show its
403 * contents rather than working directly on the link.
404 *
405 * Newer Linux distros such as Ubuntu 22.10 symlink /bin to /usr/bin, for example. */
406 if (!(mData.mOpenInfo.mFlags & DirectoryOpenFlag_NoSymlinks)) /* Check if the caller explicitly forbids this. */
407 procInfo.mArguments.push_back(Utf8Str("--dereference"));
408 /** @todo Recursion support? */
409 procInfo.mArguments.push_back(mData.mOpenInfo.mPath); /* The directory we want to open. */
410
411 /*
412 * Start the process synchronously and keep it around so that we can use
413 * it later in subsequent read() calls.
414 */
415 int vrc = mData.mProcessTool.init(mSession, procInfo, false /*fAsync*/, NULL /*pvrcGuest*/);
416 if (RT_SUCCESS(vrc))
417 {
418 /* As we need to know if the directory we were about to open exists and and is accessible,
419 * do the first read here in order to return a meaningful status here. */
420 int vrcGuest = VERR_IPE_UNINITIALIZED_STATUS;
421 vrc = i_readInternal(mData.mObjData, &vrcGuest);
422 if (RT_FAILURE(vrc))
423 {
424 /*
425 * We need to actively terminate our process tool in case of an error here,
426 * as this otherwise would be done on (directory) object destruction implicitly.
427 * This in turn then will run into a timeout, as the directory object won't be
428 * around anymore at that time. Ugly, but that's how it is for the moment.
429 */
430 /* ignore rc */ mData.mProcessTool.terminate(30 * RT_MS_1SEC, NULL /* pvrcGuest */);
431 }
432
433 if (pvrcGuest)
434 *pvrcGuest = vrcGuest;
435 }
436
437 return vrc;
438}
439#endif /* VBOX_WITH_GSTCTL_TOOLBOX_SUPPORT */
440
441/**
442 * Called when the guest side notifies the host of a directory event.
443 *
444 * @returns VBox status code.
445 * @param pCbCtx Host callback context.
446 * @param pSvcCbData Host callback data.
447 */
448int GuestDirectory::i_onDirNotify(PVBOXGUESTCTRLHOSTCBCTX pCbCtx, PVBOXGUESTCTRLHOSTCALLBACK pSvcCbData)
449{
450#ifndef VBOX_WITH_GSTCTL_TOOLBOX_AS_CMDS
451 RT_NOREF(pCbCtx, pSvcCbData);
452 return VERR_NOT_SUPPORTED;
453#else
454 AssertPtrReturn(pCbCtx, VERR_INVALID_POINTER);
455 AssertPtrReturn(pSvcCbData, VERR_INVALID_POINTER);
456
457 LogFlowThisFuncEnter();
458
459 if (pSvcCbData->mParms < 3)
460 return VERR_INVALID_PARAMETER;
461
462 int idx = 1; /* Current parameter index. */
463 CALLBACKDATA_DIR_NOTIFY dataCb;
464 RT_ZERO(dataCb);
465 /* pSvcCb->mpaParms[0] always contains the context ID. */
466 HGCMSvcGetU32(&pSvcCbData->mpaParms[idx++], &dataCb.uType);
467 HGCMSvcGetU32(&pSvcCbData->mpaParms[idx++], &dataCb.rc);
468
469 int const vrcGuest = (int)dataCb.rc; /* uint32_t vs. int. */
470
471 LogFlowThisFunc(("uType=%RU32, vrcGuest=%Rrc\n", dataCb.uType, vrcGuest));
472
473 if (RT_FAILURE(vrcGuest))
474 {
475 /** @todo Set status? */
476
477 /* Ignore return code, as the event to signal might not be there (anymore). */
478 signalWaitEventInternal(pCbCtx, vrcGuest, NULL /* pPayload */);
479 return VINF_SUCCESS; /* Report to the guest. */
480 }
481
482 int vrc = VERR_NOT_SUPPORTED; /* Play safe by default. */
483
484 ComObjPtr<VirtualBoxErrorInfo> errorInfo;
485 HRESULT hrc = errorInfo.createObject();
486 ComAssertComRCRet(hrc, VERR_COM_UNEXPECTED);
487 if (RT_FAILURE(vrcGuest))
488 {
489 hrc = errorInfo->initEx(VBOX_E_GSTCTL_GUEST_ERROR, vrcGuest,
490 COM_IIDOF(IGuestDirectory), getComponentName(),
491 i_guestErrorToString(vrcGuest, mData.mOpenInfo.mPath.c_str()));
492 ComAssertComRCRet(hrc, VERR_COM_UNEXPECTED);
493 }
494
495 switch (dataCb.uType)
496 {
497 case GUEST_DIR_NOTIFYTYPE_ERROR:
498 {
499 vrc = i_setStatus(DirectoryStatus_Error, vrcGuest);
500 break;
501 }
502
503 case GUEST_DIR_NOTIFYTYPE_OPEN:
504 {
505 AssertBreakStmt(pSvcCbData->mParms >= 4, vrc = VERR_INVALID_PARAMETER);
506 vrc = HGCMSvcGetU32(&pSvcCbData->mpaParms[idx++], &dataCb.u.open.uHandle /* Guest native file handle */);
507 AssertRCBreak(vrc);
508 vrc = i_setStatus(DirectoryStatus_Open, vrcGuest);
509 break;
510 }
511
512 case GUEST_DIR_NOTIFYTYPE_CLOSE:
513 {
514 vrc = i_setStatus(DirectoryStatus_Close, vrcGuest);
515 break;
516 }
517
518 case GUEST_DIR_NOTIFYTYPE_READ:
519 {
520 ASSERT_GUEST_MSG_STMT_BREAK(pSvcCbData->mParms == 6, ("mParms=%u\n", pSvcCbData->mParms),
521 vrc = VERR_WRONG_PARAMETER_COUNT);
522 ASSERT_GUEST_MSG_STMT_BREAK(pSvcCbData->mpaParms[idx].type == VBOX_HGCM_SVC_PARM_PTR,
523 ("type=%u\n", pSvcCbData->mpaParms[idx].type),
524 vrc = VERR_WRONG_PARAMETER_TYPE);
525 PGSTCTLDIRENTRYEX pDirEntryEx;
526 uint32_t cbDirEntryEx;
527 vrc = HGCMSvcGetPv(&pSvcCbData->mpaParms[idx++], (void **)&pDirEntryEx, &cbDirEntryEx);
528 AssertRCBreak(vrc);
529 AssertBreakStmt( cbDirEntryEx >= RT_UOFFSETOF(GSTCTLDIRENTRYEX, szName[2])
530 && cbDirEntryEx <= GSTCTL_DIRENTRY_MAX_SIZE, vrc = VERR_INVALID_PARAMETER);
531 dataCb.u.read.Entry.pDirEntryEx = (PGSTCTLDIRENTRYEX)RTMemDup(pDirEntryEx, cbDirEntryEx);
532 AssertPtrBreakStmt(dataCb.u.read.Entry.pDirEntryEx, vrc = VERR_NO_MEMORY);
533 dataCb.u.read.Entry.cbDirEntryEx = cbDirEntryEx;
534
535 char *pszUser;
536 uint32_t cbUser;
537 vrc = HGCMSvcGetStr(&pSvcCbData->mpaParms[idx++], &pszUser, &cbUser);
538 AssertRCBreak(vrc);
539 AssertBreakStmt(cbUser <= GSTCTL_DIRENTRY_MAX_USER_NAME, vrc = VERR_TOO_MUCH_DATA);
540 dataCb.u.read.Entry.pszUser = RTStrDup(pszUser);
541 AssertPtrBreakStmt(dataCb.u.read.Entry.pszUser, vrc = VERR_NO_MEMORY);
542 dataCb.u.read.Entry.cbUser = cbUser;
543
544 char *pszGroups;
545 uint32_t cbGroups;
546 vrc = HGCMSvcGetStr(&pSvcCbData->mpaParms[idx++], &pszGroups, &cbGroups);
547 AssertRCBreak(vrc);
548 AssertBreakStmt(cbGroups <= GSTCTL_DIRENTRY_MAX_USER_GROUPS, vrc = VERR_TOO_MUCH_DATA);
549 dataCb.u.read.Entry.pszGroups = RTStrDup(pszGroups);
550 AssertPtrBreakStmt(dataCb.u.read.Entry.pszGroups, vrc = VERR_NO_MEMORY);
551 dataCb.u.read.Entry.cbGroups = cbGroups;
552
553 /** @todo ACLs not implemented yet. */
554
555 GuestFsObjData fsObjData(dataCb.u.read.Entry.pDirEntryEx->szName);
556 vrc = fsObjData.FromGuestFsObjInfo(&dataCb.u.read.Entry.pDirEntryEx->Info);
557 AssertRCBreak(vrc);
558 ComObjPtr<GuestFsObjInfo> ptrFsObjInfo;
559 hrc = ptrFsObjInfo.createObject();
560 ComAssertComRCBreak(hrc, vrc = VERR_COM_UNEXPECTED);
561 vrc = ptrFsObjInfo->init(fsObjData);
562 AssertRCBreak(vrc);
563
564 ::FireGuestDirectoryReadEvent(mEventSource, mSession, this,
565 dataCb.u.read.Entry.pDirEntryEx->szName, ptrFsObjInfo,
566 dataCb.u.read.Entry.pszUser, dataCb.u.read.Entry.pszGroups);
567 break;
568 }
569
570 case GUEST_DIR_NOTIFYTYPE_REWIND:
571 {
572 /* Note: This does not change the overall status of the directory (i.e. open). */
573 ::FireGuestDirectoryStateChangedEvent(mEventSource, mSession, this, DirectoryStatus_Rewind, errorInfo);
574 break;
575 }
576
577 case GUEST_DIR_NOTIFYTYPE_LIST:
578 {
579 ASSERT_GUEST_MSG_STMT_BREAK(pSvcCbData->mParms >= 4, ("mParms=%u\n", pSvcCbData->mParms),
580 vrc = VERR_WRONG_PARAMETER_COUNT);
581 ASSERT_GUEST_MSG_STMT_BREAK(pSvcCbData->mpaParms[idx].type == VBOX_HGCM_SVC_PARM_32BIT,
582 ("type=%u\n", pSvcCbData->mpaParms[idx].type),
583 vrc = VERR_WRONG_PARAMETER_TYPE);
584
585 vrc = HGCMSvcGetU32(&pSvcCbData->mpaParms[idx++], &dataCb.u.list.cEntries);
586 AssertRCBreak(vrc);
587 /* We limit this for now to 64K entries max per call.
588 * The guest does not do this check, so we could de/increase this limit in the future. */
589 AssertBreakStmt(dataCb.u.list.cEntries <= _64K, vrc = VERR_TOO_MUCH_DATA);
590
591 if (!dataCb.u.list.cEntries) /* No entries sent? Bail out early. */
592 break;
593
594 /*
595 * Fetch buffer with packed directory entries.
596 */
597 ASSERT_GUEST_MSG_STMT_BREAK(pSvcCbData->mParms == 5, ("mParms=%u\n", pSvcCbData->mParms),
598 vrc = VERR_WRONG_PARAMETER_COUNT);
599 ASSERT_GUEST_MSG_STMT_BREAK(pSvcCbData->mpaParms[idx].type == VBOX_HGCM_SVC_PARM_PTR,
600 ("type=%u\n", pSvcCbData->mpaParms[idx].type),
601 vrc = VERR_WRONG_PARAMETER_TYPE);
602 void *pvBuf;
603 uint32_t cbBuf;
604 vrc = HGCMSvcGetPv(&pSvcCbData->mpaParms[idx], &pvBuf, &cbBuf);
605 AssertRCBreak(vrc);
606 AssertBreakStmt(cbBuf >= sizeof(GSTCTLDIRENTRYEX), vrc = VERR_INVALID_PARAMETER);
607 dataCb.u.list.paEntries = (PCALLBACKDATA_DIR_ENTRY *)RTMemAllocZ(dataCb.u.list.cEntries * sizeof(PCALLBACKDATA_DIR_ENTRY));
608 AssertPtrBreakStmt(dataCb.u.list.paEntries, vrc = VERR_NO_MEMORY);
609
610 /*
611 * Unpack directory entries.
612 */
613 size_t offBuf = 0;
614 for (uint32_t i = 0; i < dataCb.u.list.cEntries; i++)
615 {
616 dataCb.u.list.paEntries[i] = (PCALLBACKDATA_DIR_ENTRY)RTMemAlloc(sizeof(CALLBACKDATA_DIR_ENTRY));
617 AssertPtrBreakStmt(dataCb.u.list.paEntries[i], vrc = VERR_NO_MEMORY);
618
619 PCALLBACKDATA_DIR_ENTRY pEntry = dataCb.u.list.paEntries[i];
620
621 PGSTCTLDIRENTRYLISTHDR const pHdr = (PGSTCTLDIRENTRYLISTHDR)((uint8_t *)pvBuf + offBuf);
622 AssertBreakStmt(pHdr->cbDirEntryEx <= GSTCTL_DIRENTRY_MAX_SIZE, vrc = VERR_TOO_MUCH_DATA);
623 AssertBreakStmt(pHdr->cbUser <= GSTCTL_DIRENTRY_MAX_USER_NAME, vrc = VERR_TOO_MUCH_DATA);
624 AssertBreakStmt(pHdr->cbGroups <= GSTCTL_DIRENTRY_MAX_USER_GROUPS, vrc = VERR_TOO_MUCH_DATA);
625 offBuf += sizeof(GSTCTLDIRENTRYLISTHDR);
626
627 AssertBreakStmt( pHdr->cbDirEntryEx >= RT_UOFFSETOF(GSTCTLDIRENTRYEX, szName[2])
628 && pHdr->cbDirEntryEx <= GSTCTL_DIRENTRY_MAX_SIZE, vrc = VERR_INVALID_PARAMETER);
629 pEntry->pDirEntryEx = (PGSTCTLDIRENTRYEX)RTMemDup((uint8_t *)pvBuf + offBuf, pHdr->cbDirEntryEx);
630 AssertPtrBreakStmt(pEntry->pDirEntryEx, vrc = VERR_NO_MEMORY);
631 pEntry->cbDirEntryEx = pHdr->cbDirEntryEx;
632 offBuf += pHdr->cbDirEntryEx;
633
634 if (pHdr->cbUser)
635 {
636 pEntry->pszUser = (char *)RTMemDup((uint8_t *)pvBuf + offBuf, pHdr->cbUser);
637 AssertPtrBreakStmt(pEntry->pszUser, vrc = VERR_NO_MEMORY);
638 pEntry->cbUser = pHdr->cbUser;
639 offBuf += pHdr->cbUser;
640 }
641
642 if (pHdr->cbGroups)
643 {
644 pEntry->pszGroups = (char *)RTMemDup((uint8_t *)pvBuf + offBuf, pHdr->cbGroups);
645 AssertPtrBreakStmt(pEntry->pszGroups, vrc = VERR_NO_MEMORY);
646 pEntry->cbGroups = pHdr->cbGroups;
647 offBuf += pHdr->cbGroups;
648 }
649
650#ifdef DEBUG
651 GuestFsObjData obj;
652 AssertRC(obj.FromGuestFsObjInfo(&pEntry->pDirEntryEx->Info, pEntry->pszUser, pEntry->pszGroups));
653 AssertRC(RTStrValidateEncodingEx(pEntry->pszUser, pHdr->cbUser, RTSTR_VALIDATE_ENCODING_ZERO_TERMINATED));
654 AssertRC(RTStrValidateEncodingEx(pEntry->pszGroups, pHdr->cbGroups, RTSTR_VALIDATE_ENCODING_ZERO_TERMINATED));
655#endif
656 }
657
658 if (RT_SUCCESS(vrc))
659 {
660 Assert(offBuf == cbBuf);
661 }
662 else /* Roll back on error. */
663 {
664 GuestDirectory::i_dirNotifyDataDestroy(&dataCb);
665 }
666 break;
667 }
668
669 default:
670 AssertFailed();
671 break;
672 }
673
674 try
675 {
676 if (RT_SUCCESS(vrc))
677 {
678 GuestWaitEventPayload payload(dataCb.uType, &dataCb, sizeof(dataCb));
679
680 /* Ignore return code, as the event to signal might not be there (anymore). */
681 signalWaitEventInternal(pCbCtx, vrcGuest, &payload);
682 }
683 else /* OOM situation, wrong HGCM parameters or smth. not expected. */
684 {
685 /* Ignore return code, as the event to signal might not be there (anymore). */
686 signalWaitEventInternalEx(pCbCtx, vrc, 0 /* guestRc */, NULL /* pPayload */);
687 }
688 }
689 catch (int vrcEx) /* Thrown by GuestWaitEventPayload constructor. */
690 {
691 /* Also try to signal the waiter, to let it know of the OOM situation.
692 * Ignore return code, as the event to signal might not be there (anymore). */
693 signalWaitEventInternalEx(pCbCtx, vrcEx, 0 /* guestRc */, NULL /* pPayload */);
694 vrc = vrcEx;
695 }
696
697 LogFlowThisFunc(("uType=%RU32, rcGuest=%Rrc, vrc=%Rrc\n", dataCb.uType, vrcGuest, vrc));
698 return vrc;
699#endif /* VBOX_WITH_GSTCTL_TOOLBOX_AS_CMDS */
700}
701
702/**
703 * Static helper function to convert a given guest directory error to a string.
704 *
705 * @returns Error string.
706 * @param vrcGuest Guest directory error to return string for.
707 * @param pcszWhat Hint of what was involved when the error occurred.
708 */
709/* static */
710Utf8Str GuestDirectory::i_guestErrorToString(int vrcGuest, const char *pcszWhat)
711{
712 AssertPtrReturn(pcszWhat, "");
713
714#define CASE_MSG(a_iRc, ...) \
715 case a_iRc: strErr.printf(__VA_ARGS__); break;
716
717 Utf8Str strErr;
718 switch (vrcGuest)
719 {
720 CASE_MSG(VERR_ACCESS_DENIED, tr("Access to guest directory \"%s\" is denied"), pcszWhat);
721 CASE_MSG(VERR_ALREADY_EXISTS, tr("Guest directory \"%s\" already exists"), pcszWhat);
722 CASE_MSG(VERR_CANT_CREATE, tr("Guest directory \"%s\" cannot be created"), pcszWhat);
723 CASE_MSG(VERR_DIR_NOT_EMPTY, tr("Guest directory \"%s\" is not empty"), pcszWhat);
724 CASE_MSG(VERR_NO_MORE_FILES, tr("Guest directory \"%s\" has no more entries"), pcszWhat);
725 CASE_MSG(VERR_PATH_NOT_FOUND, tr("Path of guest directory \"%s\" not found"), pcszWhat);
726 default:
727 strErr.printf(tr("Error %Rrc for guest directory \"%s\" occurred\n"), vrcGuest, pcszWhat);
728 break;
729 }
730
731#undef CASE_MSG
732
733 return strErr;
734}
735
736/**
737 * Static helper function to destroy direction notification callback data.
738 *
739 * @param pDirNotify Pointer to direction notification callback data to destroy.
740 */
741/* static */
742void GuestDirectory::i_dirNotifyDataDestroy(PCALLBACKDATA_DIR_NOTIFY pDirNotify)
743{
744 if (!pDirNotify)
745 return;
746
747 switch (pDirNotify->uType)
748 {
749 case GUEST_DIR_NOTIFYTYPE_LIST:
750 {
751 for (uint32_t i = 0; i < pDirNotify->u.list.cEntries; i++)
752 {
753 PCALLBACKDATA_DIR_ENTRY const pEntry = pDirNotify->u.list.paEntries[i];
754 AssertPtrBreak(pEntry);
755 RTStrFree(pEntry->pszUser);
756 RTStrFree(pEntry->pszGroups);
757 RTMemFree(pEntry->pDirEntryEx);
758 RTMemFree(pEntry);
759 }
760 RTMemFree(pDirNotify->u.list.paEntries);
761 pDirNotify->u.list.paEntries = NULL;
762 pDirNotify->u.list.cEntries = 0;
763 break;
764 }
765
766 default:
767 break;
768 }
769}
770
771/**
772 * @copydoc GuestObject::i_onUnregister
773 */
774int GuestDirectory::i_onUnregister(void)
775{
776 LogFlowThisFuncEnter();
777
778 int vrc = VINF_SUCCESS;
779
780 LogFlowFuncLeaveRC(vrc);
781 return vrc;
782}
783
784/**
785 * @copydoc GuestObject::i_onSessionStatusChange
786 */
787int GuestDirectory::i_onSessionStatusChange(GuestSessionStatus_T enmSessionStatus)
788{
789 RT_NOREF(enmSessionStatus);
790
791 LogFlowThisFuncEnter();
792
793 int vrc = VINF_SUCCESS;
794
795 LogFlowFuncLeaveRC(vrc);
796 return vrc;
797}
798
799/**
800 * Closes this guest directory and removes it from the
801 * guest session's directory list.
802 *
803 * @return VBox status code.
804 * @param pvrcGuest Where to store the guest result code in case VERR_GSTCTL_GUEST_ERROR is returned.
805 */
806int GuestDirectory::i_close(int *pvrcGuest)
807{
808 int vrc;
809#ifdef VBOX_WITH_GSTCTL_TOOLBOX_AS_CMDS
810 if (mSession->i_getParent()->i_getGuestControlFeatures0() & VBOX_GUESTCTRL_GF_0_TOOLBOX_AS_CMDS)
811 {
812 GuestWaitEvent *pEvent = NULL;
813 GuestEventTypes eventTypes;
814 try
815 {
816 eventTypes.push_back(VBoxEventType_OnGuestDirectoryStateChanged);
817
818 vrc = registerWaitEvent(eventTypes, &pEvent);
819 }
820 catch (std::bad_alloc &)
821 {
822 vrc = VERR_NO_MEMORY;
823 }
824
825 if (RT_FAILURE(vrc))
826 return vrc;
827
828 /* Prepare HGCM call. */
829 VBOXHGCMSVCPARM paParms[2];
830 int i = 0;
831 HGCMSvcSetU32(&paParms[i++], pEvent->ContextID());
832 HGCMSvcSetU32(&paParms[i++], mObjectID /* Guest directory handle */);
833
834 vrc = sendMessage(HOST_MSG_DIR_CLOSE, i, paParms);
835 if (RT_SUCCESS(vrc))
836 {
837 vrc = pEvent->Wait(30 * 1000);
838 if (RT_SUCCESS(vrc))
839 {
840 // Nothing to do here.
841 }
842 else if (pEvent->HasGuestError() && pvrcGuest)
843 *pvrcGuest = pEvent->GuestResult();
844 }
845 }
846 else
847#endif /* VBOX_WITH_GSTCTL_TOOLBOX_AS_CMDS */
848 {
849 vrc = i_closeViaToolbox(pvrcGuest);
850 }
851
852 AssertPtr(mSession);
853 int vrc2 = mSession->i_directoryUnregister(this);
854 if (RT_SUCCESS(vrc))
855 vrc = vrc2;
856
857 LogFlowThisFunc(("Returning vrc=%Rrc\n", vrc));
858 return vrc;
859}
860
861#ifdef VBOX_WITH_GSTCTL_TOOLBOX_SUPPORT
862/**
863 * Closes this guest directory and removes it from the guest session's directory list (legacy version).
864 *
865 * @return VBox status code.
866 * @param pvrcGuest Where to store the guest result code in case VERR_GSTCTL_GUEST_ERROR is returned.
867 *
868 * @note This uses an own guest process via the built-in toolbox in VBoxSerivce.
869 */
870int GuestDirectory::i_closeViaToolbox(int *pvrcGuest)
871{
872 return mData.mProcessTool.terminate(30 * 1000 /* 30s timeout */, pvrcGuest);
873}
874#endif /* VBOX_WITH_GSTCTL_TOOLBOX_SUPPORT */
875
876/**
877 * Reads the next directory entry, internal version.
878 *
879 * @return VBox status code.
880 * @retval VERR_GSTCTL_GUEST_ERROR / VERR_NO_MORE_FILES if no more entries are available.
881 * @param objData Where to store the read directory entry as internal object data.
882 * @param pvrcGuest Where to store the guest result code in case VERR_GSTCTL_GUEST_ERROR is returned.
883 */
884int GuestDirectory::i_readInternal(GuestFsObjData &objData, int *pvrcGuest)
885{
886 AssertPtrReturn(pvrcGuest, VERR_INVALID_POINTER);
887
888 int vrc;
889
890#ifdef VBOX_WITH_GSTCTL_TOOLBOX_AS_CMDS
891 if (mSession->i_getParent()->i_getGuestControlFeatures0() & VBOX_GUESTCTRL_GF_0_TOOLBOX_AS_CMDS)
892 {
893 GuestWaitEvent *pEvent = NULL;
894 GuestEventTypes eventTypes;
895 try
896 {
897 vrc = registerWaitEvent(eventTypes, &pEvent);
898 }
899 catch (std::bad_alloc &)
900 {
901 vrc = VERR_NO_MEMORY;
902 }
903
904 if (RT_FAILURE(vrc))
905 return vrc;
906
907 /* Prepare HGCM call. */
908 VBOXHGCMSVCPARM paParms[4];
909 int i = 0;
910 HGCMSvcSetU32(&paParms[i++], pEvent->ContextID());
911 HGCMSvcSetU32(&paParms[i++], mObjectID /* Guest directory handle */);
912
913 vrc = sendMessage(HOST_MSG_DIR_READ, i, paParms);
914 if (RT_SUCCESS(vrc))
915 {
916 vrc = pEvent->Wait(30 * 1000);
917 if (RT_SUCCESS(vrc))
918 {
919 PCALLBACKDATA_DIR_NOTIFY const pDirNotify = (PCALLBACKDATA_DIR_NOTIFY)pEvent->Payload().Raw();
920 AssertPtrReturn(pDirNotify, VERR_INVALID_POINTER);
921 int vrcGuest = (int)pDirNotify->rc;
922 if (RT_SUCCESS(vrcGuest))
923 {
924 AssertReturn(pDirNotify->uType == GUEST_DIR_NOTIFYTYPE_READ, VERR_INVALID_PARAMETER);
925 AssertPtrReturn(pDirNotify->u.read.Entry.pDirEntryEx, VERR_INVALID_POINTER);
926 objData.Init(pDirNotify->u.read.Entry.pDirEntryEx->szName);
927 vrc = objData.FromGuestFsObjInfo(&pDirNotify->u.read.Entry.pDirEntryEx->Info,
928 pDirNotify->u.read.Entry.pszUser, pDirNotify->u.read.Entry.pszGroups);
929 RTMemFree(pDirNotify->u.read.Entry.pDirEntryEx);
930 RTStrFree(pDirNotify->u.read.Entry.pszUser);
931 RTStrFree(pDirNotify->u.read.Entry.pszGroups);
932 }
933 else
934 {
935 *pvrcGuest = vrcGuest;
936 vrc = VERR_GSTCTL_GUEST_ERROR;
937 }
938 }
939 else if (pEvent->HasGuestError() && pvrcGuest)
940 *pvrcGuest = pEvent->GuestResult();
941 }
942 }
943 else
944#endif /* VBOX_WITH_GSTCTL_TOOLBOX_AS_CMDS */
945 {
946 vrc = i_readInternalViaToolbox(objData, pvrcGuest);
947 }
948
949 LogFlowThisFunc(("Returning vrc=%Rrc\n", vrc));
950 return vrc;
951}
952
953#ifdef VBOX_WITH_GSTCTL_TOOLBOX_SUPPORT
954/**
955 * Reads the next directory entry, internal version (legacy version).
956 *
957 * @return VBox status code. Will return VERR_NO_MORE_FILES if no more entries are available.
958 * @param objData Where to store the read directory entry as internal object data.
959 * @param pvrcGuest Where to store the guest result code in case VERR_GSTCTL_GUEST_ERROR is returned.
960 *
961 * @note This uses an own guest process via the built-in toolbox in VBoxSerivce.
962 */
963int GuestDirectory::i_readInternalViaToolbox(GuestFsObjData &objData, int *pvrcGuest)
964{
965 GuestToolboxStreamBlock curBlock;
966 int vrc = mData.mProcessTool.waitEx(GUESTPROCESSTOOL_WAIT_FLAG_STDOUT_BLOCK, &curBlock, pvrcGuest);
967 if (RT_SUCCESS(vrc))
968 {
969 /*
970 * Note: The guest process can still be around to serve the next
971 * upcoming stream block next time.
972 */
973 if (!mData.mProcessTool.isRunning())
974 vrc = mData.mProcessTool.getTerminationStatus(); /* Tool process is not running (anymore). Check termination status. */
975
976 if (RT_SUCCESS(vrc))
977 {
978 if (curBlock.GetCount()) /* Did we get content? */
979 {
980 if (curBlock.GetString("name"))
981 {
982 vrc = objData.FromToolboxLs(curBlock, true /* fLong */);
983 }
984 else
985 {
986#ifdef DEBUG
987 curBlock.DumpToLog();
988#endif
989 vrc = VERR_PATH_NOT_FOUND;
990 }
991 }
992 else
993 {
994 /* Nothing to read anymore. Tell the caller. */
995 vrc = VERR_NO_MORE_FILES;
996 }
997 }
998 }
999
1000 return vrc;
1001}
1002#endif /* VBOX_WITH_GSTCTL_TOOLBOX_SUPPORT */
1003
1004/**
1005 * Worker for listing the next directory entries.
1006 *
1007 * @return VBox status code.
1008 * @retval VERR_GSTCTL_GUEST_ERROR / VERR_NO_MORE_FILES if no more entries are available after this iteration.
1009 * \a vecObjData will contain the rest of the entries then (if any).
1010 * @param cMaxEntries How many directory entries to read at max.
1011 * @param fFlags Flags of type GSTCTL_DIRLIST_F_XXX.
1012 * @param vecObjData Where to store the read directory entries on success.
1013 * @param pvrcGuest Where to store the guest result code in case VERR_GSTCTL_GUEST_ERROR is returned.
1014 */
1015int GuestDirectory::i_listInternal(uint32_t cMaxEntries, uint32_t fFlags, std::vector<GuestFsObjData> &vecObjData, int *pvrcGuest)
1016{
1017 int vrc;
1018
1019#ifdef VBOX_WITH_GSTCTL_TOOLBOX_AS_CMDS
1020 if (mSession->i_getParent()->i_getGuestControlFeatures0() & VBOX_GUESTCTRL_GF_0_TOOLBOX_AS_CMDS)
1021 {
1022 GuestWaitEvent *pEvent = NULL;
1023 GuestEventTypes eventTypes;
1024 try
1025 {
1026 vrc = registerWaitEvent(eventTypes, &pEvent);
1027 }
1028 catch (std::bad_alloc &)
1029 {
1030 vrc = VERR_NO_MEMORY;
1031 }
1032
1033 if (RT_FAILURE(vrc))
1034 return vrc;
1035
1036 /* Prepare HGCM call. */
1037 VBOXHGCMSVCPARM paParms[4];
1038 int i = 0;
1039 HGCMSvcSetU32(&paParms[i++], pEvent->ContextID());
1040 HGCMSvcSetU32(&paParms[i++], mObjectID /* Directory handle */);
1041 HGCMSvcSetU32(&paParms[i++], cMaxEntries);
1042 HGCMSvcSetU32(&paParms[i++], 0 /* Flags */);
1043
1044 vrc = sendMessage(HOST_MSG_DIR_LIST, i, paParms);
1045 if (RT_SUCCESS(vrc))
1046 {
1047 vrc = pEvent->Wait(30 * 1000);
1048 if (RT_SUCCESS(vrc))
1049 {
1050 PCALLBACKDATA_DIR_NOTIFY const pDirNotify = (PCALLBACKDATA_DIR_NOTIFY)pEvent->Payload().Raw();
1051 AssertPtrReturn(pDirNotify, VERR_INVALID_POINTER);
1052 int vrcGuest = (int)pDirNotify->rc;
1053 if ( RT_SUCCESS(vrcGuest)
1054 /* Guest indicates that there are no more entries to read.
1055 * We still need to check if we have read something with this iteration though. */
1056 || vrcGuest == VERR_NO_MORE_FILES)
1057 {
1058 AssertReturn(pDirNotify->uType == GUEST_DIR_NOTIFYTYPE_LIST, VERR_INVALID_PARAMETER);
1059
1060 try
1061 {
1062 vecObjData.resize(pDirNotify->u.list.cEntries);
1063 }
1064 catch (std::bad_alloc &)
1065 {
1066 vrc = VERR_NO_MEMORY;
1067 }
1068
1069 if (RT_SUCCESS(vrc))
1070 {
1071 for (size_t a = 0; a < pDirNotify->u.list.cEntries; a++)
1072 {
1073 PCALLBACKDATA_DIR_ENTRY const pEntry = pDirNotify->u.list.paEntries[a];
1074 AssertPtr(pEntry);
1075
1076 AssertPtr(pEntry->pDirEntryEx);
1077 vecObjData[a].Init(pEntry->pDirEntryEx->szName);
1078 int vrc2 = vecObjData[a].FromGuestFsObjInfo(&pEntry->pDirEntryEx->Info, pEntry->pszUser, pEntry->pszGroups);
1079 if (RT_SUCCESS(vrc))
1080 vrc = vrc2;
1081 }
1082 }
1083 }
1084 else
1085 {
1086 *pvrcGuest = vrcGuest;
1087 vrc = VERR_GSTCTL_GUEST_ERROR;
1088 }
1089
1090 GuestDirectory::i_dirNotifyDataDestroy(pDirNotify);
1091 }
1092 else if (pEvent->HasGuestError())
1093 *pvrcGuest = pEvent->GuestResult();
1094 }
1095 }
1096 else
1097#endif /* VBOX_WITH_GSTCTL_TOOLBOX_AS_CMDS */
1098 {
1099 RT_NOREF(cMaxEntries, fFlags, vecObjData, pvrcGuest);
1100 vrc = VERR_NOT_SUPPORTED;
1101 }
1102
1103 return vrc;
1104}
1105
1106/**
1107 * Lists the next directory entries.
1108 *
1109 * @return VBox status code.
1110 * @retval VERR_GSTCTL_GUEST_ERROR / VERR_NO_MORE_FILES if no more entries are available after this iteration.
1111 * \a vecObjData will contain the rest of the entries then (if any).
1112 * @param cMaxEntries How many directory entries to read at max.
1113 * @param fFlags Flags of type GSTCTL_DIRLIST_F_XXX.
1114 * @param vecObjInfo Where to store the read directory entries on success.
1115 * @param pvrcGuest Where to store the guest result code in case VERR_GSTCTL_GUEST_ERROR is returned.
1116 */
1117int GuestDirectory::i_listEx(uint32_t cMaxEntries, uint32_t fFlags, std::vector<ComObjPtr<GuestFsObjInfo>> &vecObjInfo,
1118 int *pvrcGuest)
1119{
1120 AssertPtrReturn(pvrcGuest, VERR_INVALID_POINTER);
1121 AssertReturn(!(fFlags & ~GSTCTL_DIRLIST_F_VALID_MASK), VERR_INVALID_PARAMETER);
1122
1123 std::vector<GuestFsObjData> vecObjDataInt;
1124 int vrc = i_listInternal(cMaxEntries, fFlags, vecObjDataInt, pvrcGuest);
1125 if ( RT_SUCCESS(vrc)
1126 || ( vrc == VERR_GSTCTL_GUEST_ERROR
1127 && *pvrcGuest == VERR_NO_MORE_FILES))
1128 {
1129 try
1130 {
1131 vecObjInfo.resize(vecObjDataInt.size());
1132 for (size_t i = 0; i < vecObjDataInt.size(); i++)
1133 {
1134 HRESULT hrc = vecObjInfo[i].createObject();
1135 ComAssertComRCBreak(hrc, vrc = VERR_COM_UNEXPECTED);
1136
1137 vrc = vecObjInfo[i]->init(vecObjDataInt[i]);
1138 if (RT_FAILURE(vrc))
1139 break;
1140 }
1141 }
1142 catch (std::bad_alloc &)
1143 {
1144 vrc = VERR_NO_MEMORY;
1145 }
1146 }
1147
1148 return vrc;
1149}
1150
1151/**
1152 * Lists the next directory entries.
1153 *
1154 * @return VBox status code.
1155 * @retval VERR_GSTCTL_GUEST_ERROR / VERR_NO_MORE_FILES if no more entries are available after this iteration.
1156 * \a vecObjData will contain the rest of the entries then (if any).
1157 * @param cMaxEntries How many directory entries to read at max.
1158 * @param vecObjInfo Where to store the read directory entries on success.
1159 * @param pvrcGuest Where to store the guest result code in case VERR_GSTCTL_GUEST_ERROR is returned.
1160 */
1161int GuestDirectory::i_list(uint32_t cMaxEntries, std::vector<ComObjPtr<GuestFsObjInfo>> &vecObjInfo, int *pvrcGuest)
1162{
1163 return i_listEx(cMaxEntries, GSTCTL_DIRLIST_F_NONE, vecObjInfo, pvrcGuest);
1164}
1165
1166/**
1167 * Reads the next directory entry.
1168 *
1169 * @return VBox status code.
1170 * @retval VERR_GSTCTL_GUEST_ERROR / VERR_NO_MORE_FILES if no more entries are available.
1171 * @param fsObjInfo Where to store the read directory entry.
1172 * @param pvrcGuest Where to store the guest result code in case VERR_GSTCTL_GUEST_ERROR is returned.
1173 */
1174int GuestDirectory::i_read(ComObjPtr<GuestFsObjInfo> &fsObjInfo, int *pvrcGuest)
1175{
1176 AssertPtrReturn(pvrcGuest, VERR_INVALID_POINTER);
1177
1178 /* Create the FS info object. */
1179 HRESULT hr = fsObjInfo.createObject();
1180 if (FAILED(hr))
1181 return VERR_COM_UNEXPECTED;
1182
1183 int vrc;
1184
1185 /* If we have a valid object data cache, read from it. */
1186 if (mData.mObjData.mName.isNotEmpty())
1187 {
1188 vrc = fsObjInfo->init(mData.mObjData);
1189 if (RT_SUCCESS(vrc))
1190 {
1191 mData.mObjData.mName = ""; /* Mark the object data as being empty (beacon). */
1192 }
1193 }
1194 else /* Otherwise ask the guest for the next object data. */
1195 {
1196 GuestFsObjData objData;
1197 vrc = i_readInternal(objData, pvrcGuest);
1198 if (RT_SUCCESS(vrc))
1199 vrc = fsObjInfo->init(objData);
1200 }
1201
1202 LogFlowThisFunc(("Returning vrc=%Rrc\n", vrc));
1203 return vrc;
1204}
1205
1206/**
1207 * Rewinds the directory reading.
1208 *
1209 * @returns VBox status code.
1210 * @retval VERR_GSTCTL_GUEST_ERROR when an error from the guest side has been received.
1211 * @param uTimeoutMS Timeout (in ms) to wait.
1212 * @param pvrcGuest Where to store the guest result code in case VERR_GSTCTL_GUEST_ERROR is returned.
1213 */
1214int GuestDirectory::i_rewind(uint32_t uTimeoutMS, int *pvrcGuest)
1215{
1216 RT_NOREF(pvrcGuest);
1217#ifndef VBOX_WITH_GSTCTL_TOOLBOX_AS_CMDS
1218 RT_NOREF(uTimeoutMS, pvrcGuest);
1219#else
1220 /* Only available for Guest Additions 7.1+. */
1221 if (mSession->i_getParent()->i_getGuestControlFeatures0() & VBOX_GUESTCTRL_GF_0_TOOLBOX_AS_CMDS)
1222 {
1223 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1224
1225 int vrc;
1226
1227 GuestWaitEvent *pEvent = NULL;
1228 GuestEventTypes eventTypes;
1229 try
1230 {
1231 eventTypes.push_back(VBoxEventType_OnGuestDirectoryStateChanged);
1232 vrc = registerWaitEvent(eventTypes, &pEvent);
1233 }
1234 catch (std::bad_alloc &)
1235 {
1236 vrc = VERR_NO_MEMORY;
1237 }
1238
1239 if (RT_FAILURE(vrc))
1240 return vrc;
1241
1242 /* Prepare HGCM call. */
1243 VBOXHGCMSVCPARM paParms[4];
1244 int i = 0;
1245 HGCMSvcSetU32(&paParms[i++], pEvent->ContextID());
1246 HGCMSvcSetU32(&paParms[i++], mObjectID /* Directory handle */);
1247
1248 alock.release(); /* Drop lock before sending. */
1249
1250 vrc = sendMessage(HOST_MSG_DIR_REWIND, i, paParms);
1251 if (RT_SUCCESS(vrc))
1252 {
1253 VBoxEventType_T evtType;
1254 ComPtr<IEvent> pIEvent;
1255 vrc = waitForEvent(pEvent, uTimeoutMS, &evtType, pIEvent.asOutParam());
1256 if (RT_SUCCESS(vrc))
1257 {
1258 if (evtType == VBoxEventType_OnGuestDirectoryStateChanged)
1259 {
1260 ComPtr<IGuestDirectoryStateChangedEvent> pEvt = pIEvent;
1261 Assert(!pEvt.isNull());
1262 }
1263 else
1264 vrc = VWRN_GSTCTL_OBJECTSTATE_CHANGED;
1265 }
1266 else if (pEvent->HasGuestError()) /* Return guest vrc if available. */
1267 vrc = pEvent->GuestResult();
1268 }
1269
1270 unregisterWaitEvent(pEvent);
1271 return vrc;
1272 }
1273#endif /* VBOX_WITH_GSTCTL_TOOLBOX_AS_CMDS */
1274
1275 return VERR_NOT_SUPPORTED;
1276}
1277
1278/**
1279 * Sets the current internal directory object status.
1280 *
1281 * @returns VBox status code.
1282 * @param enmStatus New directory status to set.
1283 * @param vrcDir New result code to set.
1284 *
1285 * @note Takes the write lock.
1286 */
1287int GuestDirectory::i_setStatus(DirectoryStatus_T enmStatus, int vrcDir)
1288{
1289 LogFlowThisFuncEnter();
1290
1291 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1292
1293 LogFlowThisFunc(("oldStatus=%RU32, newStatus=%RU32, vrcDir=%Rrc\n", mData.mStatus, enmStatus, vrcDir));
1294
1295#ifdef VBOX_STRICT
1296 if (enmStatus == DirectoryStatus_Error)
1297 AssertMsg(RT_FAILURE(vrcDir), ("Guest vrc must be an error (%Rrc)\n", vrcDir));
1298 else
1299 AssertMsg(RT_SUCCESS(vrcDir), ("Guest vrc must not be an error (%Rrc)\n", vrcDir));
1300#endif
1301
1302 if (mData.mStatus != enmStatus)
1303 {
1304 mData.mStatus = enmStatus;
1305 mData.mLastError = vrcDir;
1306
1307 ComObjPtr<VirtualBoxErrorInfo> errorInfo;
1308 HRESULT hrc = errorInfo.createObject();
1309 ComAssertComRCRet(hrc, VERR_COM_UNEXPECTED);
1310 if (RT_FAILURE(vrcDir))
1311 {
1312 hrc = errorInfo->initEx(VBOX_E_GSTCTL_GUEST_ERROR, vrcDir,
1313 COM_IIDOF(IGuestDirectory), getComponentName(),
1314 i_guestErrorToString(vrcDir, mData.mOpenInfo.mPath.c_str()));
1315 ComAssertComRCRet(hrc, VERR_COM_UNEXPECTED);
1316 }
1317 /* Note: On vrcDir success, errorInfo is set to S_OK and also sent via the event below. */
1318
1319 alock.release(); /* Release lock before firing off event. */
1320
1321 ::FireGuestDirectoryStateChangedEvent(mEventSource, mSession, this, mData.mStatus, errorInfo);
1322 }
1323
1324 return VINF_SUCCESS;
1325}
1326
1327/**
1328 * Waits for a guest directory status change.
1329 *
1330 * @note Similar code in GuestFile::i_waitForStatusChange().
1331 *
1332 * @returns VBox status code.
1333 * @retval VERR_GSTCTL_GUEST_ERROR when an error from the guest side has been received.
1334 * @param pEvent Guest wait event to wait for.
1335 * @param uTimeoutMS Timeout (in ms) to wait.
1336 * @param penmStatus Where to return the directoy status on success.
1337 * @param prcGuest Where to return the guest error when VERR_GSTCTL_GUEST_ERROR was returned.
1338 */
1339int GuestDirectory::i_waitForStatusChange(GuestWaitEvent *pEvent, uint32_t uTimeoutMS,
1340 DirectoryStatus_T *penmStatus, int *prcGuest)
1341{
1342 AssertPtrReturn(pEvent, VERR_INVALID_POINTER);
1343 /* penmStatus is optional. */
1344
1345 VBoxEventType_T evtType;
1346 ComPtr<IEvent> pIEvent;
1347 int vrc = waitForEvent(pEvent, uTimeoutMS, &evtType, pIEvent.asOutParam());
1348 if (RT_SUCCESS(vrc))
1349 {
1350 AssertReturn(evtType == VBoxEventType_OnGuestDirectoryStateChanged, VERR_WRONG_TYPE);
1351 ComPtr<IGuestDirectoryStateChangedEvent> pDirectoryEvent = pIEvent;
1352 AssertReturn(!pDirectoryEvent.isNull(), VERR_COM_UNEXPECTED);
1353
1354 HRESULT hr;
1355 if (penmStatus)
1356 {
1357 hr = pDirectoryEvent->COMGETTER(Status)(penmStatus);
1358 ComAssertComRC(hr);
1359 }
1360
1361 ComPtr<IVirtualBoxErrorInfo> errorInfo;
1362 hr = pDirectoryEvent->COMGETTER(Error)(errorInfo.asOutParam());
1363 ComAssertComRC(hr);
1364
1365 LONG lGuestRc;
1366 hr = errorInfo->COMGETTER(ResultDetail)(&lGuestRc);
1367 ComAssertComRC(hr);
1368
1369 LogFlowThisFunc(("resultDetail=%RI32 (%Rrc)\n", lGuestRc, lGuestRc));
1370
1371 if (RT_FAILURE((int)lGuestRc))
1372 vrc = VERR_GSTCTL_GUEST_ERROR;
1373
1374 if (prcGuest)
1375 *prcGuest = (int)lGuestRc;
1376 }
1377 /* waitForEvent may also return VERR_GSTCTL_GUEST_ERROR like we do above, so make prcGuest is set. */
1378 /** @todo Also see todo in GuestFile::i_waitForStatusChange(). */
1379 else if (vrc == VERR_GSTCTL_GUEST_ERROR && prcGuest)
1380 *prcGuest = pEvent->GuestResult();
1381 Assert(vrc != VERR_GSTCTL_GUEST_ERROR || !prcGuest || *prcGuest != (int)0xcccccccc);
1382
1383 return vrc;
1384}
1385
1386// implementation of public methods
1387/////////////////////////////////////////////////////////////////////////////
1388HRESULT GuestDirectory::close()
1389{
1390 AutoCaller autoCaller(this);
1391 if (FAILED(autoCaller.hrc())) return autoCaller.hrc();
1392
1393 LogFlowThisFuncEnter();
1394
1395 HRESULT hrc = S_OK;
1396
1397 int vrcGuest = VERR_IPE_UNINITIALIZED_STATUS;
1398 int vrc = i_close(&vrcGuest);
1399 if (RT_FAILURE(vrc))
1400 {
1401 switch (vrc)
1402 {
1403 case VERR_GSTCTL_GUEST_ERROR:
1404 {
1405 GuestErrorInfo ge(GuestErrorInfo::Type_Directory, vrcGuest, mData.mOpenInfo.mPath.c_str());
1406 hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrcGuest, tr("Closing guest directory failed: %s"),
1407 GuestBase::getErrorAsString(ge).c_str());
1408 break;
1409 }
1410 case VERR_NOT_SUPPORTED:
1411 /* Silently skip old Guest Additions which do not support killing the
1412 * the guest directory handling process. */
1413 break;
1414
1415 default:
1416 hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc,
1417 tr("Closing guest directory \"%s\" failed: %Rrc"), mData.mOpenInfo.mPath.c_str(), vrc);
1418 break;
1419 }
1420 }
1421
1422 return hrc;
1423}
1424
1425HRESULT GuestDirectory::list(ULONG aMaxEntries, std::vector<ComPtr<IFsObjInfo> > &aObjInfos)
1426{
1427 AutoCaller autoCaller(this);
1428 if (FAILED(autoCaller.hrc())) return autoCaller.hrc();
1429
1430 LogFlowThisFuncEnter();
1431
1432 HRESULT hrc = S_OK;
1433
1434 std::vector<ComObjPtr<GuestFsObjInfo> > vecObjInfo;
1435 int vrcGuest = VERR_IPE_UNINITIALIZED_STATUS;
1436 int vrc = i_list(aMaxEntries, vecObjInfo, &vrcGuest);
1437
1438 /* Don't propagate an error to API callers when this is the last listing (i.e. no more files).
1439 * For subsequent reads the API caller gets an appropriate error then. */
1440 if ( vrc == VERR_GSTCTL_GUEST_ERROR
1441 && vrcGuest == VERR_NO_MORE_FILES
1442 && vecObjInfo.size())
1443 vrc = VINF_SUCCESS;
1444
1445 if (RT_SUCCESS(vrc))
1446 {
1447 try
1448 {
1449 aObjInfos.resize(vecObjInfo.size());
1450
1451 for (size_t i = 0; i < vecObjInfo.size(); i++)
1452 {
1453 hrc = vecObjInfo[i].queryInterfaceTo(aObjInfos[i].asOutParam());
1454 ComAssertComRCBreakRC(hrc);
1455 }
1456 }
1457 catch (std::bad_alloc &)
1458 {
1459 hrc = E_OUTOFMEMORY;
1460 }
1461 }
1462 else
1463 {
1464 switch (vrc)
1465 {
1466 case VERR_GSTCTL_GUEST_ERROR:
1467 {
1468 GuestErrorInfo ge(GuestErrorInfo::Type_Directory, vrcGuest, mData.mOpenInfo.mPath.c_str());
1469 hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrcGuest, tr("Listing guest directory failed: %s"),
1470 GuestBase::getErrorAsString(ge).c_str());
1471
1472 /* Return a dedicated error code when directory reading is done. See SDK reference. */
1473 if (vrcGuest == VERR_NO_MORE_FILES)
1474 hrc = VBOX_E_OBJECT_NOT_FOUND;
1475 break;
1476 }
1477
1478 default:
1479 hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("Listing guest directory \"%s\" returned unhandled error: %Rrc\n"),
1480 mData.mOpenInfo.mPath.c_str(), vrc);
1481 break;
1482 }
1483 }
1484
1485 LogFlowThisFunc(("Returning hrc=%Rhrc / vrc=%Rrc\n", hrc, vrc));
1486 return hrc;
1487}
1488
1489HRESULT GuestDirectory::read(ComPtr<IFsObjInfo> &aObjInfo)
1490{
1491 AutoCaller autoCaller(this);
1492 if (FAILED(autoCaller.hrc())) return autoCaller.hrc();
1493
1494 LogFlowThisFuncEnter();
1495
1496 HRESULT hrc = S_OK;
1497
1498 ComObjPtr<GuestFsObjInfo> fsObjInfo;
1499 int vrcGuest = VERR_IPE_UNINITIALIZED_STATUS;
1500 int vrc = i_read(fsObjInfo, &vrcGuest);
1501 if (RT_SUCCESS(vrc))
1502 {
1503 /* Return info object to the caller. */
1504 hrc = fsObjInfo.queryInterfaceTo(aObjInfo.asOutParam());
1505 }
1506 else
1507 {
1508 switch (vrc)
1509 {
1510 case VERR_GSTCTL_GUEST_ERROR:
1511 {
1512 GuestErrorInfo ge(
1513#ifdef VBOX_WITH_GSTCTL_TOOLBOX_SUPPORT
1514 GuestErrorInfo::Type_ToolLs
1515#else
1516 GuestErrorInfo::Type_Directory
1517#endif
1518 , vrcGuest, mData.mOpenInfo.mPath.c_str());
1519 hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrcGuest, tr("Reading guest directory failed: %s"),
1520 GuestBase::getErrorAsString(ge).c_str());
1521
1522 /* Return a dedicated error code when directory reading is done. See SDK reference. */
1523 if (vrcGuest == VERR_NO_MORE_FILES)
1524 hrc = VBOX_E_OBJECT_NOT_FOUND;
1525 break;
1526 }
1527
1528#ifdef VBOX_WITH_GSTCTL_TOOLBOX_SUPPORT
1529 case VERR_GSTCTL_PROCESS_EXIT_CODE:
1530 hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("Reading guest directory \"%s\" failed: %Rrc"),
1531 mData.mOpenInfo.mPath.c_str(), mData.mProcessTool.getRc());
1532 break;
1533
1534 case VERR_PATH_NOT_FOUND:
1535 hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("Reading guest directory \"%s\" failed: Path not found"),
1536 mData.mOpenInfo.mPath.c_str());
1537 break;
1538
1539 case VERR_NO_MORE_FILES:
1540 /* See SDK reference. */
1541 hrc = setErrorBoth(VBOX_E_OBJECT_NOT_FOUND, vrc, tr("Reading guest directory \"%s\" failed: No more entries"),
1542 mData.mOpenInfo.mPath.c_str());
1543 break;
1544#endif
1545 default:
1546 hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("Reading guest directory \"%s\" returned unhandled error: %Rrc\n"),
1547 mData.mOpenInfo.mPath.c_str(), vrc);
1548 break;
1549 }
1550 }
1551
1552 LogFlowThisFunc(("Returning hrc=%Rhrc / vrc=%Rrc\n", hrc, vrc));
1553 return hrc;
1554}
1555
1556HRESULT GuestDirectory::rewind(void)
1557{
1558 AutoCaller autoCaller(this);
1559 if (FAILED(autoCaller.hrc())) return autoCaller.hrc();
1560
1561 int vrcGuest = VERR_IPE_UNINITIALIZED_STATUS;
1562 int vrc = i_rewind(30 * 1000 /* Timeout in ms */, &vrcGuest);
1563 if (RT_SUCCESS(vrc))
1564 return S_OK;
1565
1566 GuestErrorInfo ge(GuestErrorInfo::Type_Directory, vrcGuest, mData.mOpenInfo.mPath.c_str());
1567 return setErrorBoth(VBOX_E_IPRT_ERROR, vrcGuest, tr("Rewinding guest directory failed: %s"),
1568 GuestBase::getErrorAsString(ge).c_str());
1569}
1570
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