VirtualBox

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

Last change on this file since 71524 was 71406, checked in by vboxsync, 7 years ago

Guest Control: Revamped internal object [un]registration and organization to provide faster lookups and avoid code duplication. No protocol changes.

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