VirtualBox

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

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

Guest Control/Main: Added more AutoCaller checks for public APIs.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 19.2 KB
Line 
1/* $Id: GuestCtrlImpl.cpp 71560 2018-03-29 11:00:30Z 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 AutoCaller autoCaller(this);
375 if (FAILED(autoCaller.rc())) return autoCaller.rc();
376
377 /* Do not allow anonymous sessions (with system rights) with public API. */
378 if (RT_UNLIKELY(!aUser.length()))
379 return setError(E_INVALIDARG, tr("No user name specified"));
380
381 LogFlowFuncEnter();
382
383 GuestSessionStartupInfo startupInfo;
384 startupInfo.mName = aSessionName;
385
386 GuestCredentials guestCreds;
387 guestCreds.mUser = aUser;
388 guestCreds.mPassword = aPassword;
389 guestCreds.mDomain = aDomain;
390
391 ComObjPtr<GuestSession> pSession;
392 int rc = i_sessionCreate(startupInfo, guestCreds, pSession);
393 if (RT_SUCCESS(rc))
394 {
395 /* Return guest session to the caller. */
396 HRESULT hr2 = pSession.queryInterfaceTo(aGuestSession.asOutParam());
397 if (FAILED(hr2))
398 rc = VERR_COM_OBJECT_NOT_FOUND;
399 }
400
401 if (RT_SUCCESS(rc))
402 /* Start (fork) the session asynchronously
403 * on the guest. */
404 rc = pSession->i_startSessionAsync();
405
406 HRESULT hr = S_OK;
407
408 if (RT_FAILURE(rc))
409 {
410 switch (rc)
411 {
412 case VERR_MAX_PROCS_REACHED:
413 hr = setError(VBOX_E_MAXIMUM_REACHED, tr("Maximum number of concurrent guest sessions (%ld) reached"),
414 VBOX_GUESTCTRL_MAX_SESSIONS);
415 break;
416
417 /** @todo Add more errors here. */
418
419 default:
420 hr = setError(VBOX_E_IPRT_ERROR, tr("Could not create guest session: %Rrc"), rc);
421 break;
422 }
423 }
424
425 LogFlowThisFunc(("Returning rc=%Rhrc\n", hr));
426 return hr;
427#endif /* VBOX_WITH_GUEST_CONTROL */
428}
429
430HRESULT Guest::findSession(const com::Utf8Str &aSessionName, std::vector<ComPtr<IGuestSession> > &aSessions)
431{
432#ifndef VBOX_WITH_GUEST_CONTROL
433 ReturnComNotImplemented();
434#else /* VBOX_WITH_GUEST_CONTROL */
435
436 LogFlowFuncEnter();
437
438 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
439
440 Utf8Str strName(aSessionName);
441 std::list < ComObjPtr<GuestSession> > listSessions;
442
443 GuestSessions::const_iterator itSessions = mData.mGuestSessions.begin();
444 while (itSessions != mData.mGuestSessions.end())
445 {
446 if (strName.contains(itSessions->second->i_getName())) /** @todo Use a (simple) pattern match (IPRT?). */
447 listSessions.push_back(itSessions->second);
448 ++itSessions;
449 }
450
451 LogFlowFunc(("Sessions with \"%s\" = %RU32\n",
452 aSessionName.c_str(), listSessions.size()));
453
454 aSessions.resize(listSessions.size());
455 if (!listSessions.empty())
456 {
457 size_t i = 0;
458 for (std::list < ComObjPtr<GuestSession> >::const_iterator it = listSessions.begin(); it != listSessions.end(); ++it, ++i)
459 (*it).queryInterfaceTo(aSessions[i].asOutParam());
460
461 return S_OK;
462
463 }
464
465 return setErrorNoLog(VBOX_E_OBJECT_NOT_FOUND,
466 tr("Could not find sessions with name '%s'"),
467 aSessionName.c_str());
468#endif /* VBOX_WITH_GUEST_CONTROL */
469}
470
471HRESULT Guest::updateGuestAdditions(const com::Utf8Str &aSource, const std::vector<com::Utf8Str> &aArguments,
472 const std::vector<AdditionsUpdateFlag_T> &aFlags, ComPtr<IProgress> &aProgress)
473{
474#ifndef VBOX_WITH_GUEST_CONTROL
475 ReturnComNotImplemented();
476#else /* VBOX_WITH_GUEST_CONTROL */
477
478 /* Validate flags. */
479 uint32_t fFlags = AdditionsUpdateFlag_None;
480 if (aFlags.size())
481 for (size_t i = 0; i < aFlags.size(); ++i)
482 fFlags |= aFlags[i];
483
484 if (fFlags && !(fFlags & AdditionsUpdateFlag_WaitForUpdateStartOnly))
485 return setError(E_INVALIDARG, tr("Unknown flags (%#x)"), fFlags);
486
487 int rc = VINF_SUCCESS;
488
489 ProcessArguments aArgs;
490 aArgs.resize(0);
491
492 if (aArguments.size())
493 {
494 try
495 {
496 for (size_t i = 0; i < aArguments.size(); ++i)
497 aArgs.push_back(aArguments[i]);
498 }
499 catch(std::bad_alloc &)
500 {
501 rc = VERR_NO_MEMORY;
502 }
503 }
504
505 HRESULT hr = S_OK;
506
507 /*
508 * Create an anonymous session. This is required to run the Guest Additions
509 * update process with administrative rights.
510 */
511 GuestSessionStartupInfo startupInfo;
512 startupInfo.mName = "Updating Guest Additions";
513
514 GuestCredentials guestCreds;
515 RT_ZERO(guestCreds);
516
517 ComObjPtr<GuestSession> pSession;
518 if (RT_SUCCESS(rc))
519 rc = i_sessionCreate(startupInfo, guestCreds, pSession);
520 if (RT_FAILURE(rc))
521 {
522 switch (rc)
523 {
524 case VERR_MAX_PROCS_REACHED:
525 hr = setError(VBOX_E_IPRT_ERROR, tr("Maximum number of concurrent guest sessions (%ld) reached"),
526 VBOX_GUESTCTRL_MAX_SESSIONS);
527 break;
528
529 /** @todo Add more errors here. */
530
531 default:
532 hr = setError(VBOX_E_IPRT_ERROR, tr("Could not create guest session: %Rrc"), rc);
533 break;
534 }
535 }
536 else
537 {
538 Assert(!pSession.isNull());
539 int rcGuest;
540 rc = pSession->i_startSession(&rcGuest);
541 if (RT_FAILURE(rc))
542 {
543 /** @todo Handle rcGuest! */
544
545 hr = setError(VBOX_E_IPRT_ERROR, tr("Could not open guest session: %Rrc"), rc);
546 }
547 else
548 {
549
550 ComObjPtr<Progress> pProgress;
551 SessionTaskUpdateAdditions *pTask = NULL;
552 try
553 {
554 try
555 {
556 pTask = new SessionTaskUpdateAdditions(pSession /* GuestSession */, aSource, aArgs, fFlags);
557 }
558 catch(...)
559 {
560 hr = setError(VBOX_E_IPRT_ERROR, tr("Failed to create SessionTaskUpdateAdditions object "));
561 throw;
562 }
563
564
565 hr = pTask->Init(Utf8StrFmt(tr("Updating Guest Additions")));
566 if (FAILED(hr))
567 {
568 delete pTask;
569 hr = setError(VBOX_E_IPRT_ERROR,
570 tr("Creating progress object for SessionTaskUpdateAdditions object failed"));
571 throw hr;
572 }
573
574 hr = pTask->createThreadWithType(RTTHREADTYPE_MAIN_HEAVY_WORKER);
575
576 if (SUCCEEDED(hr))
577 {
578 /* Return progress to the caller. */
579 pProgress = pTask->GetProgressObject();
580 hr = pProgress.queryInterfaceTo(aProgress.asOutParam());
581 }
582 else
583 hr = setError(VBOX_E_IPRT_ERROR,
584 tr("Starting thread for updating Guest Additions on the guest failed "));
585 }
586 catch(std::bad_alloc &)
587 {
588 hr = E_OUTOFMEMORY;
589 }
590 catch(...)
591 {
592 LogFlowThisFunc(("Exception was caught in the function\n"));
593 }
594 }
595 }
596
597 LogFlowFunc(("Returning hr=%Rhrc\n", hr));
598 return hr;
599#endif /* VBOX_WITH_GUEST_CONTROL */
600}
601
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