VirtualBox

source: vbox/trunk/src/VBox/Main/src-client/GuestCtrlImpl.cpp@ 75801

Last change on this file since 75801 was 75801, checked in by vboxsync, 6 years ago

VBoxGuestControl: Optimizing message handling - part 2. bugref:9313

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 19.7 KB
Line 
1/* $Id: GuestCtrlImpl.cpp 75801 2018-11-29 01:54:46Z vboxsync $ */
2/** @file
3 * VirtualBox COM class implementation: Guest
4 */
5
6/*
7 * Copyright (C) 2006-2018 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18#define LOG_GROUP LOG_GROUP_GUEST_CONTROL
19#include "LoggingNew.h"
20
21#include "GuestImpl.h"
22#ifdef VBOX_WITH_GUEST_CONTROL
23# include "GuestSessionImpl.h"
24# include "GuestSessionImplTasks.h"
25# include "GuestCtrlImplPrivate.h"
26#endif
27
28#include "Global.h"
29#include "ConsoleImpl.h"
30#include "ProgressImpl.h"
31#include "VBoxEvents.h"
32#include "VMMDev.h"
33
34#include "AutoCaller.h"
35
36#include <VBox/VMMDev.h>
37#ifdef VBOX_WITH_GUEST_CONTROL
38# include <VBox/com/array.h>
39# include <VBox/com/ErrorInfo.h>
40#endif
41#include <iprt/cpp/utils.h>
42#include <iprt/file.h>
43#include <iprt/getopt.h>
44#include <iprt/list.h>
45#include <iprt/path.h>
46#include <VBox/vmm/pgm.h>
47#include <VBox/AssertGuest.h>
48
49#include <memory>
50
51
52/*
53 * This #ifdef goes almost to the end of the file where there are a couple of
54 * IGuest method implementations.
55 */
56#ifdef VBOX_WITH_GUEST_CONTROL
57
58
59// public methods only for internal purposes
60/////////////////////////////////////////////////////////////////////////////
61
62/**
63 * Static callback function for receiving updates on guest control commands
64 * from the guest. Acts as a dispatcher for the actual class instance.
65 *
66 * @returns VBox status code.
67 *
68 * @todo
69 *
70 * @todo r=bird: This code mostly returned VINF_SUCCESS with the comment
71 * "Never return any errors back to the guest here." attached to the
72 * return locations. However, there is no explaination for this attitude
73 * thowards error handling. Further, it creates a slight problem since
74 * the service would route all function calls it didn't recognize here,
75 * thereby making any undefined functions confusingly return VINF_SUCCESS.
76 *
77 * In my humble opinion, if the guest gives us incorrect input it should
78 * expect and deal with error statuses. If there is unimplemented
79 * features I expect there to have been sufficient forethought by the
80 * coder that these return sensible status codes.
81 *
82 * It would be much appreciated if the esteemed card house builder could
83 * please step in and explain this confusing state of affairs.
84 */
85/* static */
86DECLCALLBACK(int) Guest::i_notifyCtrlDispatcher(void *pvExtension,
87 uint32_t idFunction,
88 void *pvData,
89 uint32_t cbData)
90{
91 using namespace guestControl;
92
93 /*
94 * No locking, as this is purely a notification which does not make any
95 * changes to the object state.
96 */
97 Log2Func(("pvExtension=%p, idFunction=%RU32, pvParms=%p, cbParms=%RU32\n", pvExtension, idFunction, pvData, cbData));
98
99 ComObjPtr<Guest> pGuest = reinterpret_cast<Guest *>(pvExtension);
100 AssertReturn(pGuest.isNotNull(), VERR_WRONG_ORDER);
101
102 /*
103 * The data packet should ever be a problem, but check to be sure.
104 */
105 AssertMsgReturn(cbData == sizeof(VBOXGUESTCTRLHOSTCALLBACK),
106 ("Guest control host callback data has wrong size (expected %zu, got %zu) - buggy host service!\n",
107 sizeof(VBOXGUESTCTRLHOSTCALLBACK), cbData), VERR_INVALID_PARAMETER);
108 PVBOXGUESTCTRLHOSTCALLBACK pSvcCb = (PVBOXGUESTCTRLHOSTCALLBACK)pvData;
109 AssertPtrReturn(pSvcCb, VERR_INVALID_POINTER);
110
111 /*
112 * For guest control 2.0 using the legacy commands we need to do the following here:
113 * - Get the callback header to access the context ID
114 * - Get the context ID of the callback
115 * - Extract the session ID out of the context ID
116 * - Dispatch the whole stuff to the appropriate session (if still exists)
117 *
118 * At least context ID parameter must always be present.
119 */
120 ASSERT_GUEST_RETURN(pSvcCb->mParms > 0, VERR_WRONG_PARAMETER_COUNT);
121 ASSERT_GUEST_MSG_RETURN(pSvcCb->mpaParms[0].type == VBOX_HGCM_SVC_PARM_32BIT,
122 ("type=%d\n", pSvcCb->mpaParms[0].type), VERR_WRONG_PARAMETER_TYPE);
123 uint32_t const idContext = pSvcCb->mpaParms[0].u.uint32;
124
125 VBOXGUESTCTRLHOSTCBCTX CtxCb = { idFunction, idContext };
126 int rc = pGuest->i_dispatchToSession(&CtxCb, pSvcCb);
127
128 Log2Func(("CID=%#x, idSession=%RU32, uObject=%RU32, uCount=%RU32, rc=%Rrc\n",
129 idContext, VBOX_GUESTCTRL_CONTEXTID_GET_SESSION(idContext), VBOX_GUESTCTRL_CONTEXTID_GET_OBJECT(idContext),
130 VBOX_GUESTCTRL_CONTEXTID_GET_COUNT(idContext), rc));
131 return rc;
132}
133
134// private methods
135/////////////////////////////////////////////////////////////////////////////
136
137int Guest::i_dispatchToSession(PVBOXGUESTCTRLHOSTCBCTX pCtxCb, PVBOXGUESTCTRLHOSTCALLBACK pSvcCb)
138{
139 LogFlowFunc(("pCtxCb=%p, pSvcCb=%p\n", pCtxCb, pSvcCb));
140
141 AssertPtrReturn(pCtxCb, VERR_INVALID_POINTER);
142 AssertPtrReturn(pSvcCb, VERR_INVALID_POINTER);
143
144 Log2Func(("uFunction=%RU32, uContextID=%RU32, uProtocol=%RU32\n", pCtxCb->uFunction, pCtxCb->uContextID, pCtxCb->uProtocol));
145
146 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
147
148 const uint32_t uSessionID = VBOX_GUESTCTRL_CONTEXTID_GET_SESSION(pCtxCb->uContextID);
149
150 Log2Func(("uSessionID=%RU32 (%zu total)\n", uSessionID, mData.mGuestSessions.size()));
151
152 GuestSessions::const_iterator itSession = mData.mGuestSessions.find(uSessionID);
153
154 int rc;
155 if (itSession != mData.mGuestSessions.end())
156 {
157 ComObjPtr<GuestSession> pSession(itSession->second);
158 Assert(!pSession.isNull());
159
160 alock.release();
161
162 bool fDispatch = true;
163#ifdef DEBUG
164 /*
165 * Pre-check: If we got a status message with an error and VERR_TOO_MUCH_DATA
166 * it means that that guest could not handle the entire message
167 * because of its exceeding size. This should not happen on daily
168 * use but testcases might try this. It then makes no sense to dispatch
169 * this further because we don't have a valid context ID.
170 */
171 if ( pCtxCb->uFunction == GUEST_EXEC_STATUS
172 && pSvcCb->mParms >= 5)
173 {
174 CALLBACKDATA_PROC_STATUS dataCb;
175 /* pSvcCb->mpaParms[0] always contains the context ID. */
176 HGCMSvcGetU32(&pSvcCb->mpaParms[1], &dataCb.uPID);
177 HGCMSvcGetU32(&pSvcCb->mpaParms[2], &dataCb.uStatus);
178 HGCMSvcGetU32(&pSvcCb->mpaParms[3], &dataCb.uFlags);
179 HGCMSvcGetPv(&pSvcCb->mpaParms[4], &dataCb.pvData, &dataCb.cbData);
180
181 if ( ( dataCb.uStatus == PROC_STS_ERROR)
182 /** @todo Note: Due to legacy reasons we cannot change uFlags to
183 * int32_t, so just cast it for now. */
184 && ((int32_t)dataCb.uFlags == VERR_TOO_MUCH_DATA))
185 {
186 LogFlowFunc(("Requested command with too much data, skipping dispatching ...\n"));
187
188 Assert(dataCb.uPID == 0);
189 fDispatch = false;
190 }
191 }
192#endif
193 if (fDispatch)
194 {
195 switch (pCtxCb->uFunction)
196 {
197 case GUEST_DISCONNECTED:
198 rc = pSession->i_dispatchToThis(pCtxCb, pSvcCb);
199 break;
200
201 /* Process stuff. */
202 case GUEST_EXEC_STATUS:
203 case GUEST_EXEC_OUTPUT:
204 case GUEST_EXEC_INPUT_STATUS:
205 case GUEST_EXEC_IO_NOTIFY:
206 rc = pSession->i_dispatchToObject(pCtxCb, pSvcCb);
207 break;
208
209 /* File stuff. */
210 case GUEST_FILE_NOTIFY:
211 rc = pSession->i_dispatchToObject(pCtxCb, pSvcCb);
212 break;
213
214 /* Session stuff. */
215 case GUEST_SESSION_NOTIFY:
216 rc = pSession->i_dispatchToThis(pCtxCb, pSvcCb);
217 break;
218
219 default:
220 rc = pSession->i_dispatchToObject(pCtxCb, pSvcCb);
221 break;
222 }
223 }
224 else
225 rc = VERR_INVALID_FUNCTION;
226 }
227 else
228 rc = VERR_INVALID_SESSION_ID;
229
230 LogFlowFuncLeaveRC(rc);
231 return rc;
232}
233
234int Guest::i_sessionRemove(uint32_t uSessionID)
235{
236 LogFlowThisFuncEnter();
237
238 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
239
240 int rc = VERR_NOT_FOUND;
241
242 LogFlowThisFunc(("Removing session (ID=%RU32) ...\n", uSessionID));
243
244 GuestSessions::iterator itSessions = mData.mGuestSessions.find(uSessionID);
245 if (itSessions == mData.mGuestSessions.end())
246 return VERR_NOT_FOUND;
247
248 /* Make sure to consume the pointer before the one of the
249 * iterator gets released. */
250 ComObjPtr<GuestSession> pSession = itSessions->second;
251
252 LogFlowThisFunc(("Removing session %RU32 (now total %ld sessions)\n",
253 uSessionID, mData.mGuestSessions.size() ? mData.mGuestSessions.size() - 1 : 0));
254
255 rc = pSession->i_onRemove();
256 mData.mGuestSessions.erase(itSessions);
257
258 alock.release(); /* Release lock before firing off event. */
259
260 fireGuestSessionRegisteredEvent(mEventSource, pSession, false /* Unregistered */);
261 pSession.setNull();
262
263 LogFlowFuncLeaveRC(rc);
264 return rc;
265}
266
267int Guest::i_sessionCreate(const GuestSessionStartupInfo &ssInfo,
268 const GuestCredentials &guestCreds, ComObjPtr<GuestSession> &pGuestSession)
269{
270 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
271
272 int rc = VERR_MAX_PROCS_REACHED;
273 if (mData.mGuestSessions.size() >= VBOX_GUESTCTRL_MAX_SESSIONS)
274 return rc;
275
276 try
277 {
278 /* Create a new session ID and assign it. */
279 uint32_t uNewSessionID = VBOX_GUESTCTRL_SESSION_ID_BASE;
280 uint32_t uTries = 0;
281
282 for (;;)
283 {
284 /* Is the context ID already used? */
285 if (!i_sessionExists(uNewSessionID))
286 {
287 rc = VINF_SUCCESS;
288 break;
289 }
290 uNewSessionID++;
291 if (uNewSessionID >= VBOX_GUESTCTRL_MAX_SESSIONS)
292 uNewSessionID = VBOX_GUESTCTRL_SESSION_ID_BASE;
293
294 if (++uTries == VBOX_GUESTCTRL_MAX_SESSIONS)
295 break; /* Don't try too hard. */
296 }
297 if (RT_FAILURE(rc)) throw rc;
298
299 /* Create the session object. */
300 HRESULT hr = pGuestSession.createObject();
301 if (FAILED(hr)) throw VERR_COM_UNEXPECTED;
302
303 /** @todo Use an overloaded copy operator. Later. */
304 GuestSessionStartupInfo startupInfo;
305 startupInfo.mID = uNewSessionID; /* Assign new session ID. */
306 startupInfo.mName = ssInfo.mName;
307 startupInfo.mOpenFlags = ssInfo.mOpenFlags;
308 startupInfo.mOpenTimeoutMS = ssInfo.mOpenTimeoutMS;
309
310 GuestCredentials guestCredentials;
311 if (!guestCreds.mUser.isEmpty())
312 {
313 /** @todo Use an overloaded copy operator. Later. */
314 guestCredentials.mUser = guestCreds.mUser;
315 guestCredentials.mPassword = guestCreds.mPassword;
316 guestCredentials.mDomain = guestCreds.mDomain;
317 }
318 else
319 {
320 /* Internal (annonymous) session. */
321 startupInfo.mIsInternal = true;
322 }
323
324 rc = pGuestSession->init(this, startupInfo, guestCredentials);
325 if (RT_FAILURE(rc)) throw rc;
326
327 /*
328 * Add session object to our session map. This is necessary
329 * before calling openSession because the guest calls back
330 * with the creation result of this session.
331 */
332 mData.mGuestSessions[uNewSessionID] = pGuestSession;
333
334 alock.release(); /* Release lock before firing off event. */
335
336 fireGuestSessionRegisteredEvent(mEventSource, pGuestSession,
337 true /* Registered */);
338 }
339 catch (int rc2)
340 {
341 rc = rc2;
342 }
343
344 LogFlowFuncLeaveRC(rc);
345 return rc;
346}
347
348inline bool Guest::i_sessionExists(uint32_t uSessionID)
349{
350 GuestSessions::const_iterator itSessions = mData.mGuestSessions.find(uSessionID);
351 return (itSessions == mData.mGuestSessions.end()) ? false : true;
352}
353
354#endif /* VBOX_WITH_GUEST_CONTROL */
355
356
357// implementation of public methods
358/////////////////////////////////////////////////////////////////////////////
359HRESULT Guest::createSession(const com::Utf8Str &aUser, const com::Utf8Str &aPassword, const com::Utf8Str &aDomain,
360 const com::Utf8Str &aSessionName, ComPtr<IGuestSession> &aGuestSession)
361
362{
363#ifndef VBOX_WITH_GUEST_CONTROL
364 ReturnComNotImplemented();
365#else /* VBOX_WITH_GUEST_CONTROL */
366
367 AutoCaller autoCaller(this);
368 if (FAILED(autoCaller.rc())) return autoCaller.rc();
369
370 /* Do not allow anonymous sessions (with system rights) with public API. */
371 if (RT_UNLIKELY(!aUser.length()))
372 return setError(E_INVALIDARG, tr("No user name specified"));
373
374 LogFlowFuncEnter();
375
376 GuestSessionStartupInfo startupInfo;
377 startupInfo.mName = aSessionName;
378
379 GuestCredentials guestCreds;
380 guestCreds.mUser = aUser;
381 guestCreds.mPassword = aPassword;
382 guestCreds.mDomain = aDomain;
383
384 ComObjPtr<GuestSession> pSession;
385 int vrc = i_sessionCreate(startupInfo, guestCreds, pSession);
386 if (RT_SUCCESS(vrc))
387 {
388 /* Return guest session to the caller. */
389 HRESULT hr2 = pSession.queryInterfaceTo(aGuestSession.asOutParam());
390 if (FAILED(hr2))
391 vrc = VERR_COM_OBJECT_NOT_FOUND;
392 }
393
394 if (RT_SUCCESS(vrc))
395 /* Start (fork) the session asynchronously
396 * on the guest. */
397 vrc = pSession->i_startSessionAsync();
398
399 HRESULT hr = S_OK;
400
401 if (RT_FAILURE(vrc))
402 {
403 switch (vrc)
404 {
405 case VERR_MAX_PROCS_REACHED:
406 hr = setErrorBoth(VBOX_E_MAXIMUM_REACHED, vrc, tr("Maximum number of concurrent guest sessions (%d) reached"),
407 VBOX_GUESTCTRL_MAX_SESSIONS);
408 break;
409
410 /** @todo Add more errors here. */
411
412 default:
413 hr = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("Could not create guest session: %Rrc"), vrc);
414 break;
415 }
416 }
417
418 LogFlowThisFunc(("Returning rc=%Rhrc\n", hr));
419 return hr;
420#endif /* VBOX_WITH_GUEST_CONTROL */
421}
422
423HRESULT Guest::findSession(const com::Utf8Str &aSessionName, std::vector<ComPtr<IGuestSession> > &aSessions)
424{
425#ifndef VBOX_WITH_GUEST_CONTROL
426 ReturnComNotImplemented();
427#else /* VBOX_WITH_GUEST_CONTROL */
428
429 LogFlowFuncEnter();
430
431 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
432
433 Utf8Str strName(aSessionName);
434 std::list < ComObjPtr<GuestSession> > listSessions;
435
436 GuestSessions::const_iterator itSessions = mData.mGuestSessions.begin();
437 while (itSessions != mData.mGuestSessions.end())
438 {
439 if (strName.contains(itSessions->second->i_getName())) /** @todo Use a (simple) pattern match (IPRT?). */
440 listSessions.push_back(itSessions->second);
441 ++itSessions;
442 }
443
444 LogFlowFunc(("Sessions with \"%s\" = %RU32\n",
445 aSessionName.c_str(), listSessions.size()));
446
447 aSessions.resize(listSessions.size());
448 if (!listSessions.empty())
449 {
450 size_t i = 0;
451 for (std::list < ComObjPtr<GuestSession> >::const_iterator it = listSessions.begin(); it != listSessions.end(); ++it, ++i)
452 (*it).queryInterfaceTo(aSessions[i].asOutParam());
453
454 return S_OK;
455
456 }
457
458 return setErrorNoLog(VBOX_E_OBJECT_NOT_FOUND,
459 tr("Could not find sessions with name '%s'"),
460 aSessionName.c_str());
461#endif /* VBOX_WITH_GUEST_CONTROL */
462}
463
464HRESULT Guest::updateGuestAdditions(const com::Utf8Str &aSource, const std::vector<com::Utf8Str> &aArguments,
465 const std::vector<AdditionsUpdateFlag_T> &aFlags, ComPtr<IProgress> &aProgress)
466{
467#ifndef VBOX_WITH_GUEST_CONTROL
468 ReturnComNotImplemented();
469#else /* VBOX_WITH_GUEST_CONTROL */
470
471 /* Validate flags. */
472 uint32_t fFlags = AdditionsUpdateFlag_None;
473 if (aFlags.size())
474 for (size_t i = 0; i < aFlags.size(); ++i)
475 fFlags |= aFlags[i];
476
477 if (fFlags && !(fFlags & AdditionsUpdateFlag_WaitForUpdateStartOnly))
478 return setError(E_INVALIDARG, tr("Unknown flags (%#x)"), fFlags);
479
480 int vrc = VINF_SUCCESS;
481
482 ProcessArguments aArgs;
483 aArgs.resize(0);
484
485 if (aArguments.size())
486 {
487 try
488 {
489 for (size_t i = 0; i < aArguments.size(); ++i)
490 aArgs.push_back(aArguments[i]);
491 }
492 catch(std::bad_alloc &)
493 {
494 vrc = VERR_NO_MEMORY;
495 }
496 }
497
498 HRESULT hr = S_OK;
499
500 /*
501 * Create an anonymous session. This is required to run the Guest Additions
502 * update process with administrative rights.
503 */
504 GuestSessionStartupInfo startupInfo;
505 startupInfo.mName = "Updating Guest Additions";
506
507 GuestCredentials guestCreds;
508 RT_ZERO(guestCreds);
509
510 ComObjPtr<GuestSession> pSession;
511 if (RT_SUCCESS(vrc))
512 vrc = i_sessionCreate(startupInfo, guestCreds, pSession);
513 if (RT_FAILURE(vrc))
514 {
515 switch (vrc)
516 {
517 case VERR_MAX_PROCS_REACHED:
518 hr = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("Maximum number of concurrent guest sessions (%d) reached"),
519 VBOX_GUESTCTRL_MAX_SESSIONS);
520 break;
521
522 /** @todo Add more errors here. */
523
524 default:
525 hr = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("Could not create guest session: %Rrc"), vrc);
526 break;
527 }
528 }
529 else
530 {
531 Assert(!pSession.isNull());
532 int rcGuest;
533 vrc = pSession->i_startSession(&rcGuest);
534 if (RT_FAILURE(vrc))
535 {
536 /** @todo Handle rcGuest! */
537
538 hr = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("Could not open guest session: %Rrc"), vrc);
539 }
540 else
541 {
542
543 ComObjPtr<Progress> pProgress;
544 GuestSessionTaskUpdateAdditions *pTask = NULL;
545 try
546 {
547 try
548 {
549 pTask = new GuestSessionTaskUpdateAdditions(pSession /* GuestSession */, aSource, aArgs, fFlags);
550 }
551 catch(...)
552 {
553 hr = setError(E_OUTOFMEMORY, tr("Failed to create SessionTaskUpdateAdditions object "));
554 throw;
555 }
556
557
558 hr = pTask->Init(Utf8StrFmt(tr("Updating Guest Additions")));
559 if (FAILED(hr))
560 {
561 delete pTask;
562 hr = setError(hr, tr("Creating progress object for SessionTaskUpdateAdditions object failed"));
563 throw hr;
564 }
565
566 hr = pTask->createThreadWithType(RTTHREADTYPE_MAIN_HEAVY_WORKER);
567
568 if (SUCCEEDED(hr))
569 {
570 /* Return progress to the caller. */
571 pProgress = pTask->GetProgressObject();
572 hr = pProgress.queryInterfaceTo(aProgress.asOutParam());
573 }
574 else
575 hr = setError(hr, tr("Starting thread for updating Guest Additions on the guest failed "));
576 }
577 catch(std::bad_alloc &)
578 {
579 hr = E_OUTOFMEMORY;
580 }
581 catch(...)
582 {
583 LogFlowThisFunc(("Exception was caught in the function\n"));
584 }
585 }
586 }
587
588 LogFlowFunc(("Returning hr=%Rhrc\n", hr));
589 return hr;
590#endif /* VBOX_WITH_GUEST_CONTROL */
591}
592
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