VirtualBox

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

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

Main/Guest::updateGuestAdditions: Cleanup similar to r130830. bugref:9320

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 20.3 KB
Line 
1/* $Id: GuestCtrlImpl.cpp 78744 2019-05-25 14:21:47Z 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 messages
64 * from the guest. Acts as a dispatcher for the actual class instance.
65 *
66 * @returns VBox status code.
67 * @param pvExtension Pointer to HGCM service extension.
68 * @param idMessage HGCM message ID the callback was called for.
69 * @param pvData Pointer to user-supplied callback data.
70 * @param cbData Size (in bytes) of user-supplied callback data.
71 */
72/* static */
73DECLCALLBACK(int) Guest::i_notifyCtrlDispatcher(void *pvExtension,
74 uint32_t idMessage,
75 void *pvData,
76 uint32_t cbData)
77{
78 using namespace guestControl;
79
80 /*
81 * No locking, as this is purely a notification which does not make any
82 * changes to the object state.
83 */
84 Log2Func(("pvExtension=%p, idMessage=%RU32, pvParms=%p, cbParms=%RU32\n", pvExtension, idMessage, pvData, cbData));
85
86 ComObjPtr<Guest> pGuest = reinterpret_cast<Guest *>(pvExtension);
87 AssertReturn(pGuest.isNotNull(), VERR_WRONG_ORDER);
88
89 /*
90 * The data packet should ever be a problem, but check to be sure.
91 */
92 AssertMsgReturn(cbData == sizeof(VBOXGUESTCTRLHOSTCALLBACK),
93 ("Guest control host callback data has wrong size (expected %zu, got %zu) - buggy host service!\n",
94 sizeof(VBOXGUESTCTRLHOSTCALLBACK), cbData), VERR_INVALID_PARAMETER);
95 PVBOXGUESTCTRLHOSTCALLBACK pSvcCb = (PVBOXGUESTCTRLHOSTCALLBACK)pvData;
96 AssertPtrReturn(pSvcCb, VERR_INVALID_POINTER);
97
98 /*
99 * For guest control 2.0 using the legacy messages we need to do the following here:
100 * - Get the callback header to access the context ID
101 * - Get the context ID of the callback
102 * - Extract the session ID out of the context ID
103 * - Dispatch the whole stuff to the appropriate session (if still exists)
104 *
105 * At least context ID parameter must always be present.
106 */
107 ASSERT_GUEST_RETURN(pSvcCb->mParms > 0, VERR_WRONG_PARAMETER_COUNT);
108 ASSERT_GUEST_MSG_RETURN(pSvcCb->mpaParms[0].type == VBOX_HGCM_SVC_PARM_32BIT,
109 ("type=%d\n", pSvcCb->mpaParms[0].type), VERR_WRONG_PARAMETER_TYPE);
110 uint32_t const idContext = pSvcCb->mpaParms[0].u.uint32;
111
112 VBOXGUESTCTRLHOSTCBCTX CtxCb = { idMessage, idContext };
113 int rc = pGuest->i_dispatchToSession(&CtxCb, pSvcCb);
114
115 Log2Func(("CID=%#x, idSession=%RU32, uObject=%RU32, uCount=%RU32, rc=%Rrc\n",
116 idContext, VBOX_GUESTCTRL_CONTEXTID_GET_SESSION(idContext), VBOX_GUESTCTRL_CONTEXTID_GET_OBJECT(idContext),
117 VBOX_GUESTCTRL_CONTEXTID_GET_COUNT(idContext), rc));
118 return rc;
119}
120
121// private methods
122/////////////////////////////////////////////////////////////////////////////
123
124/**
125 * Dispatches a host service callback to the appropriate guest control session object.
126 *
127 * @returns VBox status code.
128 * @param pCtxCb Pointer to host callback context.
129 * @param pSvcCb Pointer to callback parameters.
130 */
131int Guest::i_dispatchToSession(PVBOXGUESTCTRLHOSTCBCTX pCtxCb, PVBOXGUESTCTRLHOSTCALLBACK pSvcCb)
132{
133 LogFlowFunc(("pCtxCb=%p, pSvcCb=%p\n", pCtxCb, pSvcCb));
134
135 AssertPtrReturn(pCtxCb, VERR_INVALID_POINTER);
136 AssertPtrReturn(pSvcCb, VERR_INVALID_POINTER);
137
138 Log2Func(("uMessage=%RU32, uContextID=%RU32, uProtocol=%RU32\n", pCtxCb->uMessage, pCtxCb->uContextID, pCtxCb->uProtocol));
139
140 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
141
142 const uint32_t uSessionID = VBOX_GUESTCTRL_CONTEXTID_GET_SESSION(pCtxCb->uContextID);
143
144 Log2Func(("uSessionID=%RU32 (%zu total)\n", uSessionID, mData.mGuestSessions.size()));
145
146 GuestSessions::const_iterator itSession = mData.mGuestSessions.find(uSessionID);
147
148 int rc;
149 if (itSession != mData.mGuestSessions.end())
150 {
151 ComObjPtr<GuestSession> pSession(itSession->second);
152 Assert(!pSession.isNull());
153
154 alock.release();
155
156#ifdef DEBUG
157 /*
158 * Pre-check: If we got a status message with an error and VERR_TOO_MUCH_DATA
159 * it means that that guest could not handle the entire message
160 * because of its exceeding size. This should not happen on daily
161 * use but testcases might try this. It then makes no sense to dispatch
162 * this further because we don't have a valid context ID.
163 */
164 bool fDispatch = true;
165 rc = VERR_INVALID_FUNCTION;
166 if ( pCtxCb->uMessage == GUEST_MSG_EXEC_STATUS
167 && pSvcCb->mParms >= 5)
168 {
169 CALLBACKDATA_PROC_STATUS dataCb;
170 /* pSvcCb->mpaParms[0] always contains the context ID. */
171 HGCMSvcGetU32(&pSvcCb->mpaParms[1], &dataCb.uPID);
172 HGCMSvcGetU32(&pSvcCb->mpaParms[2], &dataCb.uStatus);
173 HGCMSvcGetU32(&pSvcCb->mpaParms[3], &dataCb.uFlags);
174 HGCMSvcGetPv(&pSvcCb->mpaParms[4], &dataCb.pvData, &dataCb.cbData);
175
176 if ( dataCb.uStatus == PROC_STS_ERROR
177 && (int32_t)dataCb.uFlags == VERR_TOO_MUCH_DATA)
178 {
179 LogFlowFunc(("Requested message with too much data, skipping dispatching ...\n"));
180 Assert(dataCb.uPID == 0);
181 fDispatch = false;
182 }
183 }
184 if (fDispatch)
185#endif
186 {
187 switch (pCtxCb->uMessage)
188 {
189 case GUEST_MSG_DISCONNECTED:
190 rc = pSession->i_dispatchToThis(pCtxCb, pSvcCb);
191 break;
192
193 /* Process stuff. */
194 case GUEST_MSG_EXEC_STATUS:
195 case GUEST_MSG_EXEC_OUTPUT:
196 case GUEST_MSG_EXEC_INPUT_STATUS:
197 case GUEST_MSG_EXEC_IO_NOTIFY:
198 rc = pSession->i_dispatchToObject(pCtxCb, pSvcCb);
199 break;
200
201 /* File stuff. */
202 case GUEST_MSG_FILE_NOTIFY:
203 rc = pSession->i_dispatchToObject(pCtxCb, pSvcCb);
204 break;
205
206 /* Session stuff. */
207 case GUEST_MSG_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 }
217 else
218 rc = VERR_INVALID_SESSION_ID;
219
220 LogFlowFuncLeaveRC(rc);
221 return rc;
222}
223
224/**
225 * Removes a guest control session from the internal list and destroys the session.
226 *
227 * @returns VBox status code.
228 * @param uSessionID ID of the guest control session to remove.
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
263/**
264 * Creates a new guest session.
265 * This will invoke VBoxService running on the guest creating a new (dedicated) guest session
266 * On older Guest Additions this call has no effect on the guest, and only the credentials will be
267 * used for starting/impersonating guest processes.
268 *
269 * @returns VBox status code.
270 * @param ssInfo Guest session startup information.
271 * @param guestCreds Guest OS (user) credentials to use on the guest for creating the session.
272 * The specified user must be able to logon to the guest and able to start new processes.
273 * @param pGuestSession Where to store the created guest session on success.
274 */
275int Guest::i_sessionCreate(const GuestSessionStartupInfo &ssInfo,
276 const GuestCredentials &guestCreds, ComObjPtr<GuestSession> &pGuestSession)
277{
278 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
279
280 int rc = VERR_MAX_PROCS_REACHED;
281 if (mData.mGuestSessions.size() >= VBOX_GUESTCTRL_MAX_SESSIONS)
282 return rc;
283
284 try
285 {
286 /* Create a new session ID and assign it. */
287 uint32_t uNewSessionID = VBOX_GUESTCTRL_SESSION_ID_BASE;
288 uint32_t uTries = 0;
289
290 for (;;)
291 {
292 /* Is the context ID already used? */
293 if (!i_sessionExists(uNewSessionID))
294 {
295 rc = VINF_SUCCESS;
296 break;
297 }
298 uNewSessionID++;
299 if (uNewSessionID >= VBOX_GUESTCTRL_MAX_SESSIONS)
300 uNewSessionID = VBOX_GUESTCTRL_SESSION_ID_BASE;
301
302 if (++uTries == VBOX_GUESTCTRL_MAX_SESSIONS)
303 break; /* Don't try too hard. */
304 }
305 if (RT_FAILURE(rc)) throw rc;
306
307 /* Create the session object. */
308 HRESULT hr = pGuestSession.createObject();
309 if (FAILED(hr)) throw VERR_COM_UNEXPECTED;
310
311 /** @todo Use an overloaded copy operator. Later. */
312 GuestSessionStartupInfo startupInfo;
313 startupInfo.mID = uNewSessionID; /* Assign new session ID. */
314 startupInfo.mName = ssInfo.mName;
315 startupInfo.mOpenFlags = ssInfo.mOpenFlags;
316 startupInfo.mOpenTimeoutMS = ssInfo.mOpenTimeoutMS;
317
318 GuestCredentials guestCredentials;
319 if (!guestCreds.mUser.isEmpty())
320 {
321 /** @todo Use an overloaded copy operator. Later. */
322 guestCredentials.mUser = guestCreds.mUser;
323 guestCredentials.mPassword = guestCreds.mPassword;
324 guestCredentials.mDomain = guestCreds.mDomain;
325 }
326 else
327 {
328 /* Internal (annonymous) session. */
329 startupInfo.mIsInternal = true;
330 }
331
332 rc = pGuestSession->init(this, startupInfo, guestCredentials);
333 if (RT_FAILURE(rc)) throw rc;
334
335 /*
336 * Add session object to our session map. This is necessary
337 * before calling openSession because the guest calls back
338 * with the creation result of this session.
339 */
340 mData.mGuestSessions[uNewSessionID] = pGuestSession;
341
342 alock.release(); /* Release lock before firing off event. */
343
344 fireGuestSessionRegisteredEvent(mEventSource, pGuestSession,
345 true /* Registered */);
346 }
347 catch (int rc2)
348 {
349 rc = rc2;
350 }
351
352 LogFlowFuncLeaveRC(rc);
353 return rc;
354}
355
356/**
357 * Returns whether a guest control session with a specific ID exists or not.
358 *
359 * @returns Returns \c true if the session exists, \c false if not.
360 * @param uSessionID ID to check for.
361 */
362inline bool Guest::i_sessionExists(uint32_t uSessionID)
363{
364 GuestSessions::const_iterator itSessions = mData.mGuestSessions.find(uSessionID);
365 return (itSessions == mData.mGuestSessions.end()) ? false : true;
366}
367
368#endif /* VBOX_WITH_GUEST_CONTROL */
369
370
371// implementation of public methods
372/////////////////////////////////////////////////////////////////////////////
373HRESULT Guest::createSession(const com::Utf8Str &aUser, const com::Utf8Str &aPassword, const com::Utf8Str &aDomain,
374 const com::Utf8Str &aSessionName, ComPtr<IGuestSession> &aGuestSession)
375
376{
377#ifndef VBOX_WITH_GUEST_CONTROL
378 ReturnComNotImplemented();
379#else /* VBOX_WITH_GUEST_CONTROL */
380
381 AutoCaller autoCaller(this);
382 if (FAILED(autoCaller.rc())) return autoCaller.rc();
383
384 /* Do not allow anonymous sessions (with system rights) with public API. */
385 if (RT_UNLIKELY(!aUser.length()))
386 return setError(E_INVALIDARG, tr("No user name specified"));
387
388 LogFlowFuncEnter();
389
390 GuestSessionStartupInfo startupInfo;
391 startupInfo.mName = aSessionName;
392
393 GuestCredentials guestCreds;
394 guestCreds.mUser = aUser;
395 guestCreds.mPassword = aPassword;
396 guestCreds.mDomain = aDomain;
397
398 ComObjPtr<GuestSession> pSession;
399 int vrc = i_sessionCreate(startupInfo, guestCreds, pSession);
400 if (RT_SUCCESS(vrc))
401 {
402 /* Return guest session to the caller. */
403 HRESULT hr2 = pSession.queryInterfaceTo(aGuestSession.asOutParam());
404 if (FAILED(hr2))
405 vrc = VERR_COM_OBJECT_NOT_FOUND;
406 }
407
408 if (RT_SUCCESS(vrc))
409 /* Start (fork) the session asynchronously
410 * on the guest. */
411 vrc = pSession->i_startSessionAsync();
412
413 HRESULT hr = S_OK;
414
415 if (RT_FAILURE(vrc))
416 {
417 switch (vrc)
418 {
419 case VERR_MAX_PROCS_REACHED:
420 hr = setErrorBoth(VBOX_E_MAXIMUM_REACHED, vrc, tr("Maximum number of concurrent guest sessions (%d) reached"),
421 VBOX_GUESTCTRL_MAX_SESSIONS);
422 break;
423
424 /** @todo Add more errors here. */
425
426 default:
427 hr = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("Could not create guest session: %Rrc"), vrc);
428 break;
429 }
430 }
431
432 LogFlowThisFunc(("Returning rc=%Rhrc\n", hr));
433 return hr;
434#endif /* VBOX_WITH_GUEST_CONTROL */
435}
436
437HRESULT Guest::findSession(const com::Utf8Str &aSessionName, std::vector<ComPtr<IGuestSession> > &aSessions)
438{
439#ifndef VBOX_WITH_GUEST_CONTROL
440 ReturnComNotImplemented();
441#else /* VBOX_WITH_GUEST_CONTROL */
442
443 LogFlowFuncEnter();
444
445 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
446
447 Utf8Str strName(aSessionName);
448 std::list < ComObjPtr<GuestSession> > listSessions;
449
450 GuestSessions::const_iterator itSessions = mData.mGuestSessions.begin();
451 while (itSessions != mData.mGuestSessions.end())
452 {
453 if (strName.contains(itSessions->second->i_getName())) /** @todo Use a (simple) pattern match (IPRT?). */
454 listSessions.push_back(itSessions->second);
455 ++itSessions;
456 }
457
458 LogFlowFunc(("Sessions with \"%s\" = %RU32\n",
459 aSessionName.c_str(), listSessions.size()));
460
461 aSessions.resize(listSessions.size());
462 if (!listSessions.empty())
463 {
464 size_t i = 0;
465 for (std::list < ComObjPtr<GuestSession> >::const_iterator it = listSessions.begin(); it != listSessions.end(); ++it, ++i)
466 (*it).queryInterfaceTo(aSessions[i].asOutParam());
467
468 return S_OK;
469
470 }
471
472 return setErrorNoLog(VBOX_E_OBJECT_NOT_FOUND,
473 tr("Could not find sessions with name '%s'"),
474 aSessionName.c_str());
475#endif /* VBOX_WITH_GUEST_CONTROL */
476}
477
478HRESULT Guest::updateGuestAdditions(const com::Utf8Str &aSource, const std::vector<com::Utf8Str> &aArguments,
479 const std::vector<AdditionsUpdateFlag_T> &aFlags, ComPtr<IProgress> &aProgress)
480{
481#ifndef VBOX_WITH_GUEST_CONTROL
482 ReturnComNotImplemented();
483#else /* VBOX_WITH_GUEST_CONTROL */
484
485 /* Validate flags. */
486 uint32_t fFlags = AdditionsUpdateFlag_None;
487 if (aFlags.size())
488 for (size_t i = 0; i < aFlags.size(); ++i)
489 fFlags |= aFlags[i];
490
491 if (fFlags && !(fFlags & AdditionsUpdateFlag_WaitForUpdateStartOnly))
492 return setError(E_INVALIDARG, tr("Unknown flags (%#x)"), fFlags);
493
494
495 /* Copy arguments into aArgs: */
496 ProcessArguments aArgs;
497 try
498 {
499 aArgs.resize(0);
500 for (size_t i = 0; i < aArguments.size(); ++i)
501 aArgs.push_back(aArguments[i]);
502 }
503 catch (std::bad_alloc &)
504 {
505 return E_OUTOFMEMORY;
506 }
507
508
509 /*
510 * Create an anonymous session. This is required to run the Guest Additions
511 * update process with administrative rights.
512 */
513 GuestSessionStartupInfo startupInfo;
514 startupInfo.mName = "Updating Guest Additions";
515
516 GuestCredentials guestCreds;
517 RT_ZERO(guestCreds);
518
519 HRESULT hrc;
520 ComObjPtr<GuestSession> pSession;
521 int vrc = i_sessionCreate(startupInfo, guestCreds, pSession);
522 if (RT_SUCCESS(vrc))
523 {
524 Assert(!pSession.isNull());
525
526 int rcGuest = VERR_GSTCTL_GUEST_ERROR;
527 vrc = pSession->i_startSession(&rcGuest);
528 if (RT_SUCCESS(vrc))
529 {
530 /*
531 * Create the update task.
532 */
533 GuestSessionTaskUpdateAdditions *pTask = NULL;
534 try
535 {
536 pTask = new GuestSessionTaskUpdateAdditions(pSession /* GuestSession */, aSource, aArgs, fFlags);
537 hrc = S_OK;
538 }
539 catch (std::bad_alloc &)
540 {
541 hrc = setError(E_OUTOFMEMORY, tr("Failed to create SessionTaskUpdateAdditions object"));
542 }
543 if (SUCCEEDED(hrc))
544 {
545 try
546 {
547 hrc = pTask->Init(Utf8StrFmt(tr("Updating Guest Additions")));
548 }
549 catch (std::bad_alloc &)
550 {
551 hrc = E_OUTOFMEMORY;
552 }
553 if (SUCCEEDED(hrc))
554 {
555 ComPtr<Progress> ptrProgress = pTask->GetProgressObject();
556
557 /*
558 * Kick off the thread. Note! consumes pTask!
559 */
560 hrc = pTask->createThreadWithType(RTTHREADTYPE_MAIN_HEAVY_WORKER);
561 pTask = NULL;
562 if (SUCCEEDED(hrc))
563 hrc = ptrProgress.queryInterfaceTo(aProgress.asOutParam());
564 else
565 hrc = setError(hrc, tr("Starting thread for updating Guest Additions on the guest failed"));
566 }
567 else
568 {
569 hrc = setError(hrc, tr("Failed to initialize SessionTaskUpdateAdditions object"));
570 delete pTask;
571 }
572 }
573 }
574 else
575 {
576 if (vrc == VERR_GSTCTL_GUEST_ERROR)
577 vrc = rcGuest;
578 hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("Could not open guest session: %Rrc"), vrc);
579 }
580 }
581 else
582 {
583 switch (vrc)
584 {
585 case VERR_MAX_PROCS_REACHED:
586 hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("Maximum number of concurrent guest sessions (%d) reached"),
587 VBOX_GUESTCTRL_MAX_SESSIONS);
588 break;
589
590 /** @todo Add more errors here. */
591
592 default:
593 hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("Could not create guest session: %Rrc"), vrc);
594 break;
595 }
596 }
597
598 LogFlowFunc(("Returning hrc=%Rhrc\n", hrc));
599 return hrc;
600#endif /* VBOX_WITH_GUEST_CONTROL */
601}
602
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