VirtualBox

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

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

scm --update-copyright-year

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