VirtualBox

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

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

Main/Guest: Added a few codereview comments, mainly in the guest base class area. Replaced the object ID management in GuestSession with a classic allocation bitmap approach as that's much less memory intensive than 16 byte structs in a insert-only std::map and an additional map tracking free 32-bit IDs after we run out. bugref:9313 [build fix]

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 19.5 KB
Line 
1/* $Id: GuestCtrlImpl.cpp 75862 2018-12-02 00:33:01Z 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.215389.xyz. 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#ifdef DEBUG
163 /*
164 * Pre-check: If we got a status message with an error and VERR_TOO_MUCH_DATA
165 * it means that that guest could not handle the entire message
166 * because of its exceeding size. This should not happen on daily
167 * use but testcases might try this. It then makes no sense to dispatch
168 * this further because we don't have a valid context ID.
169 */
170 bool fDispatch = true;
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 && (int32_t)dataCb.uFlags == VERR_TOO_MUCH_DATA)
183 {
184 LogFlowFunc(("Requested command with too much data, skipping dispatching ...\n"));
185 Assert(dataCb.uPID == 0);
186 fDispatch = false;
187 rc = VINF_SUCCESS;
188 }
189 }
190 if (fDispatch)
191#endif
192 {
193 switch (pCtxCb->uFunction)
194 {
195 case GUEST_DISCONNECTED:
196 rc = pSession->i_dispatchToThis(pCtxCb, pSvcCb);
197 break;
198
199 /* Process stuff. */
200 case GUEST_EXEC_STATUS:
201 case GUEST_EXEC_OUTPUT:
202 case GUEST_EXEC_INPUT_STATUS:
203 case GUEST_EXEC_IO_NOTIFY:
204 rc = pSession->i_dispatchToObject(pCtxCb, pSvcCb);
205 break;
206
207 /* File stuff. */
208 case GUEST_FILE_NOTIFY:
209 rc = pSession->i_dispatchToObject(pCtxCb, pSvcCb);
210 break;
211
212 /* Session stuff. */
213 case GUEST_SESSION_NOTIFY:
214 rc = pSession->i_dispatchToThis(pCtxCb, pSvcCb);
215 break;
216
217 default:
218 rc = pSession->i_dispatchToObject(pCtxCb, pSvcCb);
219 break;
220 }
221 }
222 else
223 rc = VERR_INVALID_FUNCTION;
224 }
225 else
226 rc = VERR_INVALID_SESSION_ID;
227
228 LogFlowFuncLeaveRC(rc);
229 return rc;
230}
231
232int Guest::i_sessionRemove(uint32_t uSessionID)
233{
234 LogFlowThisFuncEnter();
235
236 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
237
238 int rc = VERR_NOT_FOUND;
239
240 LogFlowThisFunc(("Removing session (ID=%RU32) ...\n", uSessionID));
241
242 GuestSessions::iterator itSessions = mData.mGuestSessions.find(uSessionID);
243 if (itSessions == mData.mGuestSessions.end())
244 return VERR_NOT_FOUND;
245
246 /* Make sure to consume the pointer before the one of the
247 * iterator gets released. */
248 ComObjPtr<GuestSession> pSession = itSessions->second;
249
250 LogFlowThisFunc(("Removing session %RU32 (now total %ld sessions)\n",
251 uSessionID, mData.mGuestSessions.size() ? mData.mGuestSessions.size() - 1 : 0));
252
253 rc = pSession->i_onRemove();
254 mData.mGuestSessions.erase(itSessions);
255
256 alock.release(); /* Release lock before firing off event. */
257
258 fireGuestSessionRegisteredEvent(mEventSource, pSession, false /* Unregistered */);
259 pSession.setNull();
260
261 LogFlowFuncLeaveRC(rc);
262 return rc;
263}
264
265int Guest::i_sessionCreate(const GuestSessionStartupInfo &ssInfo,
266 const GuestCredentials &guestCreds, ComObjPtr<GuestSession> &pGuestSession)
267{
268 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
269
270 int rc = VERR_MAX_PROCS_REACHED;
271 if (mData.mGuestSessions.size() >= VBOX_GUESTCTRL_MAX_SESSIONS)
272 return rc;
273
274 try
275 {
276 /* Create a new session ID and assign it. */
277 uint32_t uNewSessionID = VBOX_GUESTCTRL_SESSION_ID_BASE;
278 uint32_t uTries = 0;
279
280 for (;;)
281 {
282 /* Is the context ID already used? */
283 if (!i_sessionExists(uNewSessionID))
284 {
285 rc = VINF_SUCCESS;
286 break;
287 }
288 uNewSessionID++;
289 if (uNewSessionID >= VBOX_GUESTCTRL_MAX_SESSIONS)
290 uNewSessionID = VBOX_GUESTCTRL_SESSION_ID_BASE;
291
292 if (++uTries == VBOX_GUESTCTRL_MAX_SESSIONS)
293 break; /* Don't try too hard. */
294 }
295 if (RT_FAILURE(rc)) throw rc;
296
297 /* Create the session object. */
298 HRESULT hr = pGuestSession.createObject();
299 if (FAILED(hr)) throw VERR_COM_UNEXPECTED;
300
301 /** @todo Use an overloaded copy operator. Later. */
302 GuestSessionStartupInfo startupInfo;
303 startupInfo.mID = uNewSessionID; /* Assign new session ID. */
304 startupInfo.mName = ssInfo.mName;
305 startupInfo.mOpenFlags = ssInfo.mOpenFlags;
306 startupInfo.mOpenTimeoutMS = ssInfo.mOpenTimeoutMS;
307
308 GuestCredentials guestCredentials;
309 if (!guestCreds.mUser.isEmpty())
310 {
311 /** @todo Use an overloaded copy operator. Later. */
312 guestCredentials.mUser = guestCreds.mUser;
313 guestCredentials.mPassword = guestCreds.mPassword;
314 guestCredentials.mDomain = guestCreds.mDomain;
315 }
316 else
317 {
318 /* Internal (annonymous) session. */
319 startupInfo.mIsInternal = true;
320 }
321
322 rc = pGuestSession->init(this, startupInfo, guestCredentials);
323 if (RT_FAILURE(rc)) throw rc;
324
325 /*
326 * Add session object to our session map. This is necessary
327 * before calling openSession because the guest calls back
328 * with the creation result of this session.
329 */
330 mData.mGuestSessions[uNewSessionID] = pGuestSession;
331
332 alock.release(); /* Release lock before firing off event. */
333
334 fireGuestSessionRegisteredEvent(mEventSource, pGuestSession,
335 true /* Registered */);
336 }
337 catch (int rc2)
338 {
339 rc = rc2;
340 }
341
342 LogFlowFuncLeaveRC(rc);
343 return rc;
344}
345
346inline bool Guest::i_sessionExists(uint32_t uSessionID)
347{
348 GuestSessions::const_iterator itSessions = mData.mGuestSessions.find(uSessionID);
349 return (itSessions == mData.mGuestSessions.end()) ? false : true;
350}
351
352#endif /* VBOX_WITH_GUEST_CONTROL */
353
354
355// implementation of public methods
356/////////////////////////////////////////////////////////////////////////////
357HRESULT Guest::createSession(const com::Utf8Str &aUser, const com::Utf8Str &aPassword, const com::Utf8Str &aDomain,
358 const com::Utf8Str &aSessionName, ComPtr<IGuestSession> &aGuestSession)
359
360{
361#ifndef VBOX_WITH_GUEST_CONTROL
362 ReturnComNotImplemented();
363#else /* VBOX_WITH_GUEST_CONTROL */
364
365 AutoCaller autoCaller(this);
366 if (FAILED(autoCaller.rc())) return autoCaller.rc();
367
368 /* Do not allow anonymous sessions (with system rights) with public API. */
369 if (RT_UNLIKELY(!aUser.length()))
370 return setError(E_INVALIDARG, tr("No user name specified"));
371
372 LogFlowFuncEnter();
373
374 GuestSessionStartupInfo startupInfo;
375 startupInfo.mName = aSessionName;
376
377 GuestCredentials guestCreds;
378 guestCreds.mUser = aUser;
379 guestCreds.mPassword = aPassword;
380 guestCreds.mDomain = aDomain;
381
382 ComObjPtr<GuestSession> pSession;
383 int vrc = i_sessionCreate(startupInfo, guestCreds, pSession);
384 if (RT_SUCCESS(vrc))
385 {
386 /* Return guest session to the caller. */
387 HRESULT hr2 = pSession.queryInterfaceTo(aGuestSession.asOutParam());
388 if (FAILED(hr2))
389 vrc = VERR_COM_OBJECT_NOT_FOUND;
390 }
391
392 if (RT_SUCCESS(vrc))
393 /* Start (fork) the session asynchronously
394 * on the guest. */
395 vrc = pSession->i_startSessionAsync();
396
397 HRESULT hr = S_OK;
398
399 if (RT_FAILURE(vrc))
400 {
401 switch (vrc)
402 {
403 case VERR_MAX_PROCS_REACHED:
404 hr = setErrorBoth(VBOX_E_MAXIMUM_REACHED, vrc, tr("Maximum number of concurrent guest sessions (%d) reached"),
405 VBOX_GUESTCTRL_MAX_SESSIONS);
406 break;
407
408 /** @todo Add more errors here. */
409
410 default:
411 hr = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("Could not create guest session: %Rrc"), vrc);
412 break;
413 }
414 }
415
416 LogFlowThisFunc(("Returning rc=%Rhrc\n", hr));
417 return hr;
418#endif /* VBOX_WITH_GUEST_CONTROL */
419}
420
421HRESULT Guest::findSession(const com::Utf8Str &aSessionName, std::vector<ComPtr<IGuestSession> > &aSessions)
422{
423#ifndef VBOX_WITH_GUEST_CONTROL
424 ReturnComNotImplemented();
425#else /* VBOX_WITH_GUEST_CONTROL */
426
427 LogFlowFuncEnter();
428
429 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
430
431 Utf8Str strName(aSessionName);
432 std::list < ComObjPtr<GuestSession> > listSessions;
433
434 GuestSessions::const_iterator itSessions = mData.mGuestSessions.begin();
435 while (itSessions != mData.mGuestSessions.end())
436 {
437 if (strName.contains(itSessions->second->i_getName())) /** @todo Use a (simple) pattern match (IPRT?). */
438 listSessions.push_back(itSessions->second);
439 ++itSessions;
440 }
441
442 LogFlowFunc(("Sessions with \"%s\" = %RU32\n",
443 aSessionName.c_str(), listSessions.size()));
444
445 aSessions.resize(listSessions.size());
446 if (!listSessions.empty())
447 {
448 size_t i = 0;
449 for (std::list < ComObjPtr<GuestSession> >::const_iterator it = listSessions.begin(); it != listSessions.end(); ++it, ++i)
450 (*it).queryInterfaceTo(aSessions[i].asOutParam());
451
452 return S_OK;
453
454 }
455
456 return setErrorNoLog(VBOX_E_OBJECT_NOT_FOUND,
457 tr("Could not find sessions with name '%s'"),
458 aSessionName.c_str());
459#endif /* VBOX_WITH_GUEST_CONTROL */
460}
461
462HRESULT Guest::updateGuestAdditions(const com::Utf8Str &aSource, const std::vector<com::Utf8Str> &aArguments,
463 const std::vector<AdditionsUpdateFlag_T> &aFlags, ComPtr<IProgress> &aProgress)
464{
465#ifndef VBOX_WITH_GUEST_CONTROL
466 ReturnComNotImplemented();
467#else /* VBOX_WITH_GUEST_CONTROL */
468
469 /* Validate flags. */
470 uint32_t fFlags = AdditionsUpdateFlag_None;
471 if (aFlags.size())
472 for (size_t i = 0; i < aFlags.size(); ++i)
473 fFlags |= aFlags[i];
474
475 if (fFlags && !(fFlags & AdditionsUpdateFlag_WaitForUpdateStartOnly))
476 return setError(E_INVALIDARG, tr("Unknown flags (%#x)"), fFlags);
477
478 int vrc = VINF_SUCCESS;
479
480 ProcessArguments aArgs;
481 aArgs.resize(0);
482
483 if (aArguments.size())
484 {
485 try
486 {
487 for (size_t i = 0; i < aArguments.size(); ++i)
488 aArgs.push_back(aArguments[i]);
489 }
490 catch(std::bad_alloc &)
491 {
492 vrc = VERR_NO_MEMORY;
493 }
494 }
495
496 HRESULT hr = S_OK;
497
498 /*
499 * Create an anonymous session. This is required to run the Guest Additions
500 * update process with administrative rights.
501 */
502 GuestSessionStartupInfo startupInfo;
503 startupInfo.mName = "Updating Guest Additions";
504
505 GuestCredentials guestCreds;
506 RT_ZERO(guestCreds);
507
508 ComObjPtr<GuestSession> pSession;
509 if (RT_SUCCESS(vrc))
510 vrc = i_sessionCreate(startupInfo, guestCreds, pSession);
511 if (RT_FAILURE(vrc))
512 {
513 switch (vrc)
514 {
515 case VERR_MAX_PROCS_REACHED:
516 hr = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("Maximum number of concurrent guest sessions (%d) reached"),
517 VBOX_GUESTCTRL_MAX_SESSIONS);
518 break;
519
520 /** @todo Add more errors here. */
521
522 default:
523 hr = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("Could not create guest session: %Rrc"), vrc);
524 break;
525 }
526 }
527 else
528 {
529 Assert(!pSession.isNull());
530 int rcGuest;
531 vrc = pSession->i_startSession(&rcGuest);
532 if (RT_FAILURE(vrc))
533 {
534 /** @todo Handle rcGuest! */
535
536 hr = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("Could not open guest session: %Rrc"), vrc);
537 }
538 else
539 {
540
541 ComObjPtr<Progress> pProgress;
542 GuestSessionTaskUpdateAdditions *pTask = NULL;
543 try
544 {
545 try
546 {
547 pTask = new GuestSessionTaskUpdateAdditions(pSession /* GuestSession */, aSource, aArgs, fFlags);
548 }
549 catch(...)
550 {
551 hr = setError(E_OUTOFMEMORY, tr("Failed to create SessionTaskUpdateAdditions object "));
552 throw;
553 }
554
555
556 hr = pTask->Init(Utf8StrFmt(tr("Updating Guest Additions")));
557 if (FAILED(hr))
558 {
559 delete pTask;
560 hr = setError(hr, tr("Creating progress object for SessionTaskUpdateAdditions object failed"));
561 throw hr;
562 }
563
564 hr = pTask->createThreadWithType(RTTHREADTYPE_MAIN_HEAVY_WORKER);
565
566 if (SUCCEEDED(hr))
567 {
568 /* Return progress to the caller. */
569 pProgress = pTask->GetProgressObject();
570 hr = pProgress.queryInterfaceTo(aProgress.asOutParam());
571 }
572 else
573 hr = setError(hr, tr("Starting thread for updating Guest Additions on the guest failed "));
574 }
575 catch(std::bad_alloc &)
576 {
577 hr = E_OUTOFMEMORY;
578 }
579 catch(...)
580 {
581 LogFlowThisFunc(("Exception was caught in the function\n"));
582 }
583 }
584 }
585
586 LogFlowFunc(("Returning hr=%Rhrc\n", hr));
587 return hr;
588#endif /* VBOX_WITH_GUEST_CONTROL */
589}
590
Note: See TracBrowser for help on using the repository browser.

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