VirtualBox

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

Last change on this file since 39895 was 39843, checked in by vboxsync, 13 years ago

GuestCtrl: Request (IPC) changes, bugfixes, fixed handle leaks.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 86.5 KB
Line 
1/* $Id: GuestCtrlImpl.cpp 39843 2012-01-23 18:38:18Z vboxsync $ */
2/** @file
3 * VirtualBox COM class implementation: Guest
4 */
5
6/*
7 * Copyright (C) 2006-2011 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#include "GuestImpl.h"
19#include "GuestCtrlImplPrivate.h"
20
21#include "Global.h"
22#include "ConsoleImpl.h"
23#include "ProgressImpl.h"
24#include "VMMDev.h"
25
26#include "AutoCaller.h"
27#include "Logging.h"
28
29#include <VBox/VMMDev.h>
30#ifdef VBOX_WITH_GUEST_CONTROL
31# include <VBox/com/array.h>
32# include <VBox/com/ErrorInfo.h>
33#endif
34#include <iprt/cpp/utils.h>
35#include <iprt/file.h>
36#include <iprt/getopt.h>
37#include <iprt/isofs.h>
38#include <iprt/list.h>
39#include <iprt/path.h>
40#include <VBox/vmm/pgm.h>
41
42#include <memory>
43
44// public methods only for internal purposes
45/////////////////////////////////////////////////////////////////////////////
46
47#ifdef VBOX_WITH_GUEST_CONTROL
48/**
49 * Appends environment variables to the environment block.
50 *
51 * Each var=value pair is separated by the null character ('\\0'). The whole
52 * block will be stored in one blob and disassembled on the guest side later to
53 * fit into the HGCM param structure.
54 *
55 * @returns VBox status code.
56 *
57 * @param pszEnvVar The environment variable=value to append to the
58 * environment block.
59 * @param ppvList This is actually a pointer to a char pointer
60 * variable which keeps track of the environment block
61 * that we're constructing.
62 * @param pcbList Pointer to the variable holding the current size of
63 * the environment block. (List is a misnomer, go
64 * ahead a be confused.)
65 * @param pcEnvVars Pointer to the variable holding count of variables
66 * stored in the environment block.
67 */
68int Guest::prepareExecuteEnv(const char *pszEnv, void **ppvList, uint32_t *pcbList, uint32_t *pcEnvVars)
69{
70 int rc = VINF_SUCCESS;
71 uint32_t cchEnv = strlen(pszEnv); Assert(cchEnv >= 2);
72 if (*ppvList)
73 {
74 uint32_t cbNewLen = *pcbList + cchEnv + 1; /* Include zero termination. */
75 char *pvTmp = (char *)RTMemRealloc(*ppvList, cbNewLen);
76 if (pvTmp == NULL)
77 rc = VERR_NO_MEMORY;
78 else
79 {
80 memcpy(pvTmp + *pcbList, pszEnv, cchEnv);
81 pvTmp[cbNewLen - 1] = '\0'; /* Add zero termination. */
82 *ppvList = (void **)pvTmp;
83 }
84 }
85 else
86 {
87 char *pszTmp;
88 if (RTStrAPrintf(&pszTmp, "%s", pszEnv) >= 0)
89 {
90 *ppvList = (void **)pszTmp;
91 /* Reset counters. */
92 *pcEnvVars = 0;
93 *pcbList = 0;
94 }
95 }
96 if (RT_SUCCESS(rc))
97 {
98 *pcbList += cchEnv + 1; /* Include zero termination. */
99 *pcEnvVars += 1; /* Increase env variable count. */
100 }
101 return rc;
102}
103
104/**
105 * Adds a callback with a user provided data block and an optional progress object
106 * to the callback map. A callback is identified by a unique context ID which is used
107 * to identify a callback from the guest side.
108 *
109 * @return IPRT status code.
110 * @param pCallback
111 * @param puContextID
112 */
113int Guest::callbackAdd(const PVBOXGUESTCTRL_CALLBACK pCallback, uint32_t *puContextID)
114{
115 AssertPtrReturn(pCallback, VERR_INVALID_PARAMETER);
116 /* puContextID is optional. */
117
118 int rc;
119
120 /* Create a new context ID and assign it. */
121 uint32_t uNewContextID = 0;
122 for (;;)
123 {
124 /* Create a new context ID ... */
125 uNewContextID = ASMAtomicIncU32(&mNextContextID);
126 if (uNewContextID == UINT32_MAX)
127 ASMAtomicUoWriteU32(&mNextContextID, 1000);
128 /* Is the context ID already used? Try next ID ... */
129 if (!callbackExists(uNewContextID))
130 {
131 /* Callback with context ID was not found. This means
132 * we can use this context ID for our new callback we want
133 * to add below. */
134 rc = VINF_SUCCESS;
135 break;
136 }
137 }
138
139 if (RT_SUCCESS(rc))
140 {
141 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
142
143 /* Add callback with new context ID to our callback map. */
144 mCallbackMap[uNewContextID] = *pCallback;
145 Assert(mCallbackMap.size());
146
147 /* Report back new context ID. */
148 if (puContextID)
149 *puContextID = uNewContextID;
150 }
151
152 return rc;
153}
154
155/**
156 * Does not do locking!
157 *
158 * @param uContextID
159 */
160void Guest::callbackDestroy(uint32_t uContextID)
161{
162 AssertReturnVoid(uContextID);
163
164 CallbackMapIter it = mCallbackMap.find(uContextID);
165 if (it != mCallbackMap.end())
166 {
167 LogFlowFunc(("Callback with CID=%u found\n", uContextID));
168 if (it->second.pvData)
169 {
170 LogFlowFunc(("Destroying callback with CID=%u ...\n", uContextID));
171
172 callbackFreeUserData(it->second.pvData);
173 it->second.cbData = 0;
174 }
175
176 /* Remove callback context (not used anymore). */
177 mCallbackMap.erase(it);
178 }
179}
180
181bool Guest::callbackExists(uint32_t uContextID)
182{
183 AssertReturn(uContextID, false);
184
185 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
186
187 CallbackMapIter it = mCallbackMap.find(uContextID);
188 return (it == mCallbackMap.end()) ? false : true;
189}
190
191void Guest::callbackFreeUserData(void *pvData)
192{
193 if (pvData)
194 {
195 RTMemFree(pvData);
196 pvData = NULL;
197 }
198}
199
200int Guest::callbackGetUserData(uint32_t uContextID, eVBoxGuestCtrlCallbackType *pEnmType,
201 void **ppvData, size_t *pcbData)
202{
203 AssertReturn(uContextID, VERR_INVALID_PARAMETER);
204 /* pEnmType is optional. */
205 /* ppvData is optional. */
206 /* pcbData is optional. */
207
208 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
209
210 CallbackMapIterConst it = mCallbackMap.find(uContextID);
211 if (it == mCallbackMap.end())
212 return VERR_NOT_FOUND;
213
214 if (pEnmType)
215 *pEnmType = it->second.mType;
216
217 if ( ppvData
218 && it->second.cbData)
219 {
220 void *pvData = RTMemAlloc(it->second.cbData);
221 AssertPtrReturn(pvData, VERR_NO_MEMORY);
222 memcpy(pvData, it->second.pvData, it->second.cbData);
223 *ppvData = pvData;
224 }
225
226 if (pcbData)
227 *pcbData = it->second.cbData;
228
229 return VINF_SUCCESS;
230}
231
232/* Does not do locking! Caller has to take care of it because the caller needs to
233 * modify the data ...*/
234void* Guest::callbackGetUserDataMutableRaw(uint32_t uContextID, size_t *pcbData)
235{
236 AssertReturn(uContextID, NULL);
237 /* pcbData is optional. */
238
239 CallbackMapIterConst it = mCallbackMap.find(uContextID);
240 if (it != mCallbackMap.end())
241 {
242 if (pcbData)
243 *pcbData = it->second.cbData;
244 return it->second.pvData;
245 }
246
247 return NULL;
248}
249
250int Guest::callbackInit(PVBOXGUESTCTRL_CALLBACK pCallback, eVBoxGuestCtrlCallbackType enmType,
251 ComPtr<Progress> pProgress)
252{
253 AssertPtrReturn(pCallback, VERR_INVALID_POINTER);
254 /* Everything else is optional. */
255
256 int vrc = VINF_SUCCESS;
257 switch (enmType)
258 {
259 case VBOXGUESTCTRLCALLBACKTYPE_EXEC_START:
260 {
261 PCALLBACKDATAEXECSTATUS pData = (PCALLBACKDATAEXECSTATUS)RTMemAlloc(sizeof(CALLBACKDATAEXECSTATUS));
262 AssertPtrReturn(pData, VERR_NO_MEMORY);
263 RT_BZERO(pData, sizeof(CALLBACKDATAEXECSTATUS));
264 pCallback->cbData = sizeof(CALLBACKDATAEXECSTATUS);
265 pCallback->pvData = pData;
266 break;
267 }
268
269 case VBOXGUESTCTRLCALLBACKTYPE_EXEC_OUTPUT:
270 {
271 PCALLBACKDATAEXECOUT pData = (PCALLBACKDATAEXECOUT)RTMemAlloc(sizeof(CALLBACKDATAEXECOUT));
272 AssertPtrReturn(pData, VERR_NO_MEMORY);
273 RT_BZERO(pData, sizeof(CALLBACKDATAEXECOUT));
274 pCallback->cbData = sizeof(CALLBACKDATAEXECOUT);
275 pCallback->pvData = pData;
276 break;
277 }
278
279 case VBOXGUESTCTRLCALLBACKTYPE_EXEC_INPUT_STATUS:
280 {
281 PCALLBACKDATAEXECINSTATUS pData = (PCALLBACKDATAEXECINSTATUS)RTMemAlloc(sizeof(CALLBACKDATAEXECINSTATUS));
282 AssertPtrReturn(pData, VERR_NO_MEMORY);
283 RT_BZERO(pData, sizeof(CALLBACKDATAEXECINSTATUS));
284 pCallback->cbData = sizeof(CALLBACKDATAEXECINSTATUS);
285 pCallback->pvData = pData;
286 break;
287 }
288
289 default:
290 vrc = VERR_INVALID_PARAMETER;
291 break;
292 }
293
294 if (RT_SUCCESS(vrc))
295 {
296 /* Init/set common stuff. */
297 pCallback->mType = enmType;
298 pCallback->pProgress = pProgress;
299 }
300
301 return vrc;
302}
303
304bool Guest::callbackIsCanceled(uint32_t uContextID)
305{
306 AssertReturn(uContextID, true);
307
308 ComPtr<IProgress> pProgress;
309 {
310 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
311
312 CallbackMapIterConst it = mCallbackMap.find(uContextID);
313 if (it != mCallbackMap.end())
314 pProgress = it->second.pProgress;
315 }
316
317 if (pProgress)
318 {
319 BOOL fCanceled = FALSE;
320 HRESULT hRC = pProgress->COMGETTER(Canceled)(&fCanceled);
321 if ( SUCCEEDED(hRC)
322 && !fCanceled)
323 {
324 return false;
325 }
326 }
327
328 return true; /* No progress / error means canceled. */
329}
330
331bool Guest::callbackIsComplete(uint32_t uContextID)
332{
333 AssertReturn(uContextID, true);
334
335 ComPtr<IProgress> pProgress;
336 {
337 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
338
339 CallbackMapIterConst it = mCallbackMap.find(uContextID);
340 if (it != mCallbackMap.end())
341 pProgress = it->second.pProgress;
342 }
343
344 if (pProgress)
345 {
346 BOOL fCompleted = FALSE;
347 HRESULT hRC = pProgress->COMGETTER(Completed)(&fCompleted);
348 if ( SUCCEEDED(hRC)
349 && fCompleted)
350 {
351 return true;
352 }
353 }
354
355 return false;
356}
357
358int Guest::callbackMoveForward(uint32_t uContextID, const char *pszMessage)
359{
360 AssertReturn(uContextID, VERR_INVALID_PARAMETER);
361 AssertPtrReturn(pszMessage, VERR_INVALID_PARAMETER);
362
363 ComPtr<IProgress> pProgress;
364 {
365 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
366
367 CallbackMapIterConst it = mCallbackMap.find(uContextID);
368 if (it != mCallbackMap.end())
369 pProgress = it->second.pProgress;
370 }
371
372 if (pProgress)
373 {
374 HRESULT hr = pProgress->SetNextOperation(Bstr(pszMessage).raw(), 1 /* Weight */);
375 if (FAILED(hr))
376 return VERR_CANCELLED;
377
378 return VINF_SUCCESS;
379 }
380
381 return VERR_NOT_FOUND;
382}
383
384/**
385 * Notifies a specified callback about its final status.
386 *
387 * @return IPRT status code.
388 * @param uContextID
389 * @param iRC
390 * @param pszMessage
391 */
392int Guest::callbackNotifyEx(uint32_t uContextID, int iRC, const char *pszMessage)
393{
394 AssertReturn(uContextID, VERR_INVALID_PARAMETER);
395 if (RT_FAILURE(iRC))
396 AssertReturn(pszMessage, VERR_INVALID_PARAMETER);
397
398 LogFlowFunc(("Checking whether callback (CID=%u) needs notification iRC=%Rrc, pszMsg=%s\n",
399 uContextID, iRC, pszMessage ? pszMessage : "<No message given>"));
400
401 ComObjPtr<Progress> pProgress;
402 {
403 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
404
405 CallbackMapIterConst it = mCallbackMap.find(uContextID);
406 if (it != mCallbackMap.end())
407 pProgress = it->second.pProgress;
408 }
409
410#if 0
411 BOOL fCanceled = FALSE;
412 HRESULT hRC = pProgress->COMGETTER(Canceled)(&fCanceled);
413 if ( SUCCEEDED(hRC)
414 && fCanceled)
415 {
416 /* If progress already canceled do nothing here. */
417 return VINF_SUCCESS;
418 }
419#endif
420
421 if (pProgress)
422 {
423 /*
424 * Assume we didn't complete to make sure we clean up even if the
425 * following call fails.
426 */
427 BOOL fCompleted = FALSE;
428 HRESULT hRC = pProgress->COMGETTER(Completed)(&fCompleted);
429 if ( SUCCEEDED(hRC)
430 && !fCompleted)
431 {
432 LogFlowFunc(("Notifying callback with CID=%u, iRC=%Rrc, pszMsg=%s\n",
433 uContextID, iRC, pszMessage ? pszMessage : "<No message given>"));
434
435 /*
436 * To get waitForCompletion completed (unblocked) we have to notify it if necessary (only
437 * cancel won't work!). This could happen if the client thread (e.g. VBoxService, thread of a spawned process)
438 * is disconnecting without having the chance to sending a status message before, so we
439 * have to abort here to make sure the host never hangs/gets stuck while waiting for the
440 * progress object to become signalled.
441 */
442 if (RT_SUCCESS(iRC))
443 {
444 hRC = pProgress->notifyComplete(S_OK);
445 }
446 else
447 {
448
449 hRC = pProgress->notifyComplete(VBOX_E_IPRT_ERROR /* Must not be S_OK. */,
450 COM_IIDOF(IGuest),
451 Guest::getStaticComponentName(),
452 pszMessage);
453 }
454
455 LogFlowFunc(("Notified callback with CID=%u returned %Rhrc (0x%x)\n",
456 uContextID, hRC, hRC));
457 }
458 else
459 LogFlowFunc(("Callback with CID=%u already notified\n", uContextID));
460
461 /*
462 * Do *not* NULL pProgress here, because waiting function like executeProcess()
463 * will still rely on this object for checking whether they have to give up!
464 */
465 }
466 /* If pProgress is not found (anymore) that's fine.
467 * Might be destroyed already. */
468 return S_OK;
469}
470
471/**
472 * TODO
473 *
474 * @return IPRT status code.
475 * @param uPID
476 * @param iRC
477 * @param pszMessage
478 */
479int Guest::callbackNotifyAllForPID(uint32_t uPID, int iRC, const char *pszMessage)
480{
481 AssertReturn(uPID, VERR_INVALID_PARAMETER);
482
483 int vrc = VINF_SUCCESS;
484
485 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
486
487 CallbackMapIter it;
488 for (it = mCallbackMap.begin(); it != mCallbackMap.end(); it++)
489 {
490 switch (it->second.mType)
491 {
492 case VBOXGUESTCTRLCALLBACKTYPE_EXEC_START:
493 break;
494
495 /* When waiting for process output while the process is destroyed,
496 * make sure we also destroy the actual waiting operation (internal progress object)
497 * in order to not block the caller. */
498 case VBOXGUESTCTRLCALLBACKTYPE_EXEC_OUTPUT:
499 {
500 PCALLBACKDATAEXECOUT pItData = (PCALLBACKDATAEXECOUT)it->second.pvData;
501 AssertPtr(pItData);
502 if (pItData->u32PID == uPID)
503 vrc = callbackNotifyEx(it->first, iRC, pszMessage);
504 break;
505 }
506
507 /* When waiting for injecting process input while the process is destroyed,
508 * make sure we also destroy the actual waiting operation (internal progress object)
509 * in order to not block the caller. */
510 case VBOXGUESTCTRLCALLBACKTYPE_EXEC_INPUT_STATUS:
511 {
512 PCALLBACKDATAEXECINSTATUS pItData = (PCALLBACKDATAEXECINSTATUS)it->second.pvData;
513 AssertPtr(pItData);
514 if (pItData->u32PID == uPID)
515 vrc = callbackNotifyEx(it->first, iRC, pszMessage);
516 break;
517 }
518
519 default:
520 vrc = VERR_INVALID_PARAMETER;
521 AssertMsgFailed(("Unknown callback type %d, iRC=%d, message=%s\n",
522 it->second.mType, iRC, pszMessage ? pszMessage : "<No message given>"));
523 break;
524 }
525
526 if (RT_FAILURE(vrc))
527 break;
528 }
529
530 return vrc;
531}
532
533int Guest::callbackNotifyComplete(uint32_t uContextID)
534{
535 return callbackNotifyEx(uContextID, S_OK, NULL /* No message */);
536}
537
538/**
539 * Waits for a callback (using its context ID) to complete.
540 *
541 * @return IPRT status code.
542 * @param uContextID Context ID to wait for.
543 * @param lStage Stage to wait for. Specify -1 if no staging is present/required.
544 * Specifying a stage is only needed if there's a multi operation progress
545 * object to wait for.
546 * @param lTimeout Timeout (in ms) to wait for.
547 */
548int Guest::callbackWaitForCompletion(uint32_t uContextID, LONG lStage, LONG lTimeout)
549{
550 AssertReturn(uContextID, VERR_INVALID_PARAMETER);
551
552 /*
553 * Wait for the HGCM low level callback until the process
554 * has been started (or something went wrong). This is necessary to
555 * get the PID.
556 */
557
558 int vrc = VINF_SUCCESS;
559 ComPtr<IProgress> pProgress;
560 {
561 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
562
563 CallbackMapIterConst it = mCallbackMap.find(uContextID);
564 if (it != mCallbackMap.end())
565 pProgress = it->second.pProgress;
566 else
567 vrc = VERR_NOT_FOUND;
568 }
569
570 if (RT_SUCCESS(vrc))
571 {
572 LogFlowFunc(("Waiting for callback completion (CID=%u, Stage=%RI32, timeout=%RI32ms) ...\n",
573 uContextID, lStage, lTimeout));
574 HRESULT rc;
575 if (lStage < 0)
576 rc = pProgress->WaitForCompletion(lTimeout);
577 else
578 rc = pProgress->WaitForOperationCompletion((ULONG)lStage, lTimeout);
579 if (SUCCEEDED(rc))
580 {
581 if (!callbackIsComplete(uContextID))
582 vrc = callbackIsCanceled(uContextID)
583 ? VERR_CANCELLED : VINF_SUCCESS;
584 }
585 else
586 vrc = VERR_TIMEOUT;
587 }
588
589 LogFlowFunc(("Callback (CID=%u) completed with rc=%Rrc\n",
590 uContextID, vrc));
591 return vrc;
592}
593
594/**
595 * Static callback function for receiving updates on guest control commands
596 * from the guest. Acts as a dispatcher for the actual class instance.
597 *
598 * @returns VBox status code.
599 *
600 * @todo
601 *
602 */
603DECLCALLBACK(int) Guest::notifyCtrlDispatcher(void *pvExtension,
604 uint32_t u32Function,
605 void *pvParms,
606 uint32_t cbParms)
607{
608 using namespace guestControl;
609
610 /*
611 * No locking, as this is purely a notification which does not make any
612 * changes to the object state.
613 */
614#ifdef DEBUG_andy
615 LogFlowFunc(("pvExtension=%p, u32Function=%d, pvParms=%p, cbParms=%d\n",
616 pvExtension, u32Function, pvParms, cbParms));
617#endif
618 ComObjPtr<Guest> pGuest = reinterpret_cast<Guest *>(pvExtension);
619
620 int rc = VINF_SUCCESS;
621 switch (u32Function)
622 {
623 case GUEST_DISCONNECTED:
624 {
625 //LogFlowFunc(("GUEST_DISCONNECTED\n"));
626
627 PCALLBACKDATACLIENTDISCONNECTED pCBData = reinterpret_cast<PCALLBACKDATACLIENTDISCONNECTED>(pvParms);
628 AssertPtr(pCBData);
629 AssertReturn(sizeof(CALLBACKDATACLIENTDISCONNECTED) == cbParms, VERR_INVALID_PARAMETER);
630 AssertReturn(CALLBACKDATAMAGIC_CLIENT_DISCONNECTED == pCBData->hdr.u32Magic, VERR_INVALID_PARAMETER);
631
632 rc = pGuest->notifyCtrlClientDisconnected(u32Function, pCBData);
633 break;
634 }
635
636 case GUEST_EXEC_SEND_STATUS:
637 {
638 //LogFlowFunc(("GUEST_EXEC_SEND_STATUS\n"));
639
640 PCALLBACKDATAEXECSTATUS pCBData = reinterpret_cast<PCALLBACKDATAEXECSTATUS>(pvParms);
641 AssertPtr(pCBData);
642 AssertReturn(sizeof(CALLBACKDATAEXECSTATUS) == cbParms, VERR_INVALID_PARAMETER);
643 AssertReturn(CALLBACKDATAMAGIC_EXEC_STATUS == pCBData->hdr.u32Magic, VERR_INVALID_PARAMETER);
644
645 rc = pGuest->notifyCtrlExecStatus(u32Function, pCBData);
646 break;
647 }
648
649 case GUEST_EXEC_SEND_OUTPUT:
650 {
651 //LogFlowFunc(("GUEST_EXEC_SEND_OUTPUT\n"));
652
653 PCALLBACKDATAEXECOUT pCBData = reinterpret_cast<PCALLBACKDATAEXECOUT>(pvParms);
654 AssertPtr(pCBData);
655 AssertReturn(sizeof(CALLBACKDATAEXECOUT) == cbParms, VERR_INVALID_PARAMETER);
656 AssertReturn(CALLBACKDATAMAGIC_EXEC_OUT == pCBData->hdr.u32Magic, VERR_INVALID_PARAMETER);
657
658 rc = pGuest->notifyCtrlExecOut(u32Function, pCBData);
659 break;
660 }
661
662 case GUEST_EXEC_SEND_INPUT_STATUS:
663 {
664 //LogFlowFunc(("GUEST_EXEC_SEND_INPUT_STATUS\n"));
665
666 PCALLBACKDATAEXECINSTATUS pCBData = reinterpret_cast<PCALLBACKDATAEXECINSTATUS>(pvParms);
667 AssertPtr(pCBData);
668 AssertReturn(sizeof(CALLBACKDATAEXECINSTATUS) == cbParms, VERR_INVALID_PARAMETER);
669 AssertReturn(CALLBACKDATAMAGIC_EXEC_IN_STATUS == pCBData->hdr.u32Magic, VERR_INVALID_PARAMETER);
670
671 rc = pGuest->notifyCtrlExecInStatus(u32Function, pCBData);
672 break;
673 }
674
675 default:
676 AssertMsgFailed(("Unknown guest control notification received, u32Function=%u\n", u32Function));
677 rc = VERR_INVALID_PARAMETER;
678 break;
679 }
680 return rc;
681}
682
683/* Function for handling the execution start/termination notification. */
684/* Callback can be called several times. */
685int Guest::notifyCtrlExecStatus(uint32_t u32Function,
686 PCALLBACKDATAEXECSTATUS pData)
687{
688 AssertReturn(u32Function, VERR_INVALID_PARAMETER);
689 AssertPtrReturn(pData, VERR_INVALID_PARAMETER);
690
691 uint32_t uContextID = pData->hdr.u32ContextID;
692 Assert(uContextID);
693
694 /* Scope write locks as much as possible. */
695 {
696 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
697
698 LogFlowFunc(("Execution status (CID=%u, pData=0x%p)\n",
699 uContextID, pData));
700
701 PCALLBACKDATAEXECSTATUS pCallbackData =
702 (PCALLBACKDATAEXECSTATUS)callbackGetUserDataMutableRaw(uContextID, NULL /* cbData */);
703 if (pCallbackData)
704 {
705 pCallbackData->u32PID = pData->u32PID;
706 pCallbackData->u32Status = pData->u32Status;
707 pCallbackData->u32Flags = pData->u32Flags;
708 /** @todo Copy void* buffer contents? */
709 }
710 /* If pCallbackData is NULL this might be an old request for which no user data
711 * might exist anymore. */
712 }
713
714 int vrc = VINF_SUCCESS; /* Function result. */
715 int rcCallback = VINF_SUCCESS; /* Callback result. */
716 Utf8Str errMsg;
717
718 /* Was progress canceled before? */
719 bool fCanceled = callbackIsCanceled(uContextID);
720 if (!fCanceled)
721 {
722 /* Handle process map. This needs to be done first in order to have a valid
723 * map in case some callback gets notified a bit below. */
724
725 /* Note: PIDs never get removed here in case the guest process signalled its
726 * end; instead the next call of GetProcessStatus() will remove the PID
727 * from the process map after we got the process' final (exit) status.
728 * See waitpid() for an example. */
729 if (pData->u32PID) /* Only add/change a process if it has a valid PID (>0). */
730 {
731 switch (pData->u32Status)
732 {
733 /* Interprete u32Flags as the guest process' exit code. */
734 case PROC_STS_TES:
735 case PROC_STS_TOK:
736 vrc = processSetStatus(pData->u32PID,
737 (ExecuteProcessStatus_T)pData->u32Status,
738 pData->u32Flags /* Exit code. */, 0 /* Flags. */);
739 break;
740 /* Just reach through flags. */
741 default:
742 vrc = processSetStatus(pData->u32PID,
743 (ExecuteProcessStatus_T)pData->u32Status,
744 0 /* Exit code. */, pData->u32Flags);
745 break;
746 }
747 }
748
749 /* Do progress handling. */
750 switch (pData->u32Status)
751 {
752 case PROC_STS_STARTED:
753 vrc = callbackMoveForward(uContextID, Guest::tr("Waiting for process to exit ..."));
754 LogRel(("Guest process (PID %u) started\n", pData->u32PID)); /** @todo Add process name */
755 break;
756
757 case PROC_STS_TEN: /* Terminated normally. */
758 vrc = callbackNotifyComplete(uContextID);
759 LogRel(("Guest process (PID %u) exited normally\n", pData->u32PID)); /** @todo Add process name */
760 break;
761
762 case PROC_STS_TEA: /* Terminated abnormally. */
763 LogRel(("Guest process (PID %u) terminated abnormally with exit code = %u\n",
764 pData->u32PID, pData->u32Flags)); /** @todo Add process name */
765 errMsg = Utf8StrFmt(Guest::tr("Process terminated abnormally with status '%u'"),
766 pData->u32Flags);
767 rcCallback = VERR_GENERAL_FAILURE; /** @todo */
768 break;
769
770 case PROC_STS_TES: /* Terminated through signal. */
771 LogRel(("Guest process (PID %u) terminated through signal with exit code = %u\n",
772 pData->u32PID, pData->u32Flags)); /** @todo Add process name */
773 errMsg = Utf8StrFmt(Guest::tr("Process terminated via signal with status '%u'"),
774 pData->u32Flags);
775 rcCallback = VERR_GENERAL_FAILURE; /** @todo */
776 break;
777
778 case PROC_STS_TOK:
779 LogRel(("Guest process (PID %u) timed out and was killed\n", pData->u32PID)); /** @todo Add process name */
780 errMsg = Utf8StrFmt(Guest::tr("Process timed out and was killed"));
781 rcCallback = VERR_TIMEOUT;
782 break;
783
784 case PROC_STS_TOA:
785 LogRel(("Guest process (PID %u) timed out and could not be killed\n", pData->u32PID)); /** @todo Add process name */
786 errMsg = Utf8StrFmt(Guest::tr("Process timed out and could not be killed"));
787 rcCallback = VERR_TIMEOUT;
788 break;
789
790 case PROC_STS_DWN:
791 LogRel(("Guest process (PID %u) killed because system is shutting down\n", pData->u32PID)); /** @todo Add process name */
792 /*
793 * If u32Flags has ExecuteProcessFlag_IgnoreOrphanedProcesses set, we don't report an error to
794 * our progress object. This is helpful for waiters which rely on the success of our progress object
795 * even if the executed process was killed because the system/VBoxService is shutting down.
796 *
797 * In this case u32Flags contains the actual execution flags reached in via Guest::ExecuteProcess().
798 */
799 if (pData->u32Flags & ExecuteProcessFlag_IgnoreOrphanedProcesses)
800 {
801 vrc = callbackNotifyComplete(uContextID);
802 }
803 else
804 {
805 errMsg = Utf8StrFmt(Guest::tr("Process killed because system is shutting down"));
806 rcCallback = VERR_CANCELLED;
807 }
808 break;
809
810 case PROC_STS_ERROR:
811 if (pData->u32PID)
812 {
813 LogRel(("Guest process (PID %u) could not be started because of rc=%Rrc\n",
814 pData->u32PID, pData->u32Flags)); /** @todo Add process name */
815 }
816 else
817 {
818 switch (pData->u32Flags)
819 {
820 case VERR_MAX_PROCS_REACHED:
821 LogRel(("Guest process could not be started because maximum number of parallel guest processes has been reached\n"));
822 break;
823
824 default:
825 LogRel(("Guest process could not be started because of rc=%Rrc\n",
826 pData->u32Flags));
827 }
828
829 }
830 errMsg = Utf8StrFmt(Guest::tr("Process execution failed with rc=%Rrc"), pData->u32Flags);
831 rcCallback = pData->u32Flags; /* Report back rc. */
832 break;
833
834 default:
835 vrc = VERR_INVALID_PARAMETER;
836 break;
837 }
838 }
839 else
840 {
841 errMsg = Utf8StrFmt(Guest::tr("Process execution canceled"));
842 rcCallback = VERR_CANCELLED;
843 }
844
845 /* Do we need to handle the callback error? */
846 if (RT_FAILURE(rcCallback))
847 {
848 AssertMsg(!errMsg.isEmpty(), ("Error message must not be empty!\n"));
849
850 /* Notify all callbacks which are still waiting on something
851 * which is related to the current PID. */
852 if (pData->u32PID)
853 {
854 int rc2 = callbackNotifyAllForPID(pData->u32PID, rcCallback, errMsg.c_str());
855 if (RT_FAILURE(rc2))
856 {
857 LogFlowFunc(("Failed to notify other callbacks for PID=%u\n",
858 pData->u32PID));
859 if (RT_SUCCESS(vrc))
860 vrc = rc2;
861 }
862 }
863
864 /* Let the caller know what went wrong ... */
865 int rc2 = callbackNotifyEx(uContextID, rcCallback, errMsg.c_str());
866 if (RT_FAILURE(rc2))
867 {
868 LogFlowFunc(("Failed to notify callback CID=%u for PID=%u\n",
869 uContextID, pData->u32PID));
870 if (RT_SUCCESS(vrc))
871 vrc = rc2;
872 }
873 LogFlowFunc(("Process (CID=%u, status=%u) reported: %s\n",
874 uContextID, pData->u32Status, errMsg.c_str()));
875 }
876 LogFlowFunc(("Returned with rc=%Rrc, rcCallback=%Rrc\n",
877 vrc, rcCallback));
878 return vrc;
879}
880
881/* Function for handling the execution output notification. */
882int Guest::notifyCtrlExecOut(uint32_t u32Function,
883 PCALLBACKDATAEXECOUT pData)
884{
885 AssertReturn(u32Function, VERR_INVALID_PARAMETER);
886 AssertPtrReturn(pData, VERR_INVALID_PARAMETER);
887
888 uint32_t uContextID = pData->hdr.u32ContextID;
889 Assert(uContextID);
890
891 /* Scope write locks as much as possible. */
892 {
893 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
894
895 LogFlowFunc(("Output status (CID=%u, pData=0x%p)\n",
896 uContextID, pData));
897
898 PCALLBACKDATAEXECOUT pCallbackData =
899 (PCALLBACKDATAEXECOUT)callbackGetUserDataMutableRaw(uContextID, NULL /* cbData */);
900 if (pCallbackData)
901 {
902 pCallbackData->u32PID = pData->u32PID;
903 pCallbackData->u32HandleId = pData->u32HandleId;
904 pCallbackData->u32Flags = pData->u32Flags;
905
906 /* Make sure we really got something! */
907 if ( pData->cbData
908 && pData->pvData)
909 {
910 callbackFreeUserData(pCallbackData->pvData);
911
912 /* Allocate data buffer and copy it */
913 pCallbackData->pvData = RTMemAlloc(pData->cbData);
914 pCallbackData->cbData = pData->cbData;
915
916 AssertReturn(pCallbackData->pvData, VERR_NO_MEMORY);
917 memcpy(pCallbackData->pvData, pData->pvData, pData->cbData);
918 }
919 else /* Nothing received ... */
920 {
921 pCallbackData->pvData = NULL;
922 pCallbackData->cbData = 0;
923 }
924 }
925 /* If pCallbackData is NULL this might be an old request for which no user data
926 * might exist anymore. */
927 }
928
929 int vrc;
930 if (callbackIsCanceled(pData->u32PID))
931 {
932 vrc = callbackNotifyEx(uContextID, VERR_CANCELLED,
933 Guest::tr("The output operation was canceled"));
934 }
935 else
936 vrc = callbackNotifyComplete(uContextID);
937
938 return vrc;
939}
940
941/* Function for handling the execution input status notification. */
942int Guest::notifyCtrlExecInStatus(uint32_t u32Function,
943 PCALLBACKDATAEXECINSTATUS pData)
944{
945 AssertReturn(u32Function, VERR_INVALID_PARAMETER);
946 AssertPtrReturn(pData, VERR_INVALID_PARAMETER);
947
948 uint32_t uContextID = pData->hdr.u32ContextID;
949 Assert(uContextID);
950
951 /* Scope write locks as much as possible. */
952 {
953 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
954
955 LogFlowFunc(("Input status (CID=%u, pData=0x%p)\n",
956 uContextID, pData));
957
958 PCALLBACKDATAEXECINSTATUS pCallbackData =
959 (PCALLBACKDATAEXECINSTATUS)callbackGetUserDataMutableRaw(uContextID, NULL /* cbData */);
960 if (pCallbackData)
961 {
962 /* Save bytes processed. */
963 pCallbackData->cbProcessed = pData->cbProcessed;
964 pCallbackData->u32Status = pData->u32Status;
965 pCallbackData->u32Flags = pData->u32Flags;
966 pCallbackData->u32PID = pData->u32PID;
967 }
968 /* If pCallbackData is NULL this might be an old request for which no user data
969 * might exist anymore. */
970 }
971
972 return callbackNotifyComplete(uContextID);
973}
974
975int Guest::notifyCtrlClientDisconnected(uint32_t u32Function,
976 PCALLBACKDATACLIENTDISCONNECTED pData)
977{
978 /* u32Function is 0. */
979 AssertPtrReturn(pData, VERR_INVALID_PARAMETER);
980
981 uint32_t uContextID = pData->hdr.u32ContextID;
982 Assert(uContextID);
983
984 LogFlowFunc(("Client disconnected (CID=%u)\n,", uContextID));
985
986 return callbackNotifyEx(uContextID, VERR_CANCELLED,
987 Guest::tr("Client disconnected"));
988}
989
990/**
991 * Gets guest process information. Removes the process from the map
992 * after the process was marked as exited/terminated.
993 *
994 * @return IPRT status code.
995 * @param u32PID
996 * @param pProcess
997 */
998int Guest::processGetStatus(uint32_t u32PID, PVBOXGUESTCTRL_PROCESS pProcess)
999{
1000 AssertReturn(u32PID, VERR_INVALID_PARAMETER);
1001
1002 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1003
1004 GuestProcessMapIter it = mGuestProcessMap.find(u32PID);
1005 if (it != mGuestProcessMap.end())
1006 {
1007 if (pProcess)
1008 {
1009 pProcess->mStatus = it->second.mStatus;
1010 pProcess->mExitCode = it->second.mExitCode;
1011 pProcess->mFlags = it->second.mFlags;
1012 }
1013
1014 /* If the is marked as stopped/terminated
1015 * remove it from the map. */
1016 if (it->second.mStatus != ExecuteProcessStatus_Started)
1017 mGuestProcessMap.erase(it);
1018
1019 return VINF_SUCCESS;
1020 }
1021
1022 return VERR_NOT_FOUND;
1023}
1024
1025int Guest::processSetStatus(uint32_t u32PID, ExecuteProcessStatus_T enmStatus, uint32_t uExitCode, uint32_t uFlags)
1026{
1027 AssertReturn(u32PID, VERR_INVALID_PARAMETER);
1028
1029 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1030
1031 GuestProcessMapIter it = mGuestProcessMap.find(u32PID);
1032 if (it != mGuestProcessMap.end())
1033 {
1034 it->second.mStatus = enmStatus;
1035 it->second.mExitCode = uExitCode;
1036 it->second.mFlags = uFlags;
1037 }
1038 else
1039 {
1040 VBOXGUESTCTRL_PROCESS process;
1041
1042 process.mStatus = enmStatus;
1043 process.mExitCode = uExitCode;
1044 process.mFlags = uFlags;
1045
1046 mGuestProcessMap[u32PID] = process;
1047 }
1048
1049 return VINF_SUCCESS;
1050}
1051
1052HRESULT Guest::handleErrorCompletion(int rc)
1053{
1054 HRESULT hRC;
1055 if (rc == VERR_NOT_FOUND)
1056 hRC = setErrorNoLog(VBOX_E_VM_ERROR,
1057 tr("VMM device is not available (is the VM running?)"));
1058 else if (rc == VERR_CANCELLED)
1059 hRC = setErrorNoLog(VBOX_E_IPRT_ERROR,
1060 tr("Process execution has been canceled"));
1061 else if (rc == VERR_TIMEOUT)
1062 hRC= setErrorNoLog(VBOX_E_IPRT_ERROR,
1063 tr("The guest did not respond within time"));
1064 else
1065 hRC = setErrorNoLog(E_UNEXPECTED,
1066 tr("Waiting for completion failed with error %Rrc"), rc);
1067 return hRC;
1068}
1069
1070HRESULT Guest::handleErrorHGCM(int rc)
1071{
1072 HRESULT hRC;
1073 if (rc == VERR_INVALID_VM_HANDLE)
1074 hRC = setErrorNoLog(VBOX_E_VM_ERROR,
1075 tr("VMM device is not available (is the VM running?)"));
1076 else if (rc == VERR_NOT_FOUND)
1077 hRC = setErrorNoLog(VBOX_E_IPRT_ERROR,
1078 tr("The guest execution service is not ready (yet)"));
1079 else if (rc == VERR_HGCM_SERVICE_NOT_FOUND)
1080 hRC= setErrorNoLog(VBOX_E_IPRT_ERROR,
1081 tr("The guest execution service is not available"));
1082 else /* HGCM call went wrong. */
1083 hRC = setErrorNoLog(E_UNEXPECTED,
1084 tr("The HGCM call failed with error %Rrc"), rc);
1085 return hRC;
1086}
1087#endif /* VBOX_WITH_GUEST_CONTROL */
1088
1089STDMETHODIMP Guest::ExecuteProcess(IN_BSTR aCommand, ULONG aFlags,
1090 ComSafeArrayIn(IN_BSTR, aArguments), ComSafeArrayIn(IN_BSTR, aEnvironment),
1091 IN_BSTR aUsername, IN_BSTR aPassword,
1092 ULONG aTimeoutMS, ULONG *aPID, IProgress **aProgress)
1093{
1094/** @todo r=bird: Eventually we should clean up all the timeout parameters
1095 * in the API and have the same way of specifying infinite waits! */
1096#ifndef VBOX_WITH_GUEST_CONTROL
1097 ReturnComNotImplemented();
1098#else /* VBOX_WITH_GUEST_CONTROL */
1099 using namespace guestControl;
1100
1101 CheckComArgStrNotEmptyOrNull(aCommand);
1102 CheckComArgOutPointerValid(aPID);
1103 CheckComArgOutPointerValid(aProgress);
1104
1105 /* Do not allow anonymous executions (with system rights). */
1106 if (RT_UNLIKELY((aUsername) == NULL || *(aUsername) == '\0'))
1107 return setError(E_INVALIDARG, tr("No user name specified"));
1108
1109 LogRel(("Executing guest process \"%s\" as user \"%s\" ...\n",
1110 Utf8Str(aCommand).c_str(), Utf8Str(aUsername).c_str()));
1111
1112 return executeProcessInternal(aCommand, aFlags, ComSafeArrayInArg(aArguments),
1113 ComSafeArrayInArg(aEnvironment),
1114 aUsername, aPassword, aTimeoutMS, aPID, aProgress, NULL /* rc */);
1115#endif
1116}
1117
1118#ifdef VBOX_WITH_GUEST_CONTROL
1119/**
1120 * Executes and waits for an internal tool (that is, a tool which is integrated into
1121 * VBoxService, beginning with "vbox_" (e.g. "vbox_ls")) to finish its operation.
1122 *
1123 * @return HRESULT
1124 * @param aTool Name of tool to execute.
1125 * @param aDescription Friendly description of the operation.
1126 * @param aFlags Execution flags.
1127 * @param aUsername Username to execute tool under.
1128 * @param aPassword The user's password.
1129 * @param uFlagsToAdd ExecuteProcessFlag flags to add to the execution operation.
1130 * @param aProgress Pointer which receives the tool's progress object. Optional.
1131 * @param aPID Pointer which receives the tool's PID. Optional.
1132 */
1133HRESULT Guest::executeAndWaitForTool(IN_BSTR aTool, IN_BSTR aDescription,
1134 ComSafeArrayIn(IN_BSTR, aArguments), ComSafeArrayIn(IN_BSTR, aEnvironment),
1135 IN_BSTR aUsername, IN_BSTR aPassword,
1136 ULONG uFlagsToAdd,
1137 GuestCtrlStreamObjects *pObjStdOut, GuestCtrlStreamObjects *pObjStdErr,
1138 IProgress **aProgress, ULONG *aPID)
1139{
1140 ComPtr<IProgress> progressTool;
1141 ULONG uPID;
1142 ULONG uFlags = ExecuteProcessFlag_Hidden;
1143 if (uFlagsToAdd)
1144 uFlags |= uFlagsToAdd;
1145
1146 bool fWaitForOutput = false;
1147 if ( ( (uFlags & ExecuteProcessFlag_WaitForStdOut)
1148 && pObjStdOut)
1149 || ( (uFlags & ExecuteProcessFlag_WaitForStdErr)
1150 && pObjStdErr))
1151 {
1152 fWaitForOutput = true;
1153 }
1154
1155 HRESULT rc = ExecuteProcess(aTool,
1156 uFlags,
1157 ComSafeArrayInArg(aArguments),
1158 ComSafeArrayInArg(aEnvironment),
1159 aUsername, aPassword,
1160 0 /* No timeout. */,
1161 &uPID, progressTool.asOutParam());
1162 if ( SUCCEEDED(rc)
1163 && fWaitForOutput)
1164 {
1165 BOOL fCompleted;
1166 while ( SUCCEEDED(progressTool->COMGETTER(Completed)(&fCompleted))
1167 && !fCompleted)
1168 {
1169 BOOL fCanceled;
1170 rc = progressTool->COMGETTER(Canceled)(&fCanceled);
1171 AssertComRC(rc);
1172 if (fCanceled)
1173 {
1174 rc = setErrorNoLog(VBOX_E_IPRT_ERROR,
1175 tr("%s was cancelled"), Utf8Str(aDescription).c_str());
1176 break;
1177 }
1178
1179 if ( (uFlags & ExecuteProcessFlag_WaitForStdOut)
1180 && pObjStdOut)
1181 {
1182 rc = executeStreamParse(uPID, ProcessOutputFlag_None /* StdOut */, *pObjStdOut);
1183 }
1184
1185 if ( (uFlags & ExecuteProcessFlag_WaitForStdErr)
1186 && pObjStdErr)
1187 {
1188 rc = executeStreamParse(uPID, ProcessOutputFlag_StdErr, *pObjStdErr);
1189 }
1190
1191 if (FAILED(rc))
1192 break;
1193 }
1194 }
1195
1196 if (SUCCEEDED(rc))
1197 {
1198 if (aProgress)
1199 {
1200 /* Return the progress to the caller. */
1201 progressTool.queryInterfaceTo(aProgress);
1202 }
1203
1204 if (aPID)
1205 *aPID = uPID;
1206 }
1207
1208 return rc;
1209}
1210
1211HRESULT Guest::executeProcessResult(const char *pszCommand, const char *pszUser, ULONG ulTimeout,
1212 PCALLBACKDATAEXECSTATUS pExecStatus, ULONG *puPID)
1213{
1214 AssertPtrReturn(pExecStatus, E_INVALIDARG);
1215 AssertPtrReturn(puPID, E_INVALIDARG);
1216
1217 HRESULT rc = S_OK;
1218
1219 /* Did we get some status? */
1220 switch (pExecStatus->u32Status)
1221 {
1222 case PROC_STS_STARTED:
1223 /* Process is (still) running; get PID. */
1224 *puPID = pExecStatus->u32PID;
1225 break;
1226
1227 /* In any other case the process either already
1228 * terminated or something else went wrong, so no PID ... */
1229 case PROC_STS_TEN: /* Terminated normally. */
1230 case PROC_STS_TEA: /* Terminated abnormally. */
1231 case PROC_STS_TES: /* Terminated through signal. */
1232 case PROC_STS_TOK:
1233 case PROC_STS_TOA:
1234 case PROC_STS_DWN:
1235 /*
1236 * Process (already) ended, but we want to get the
1237 * PID anyway to retrieve the output in a later call.
1238 */
1239 *puPID = pExecStatus->u32PID;
1240 break;
1241
1242 case PROC_STS_ERROR:
1243 {
1244 int vrc = pExecStatus->u32Flags; /* u32Flags member contains IPRT error code. */
1245 if (vrc == VERR_FILE_NOT_FOUND) /* This is the most likely error. */
1246 rc = setErrorNoLog(VBOX_E_IPRT_ERROR,
1247 tr("The file '%s' was not found on guest"), pszCommand);
1248 else if (vrc == VERR_PATH_NOT_FOUND)
1249 rc = setErrorNoLog(VBOX_E_IPRT_ERROR,
1250 tr("The path to file '%s' was not found on guest"), pszCommand);
1251 else if (vrc == VERR_BAD_EXE_FORMAT)
1252 rc = setErrorNoLog(VBOX_E_IPRT_ERROR,
1253 tr("The file '%s' is not an executable format on guest"), pszCommand);
1254 else if (vrc == VERR_AUTHENTICATION_FAILURE)
1255 rc = setErrorNoLog(VBOX_E_IPRT_ERROR,
1256 tr("The specified user '%s' was not able to logon on guest"), pszUser);
1257 else if (vrc == VERR_TIMEOUT)
1258 rc = setErrorNoLog(VBOX_E_IPRT_ERROR,
1259 tr("The guest did not respond within time (%ums)"), ulTimeout);
1260 else if (vrc == VERR_CANCELLED)
1261 rc = setErrorNoLog(VBOX_E_IPRT_ERROR,
1262 tr("The execution operation was canceled"));
1263 else if (vrc == VERR_PERMISSION_DENIED)
1264 rc = setErrorNoLog(VBOX_E_IPRT_ERROR,
1265 tr("Invalid user/password credentials"));
1266 else if (vrc == VERR_MAX_PROCS_REACHED)
1267 rc = setErrorNoLog(VBOX_E_IPRT_ERROR,
1268 tr("Concurrent guest process limit is reached"));
1269 else
1270 {
1271 if (pExecStatus && pExecStatus->u32Status == PROC_STS_ERROR)
1272 rc = setErrorNoLog(VBOX_E_IPRT_ERROR,
1273 tr("Process could not be started: %Rrc"), pExecStatus->u32Flags);
1274 else
1275 rc = setErrorNoLog(E_UNEXPECTED,
1276 tr("The service call failed with error %Rrc"), vrc);
1277 }
1278 }
1279 break;
1280
1281 case PROC_STS_UNDEFINED: /* . */
1282 rc = setErrorNoLog(VBOX_E_IPRT_ERROR,
1283 tr("The operation did not complete within time"));
1284 break;
1285
1286 default:
1287 AssertReleaseMsgFailed(("Process (PID %u) reported back an undefined state!\n",
1288 pExecStatus->u32PID));
1289 rc = E_UNEXPECTED;
1290 break;
1291 }
1292
1293 return rc;
1294}
1295
1296/**
1297 * TODO
1298 *
1299 * @return HRESULT
1300 * @param aObjName
1301 * @param pStreamBlock
1302 * @param pObjInfo
1303 * @param enmAddAttribs
1304 */
1305int Guest::executeStreamQueryFsObjInfo(IN_BSTR aObjName,
1306 GuestProcessStreamBlock &streamBlock,
1307 PRTFSOBJINFO pObjInfo,
1308 RTFSOBJATTRADD enmAddAttribs)
1309{
1310 Utf8Str Utf8ObjName(aObjName);
1311 int64_t iVal;
1312 int rc = streamBlock.GetInt64Ex("st_size", &iVal);
1313 if (RT_SUCCESS(rc))
1314 pObjInfo->cbObject = iVal;
1315 /** @todo Add more stuff! */
1316 return rc;
1317}
1318
1319/**
1320 * Tries to drain the guest's output and fill it into
1321 * a guest process stream object for later usage.
1322 *
1323 * @todo What's about specifying stderr?
1324 * @return IPRT status code.
1325 * @param aPID PID of process to get the output from.
1326 * @param aFlags Which stream to drain (stdout or stderr).
1327 * @param stream Reference to guest process stream to fill.
1328 */
1329int Guest::executeStreamDrain(ULONG aPID, ULONG aFlags, GuestProcessStream &stream)
1330{
1331 AssertReturn(aPID, VERR_INVALID_PARAMETER);
1332
1333 int rc = VINF_SUCCESS;
1334 for (;;)
1335 {
1336 SafeArray<BYTE> aData;
1337 HRESULT hr = getProcessOutputInternal(aPID, aFlags,
1338 0 /* Infinite timeout */,
1339 _64K, ComSafeArrayAsOutParam(aData), &rc);
1340 if (SUCCEEDED(hr))
1341 {
1342 if (aData.size())
1343 {
1344 rc = stream.AddData(aData.raw(), aData.size());
1345 if (RT_UNLIKELY(RT_FAILURE(rc)))
1346 break;
1347 }
1348
1349 continue; /* Try one more time. */
1350 }
1351 else /* No more output and/or error! */
1352 {
1353 if (rc == VERR_NOT_FOUND)
1354 rc = VINF_SUCCESS;
1355 break;
1356 }
1357 }
1358
1359 return rc;
1360}
1361
1362/**
1363 * Tries to retrieve the next stream block of a given stream and
1364 * drains the process output only as much as needed to get this next
1365 * stream block.
1366 *
1367 * @return IPRT status code.
1368 * @param ulPID
1369 * @param ulFlags
1370 * @param stream
1371 * @param streamBlock
1372 */
1373int Guest::executeStreamGetNextBlock(ULONG ulPID,
1374 ULONG ulFlags,
1375 GuestProcessStream &stream,
1376 GuestProcessStreamBlock &streamBlock)
1377{
1378 AssertReturn(!streamBlock.GetCount(), VERR_INVALID_PARAMETER);
1379
1380 LogFlowFunc(("Getting next stream block of PID=%u, Flags=%u; cbStrmSize=%u, cbStrmOff=%u\n",
1381 ulPID, ulFlags, stream.GetSize(), stream.GetOffset()));
1382
1383 int rc;
1384
1385 uint32_t cPairs = 0;
1386 bool fDrainStream = true;
1387
1388 do
1389 {
1390 rc = stream.ParseBlock(streamBlock);
1391 LogFlowFunc(("Parsing block rc=%Rrc, strmBlockCnt=%ld\n",
1392 rc, streamBlock.GetCount()));
1393
1394 if (RT_FAILURE(rc)) /* More data needed or empty buffer? */
1395 {
1396 if (fDrainStream)
1397 {
1398 SafeArray<BYTE> aData;
1399 HRESULT hr = getProcessOutputInternal(ulPID, ulFlags,
1400 0 /* Infinite timeout */,
1401 _64K, ComSafeArrayAsOutParam(aData), &rc);
1402 if (SUCCEEDED(hr))
1403 {
1404 LogFlowFunc(("Got %ld bytes of additional data\n", aData.size()));
1405
1406 if (aData.size())
1407 {
1408 rc = stream.AddData(aData.raw(), aData.size());
1409 if (RT_UNLIKELY(RT_FAILURE(rc)))
1410 break;
1411 }
1412
1413 /* Reset found pairs to not break out too early and let all the new
1414 * data to be parsed as well. */
1415 cPairs = 0;
1416 continue; /* Try one more time. */
1417 }
1418 else
1419 {
1420 LogFlowFunc(("Getting output returned hr=%Rhrc\n", hr));
1421
1422 /* No more output to drain from stream. */
1423 if (rc == VERR_NOT_FOUND)
1424 {
1425 fDrainStream = false;
1426 continue;
1427 }
1428
1429 break;
1430 }
1431 }
1432 else
1433 {
1434 /* We haved drained the stream as much as we can and reached the
1435 * end of our stream buffer -- that means that there simply is no
1436 * stream block anymore, which is ok. */
1437 if (rc == VERR_NO_DATA)
1438 rc = VINF_SUCCESS;
1439 break;
1440 }
1441 }
1442 else
1443 cPairs = streamBlock.GetCount();
1444 }
1445 while (!cPairs);
1446
1447 LogFlowFunc(("Returned with strmBlockCnt=%ld, cPairs=%ld, rc=%Rrc\n",
1448 streamBlock.GetCount(), cPairs, rc));
1449 return rc;
1450}
1451
1452/**
1453 * Tries to get the next upcoming value block from a started guest process
1454 * by first draining its output and then processing the received guest stream.
1455 *
1456 * @return IPRT status code.
1457 * @param ulPID PID of process to get/parse the output from.
1458 * @param ulFlags ?
1459 * @param stream Reference to process stream object to use.
1460 * @param streamBlock Reference that receives the next stream block data.
1461 *
1462 */
1463int Guest::executeStreamParseNextBlock(ULONG ulPID,
1464 ULONG ulFlags,
1465 GuestProcessStream &stream,
1466 GuestProcessStreamBlock &streamBlock)
1467{
1468 AssertReturn(!streamBlock.GetCount(), VERR_INVALID_PARAMETER);
1469
1470 int rc;
1471 do
1472 {
1473 rc = stream.ParseBlock(streamBlock);
1474 if (RT_FAILURE(rc))
1475 break;
1476 }
1477 while (!streamBlock.GetCount());
1478
1479 return rc;
1480}
1481
1482/**
1483 * Gets output from a formerly started guest process, tries to parse all of its guest
1484 * stream (as long as data is available) and returns a stream object which can contain
1485 * multiple stream blocks (which in turn then can contain key=value pairs).
1486 *
1487 * @return HRESULT
1488 * @param ulPID PID of process to get/parse the output from.
1489 * @param ulFlags ?
1490 * @param streamObjects Reference to a guest stream object structure for
1491 * storing the parsed data.
1492 */
1493HRESULT Guest::executeStreamParse(ULONG ulPID, ULONG ulFlags, GuestCtrlStreamObjects &streamObjects)
1494{
1495 GuestProcessStream stream;
1496 int rc = executeStreamDrain(ulPID, ulFlags, stream);
1497 if (RT_SUCCESS(rc))
1498 {
1499 do
1500 {
1501 /* Try to parse the stream output we gathered until now. If we still need more
1502 * data the parsing routine will tell us and we just do another poll round. */
1503 GuestProcessStreamBlock curBlock;
1504 rc = executeStreamParseNextBlock(ulPID, ulFlags, stream, curBlock);
1505 if (RT_SUCCESS(rc))
1506 streamObjects.push_back(curBlock);
1507 } while (RT_SUCCESS(rc));
1508
1509 if (rc == VERR_NO_DATA) /* End of data reached. */
1510 rc = VINF_SUCCESS;
1511 }
1512
1513 if (RT_FAILURE(rc))
1514 return setError(VBOX_E_IPRT_ERROR,
1515 tr("Error while parsing guest output (%Rrc)"), rc);
1516 return rc;
1517}
1518
1519/**
1520 * Waits for a fomerly started guest process to exit using its progress
1521 * object and returns its final status. Returns E_ABORT if guest process
1522 * was canceled.
1523 *
1524 * @return IPRT status code.
1525 * @param uPID PID of guest process to wait for.
1526 * @param pProgress Progress object to wait for.
1527 * @param uTimeoutMS Timeout (in ms) for waiting; use 0 for
1528 * an indefinite timeout.
1529 * @param pRetStatus Pointer where to store the final process
1530 * status. Optional.
1531 * @param puRetExitCode Pointer where to store the final process
1532 * exit code. Optional.
1533 */
1534HRESULT Guest::executeWaitForExit(ULONG uPID, ComPtr<IProgress> pProgress, ULONG uTimeoutMS,
1535 ExecuteProcessStatus_T *pRetStatus, ULONG *puRetExitCode)
1536{
1537 HRESULT rc = S_OK;
1538
1539 BOOL fCanceled = FALSE;
1540 if ( SUCCEEDED(pProgress->COMGETTER(Canceled(&fCanceled)))
1541 && fCanceled)
1542 {
1543 return E_ABORT;
1544 }
1545
1546 BOOL fCompleted = FALSE;
1547 if ( SUCCEEDED(pProgress->COMGETTER(Completed(&fCompleted)))
1548 && !fCompleted)
1549 {
1550 rc = pProgress->WaitForCompletion( !uTimeoutMS
1551 ? -1 /* No timeout */
1552 : uTimeoutMS);
1553 if (FAILED(rc))
1554 rc = setError(VBOX_E_IPRT_ERROR,
1555 tr("Waiting for guest process to end failed (%Rhrc)"),
1556 rc);
1557 }
1558
1559 if (SUCCEEDED(rc))
1560 {
1561 ULONG uExitCode, uRetFlags;
1562 ExecuteProcessStatus_T enmStatus;
1563 HRESULT hRC = GetProcessStatus(uPID, &uExitCode, &uRetFlags, &enmStatus);
1564 if (FAILED(hRC))
1565 return hRC;
1566
1567 if (pRetStatus)
1568 *pRetStatus = enmStatus;
1569 if (puRetExitCode)
1570 *puRetExitCode = uExitCode;
1571 /** @todo Flags? */
1572 }
1573
1574 return rc;
1575}
1576
1577/**
1578 * Does the actual guest process execution, internal function.
1579 *
1580 * @return HRESULT
1581 * @param aCommand Command line to execute.
1582 * @param aFlags Execution flags.
1583 * @param Username Username to execute the process with.
1584 * @param aPassword The user's password.
1585 * @param aTimeoutMS Timeout (in ms) to wait for the execution operation.
1586 * @param aPID Pointer that receives the guest process' PID.
1587 * @param aProgress Pointer that receives the guest process' progress object.
1588 * @param pRC Pointer that receives the internal IPRT return code. Optional.
1589 */
1590HRESULT Guest::executeProcessInternal(IN_BSTR aCommand, ULONG aFlags,
1591 ComSafeArrayIn(IN_BSTR, aArguments), ComSafeArrayIn(IN_BSTR, aEnvironment),
1592 IN_BSTR aUsername, IN_BSTR aPassword,
1593 ULONG aTimeoutMS, ULONG *aPID, IProgress **aProgress, int *pRC)
1594{
1595/** @todo r=bird: Eventually we should clean up all the timeout parameters
1596 * in the API and have the same way of specifying infinite waits! */
1597 using namespace guestControl;
1598
1599 AutoCaller autoCaller(this);
1600 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1601
1602 /* Validate flags. */
1603 if (aFlags != ExecuteProcessFlag_None)
1604 {
1605 if ( !(aFlags & ExecuteProcessFlag_IgnoreOrphanedProcesses)
1606 && !(aFlags & ExecuteProcessFlag_WaitForProcessStartOnly)
1607 && !(aFlags & ExecuteProcessFlag_Hidden)
1608 && !(aFlags & ExecuteProcessFlag_NoProfile)
1609 && !(aFlags & ExecuteProcessFlag_WaitForStdOut)
1610 && !(aFlags & ExecuteProcessFlag_WaitForStdErr))
1611 {
1612 if (pRC)
1613 *pRC = VERR_INVALID_PARAMETER;
1614 return setError(E_INVALIDARG, tr("Unknown flags (%#x)"), aFlags);
1615 }
1616 }
1617
1618 HRESULT rc = S_OK;
1619
1620 try
1621 {
1622 /*
1623 * Create progress object. Note that this is a multi operation
1624 * object to perform the following steps:
1625 * - Operation 1 (0): Create/start process.
1626 * - Operation 2 (1): Wait for process to exit.
1627 * If this progress completed successfully (S_OK), the process
1628 * started and exited normally. In any other case an error/exception
1629 * occurred.
1630 */
1631 ComObjPtr <Progress> pProgress;
1632 rc = pProgress.createObject();
1633 if (SUCCEEDED(rc))
1634 {
1635 rc = pProgress->init(static_cast<IGuest*>(this),
1636 Bstr(tr("Executing process")).raw(),
1637 TRUE,
1638 2, /* Number of operations. */
1639 Bstr(tr("Starting process ...")).raw()); /* Description of first stage. */
1640 }
1641 ComAssertComRC(rc);
1642
1643 /*
1644 * Prepare process execution.
1645 */
1646 int vrc = VINF_SUCCESS;
1647 Utf8Str Utf8Command(aCommand);
1648
1649 /* Adjust timeout. If set to 0, we define
1650 * an infinite timeout. */
1651 if (aTimeoutMS == 0)
1652 aTimeoutMS = UINT32_MAX;
1653
1654 /* Prepare arguments. */
1655 char **papszArgv = NULL;
1656 uint32_t uNumArgs = 0;
1657 if (aArguments)
1658 {
1659 com::SafeArray<IN_BSTR> args(ComSafeArrayInArg(aArguments));
1660 uNumArgs = args.size();
1661 papszArgv = (char**)RTMemAlloc(sizeof(char*) * (uNumArgs + 1));
1662 AssertReturn(papszArgv, E_OUTOFMEMORY);
1663 for (unsigned i = 0; RT_SUCCESS(vrc) && i < uNumArgs; i++)
1664 vrc = RTUtf16ToUtf8(args[i], &papszArgv[i]);
1665 papszArgv[uNumArgs] = NULL;
1666 }
1667
1668 Utf8Str Utf8UserName(aUsername);
1669 Utf8Str Utf8Password(aPassword);
1670 if (RT_SUCCESS(vrc))
1671 {
1672 uint32_t uContextID = 0;
1673
1674 char *pszArgs = NULL;
1675 if (uNumArgs > 0)
1676 vrc = RTGetOptArgvToString(&pszArgs, papszArgv, RTGETOPTARGV_CNV_QUOTE_MS_CRT);
1677 if (RT_SUCCESS(vrc))
1678 {
1679 uint32_t cbArgs = pszArgs ? strlen(pszArgs) + 1 : 0; /* Include terminating zero. */
1680
1681 /* Prepare environment. */
1682 void *pvEnv = NULL;
1683 uint32_t uNumEnv = 0;
1684 uint32_t cbEnv = 0;
1685 if (aEnvironment)
1686 {
1687 com::SafeArray<IN_BSTR> env(ComSafeArrayInArg(aEnvironment));
1688
1689 for (unsigned i = 0; i < env.size(); i++)
1690 {
1691 vrc = prepareExecuteEnv(Utf8Str(env[i]).c_str(), &pvEnv, &cbEnv, &uNumEnv);
1692 if (RT_FAILURE(vrc))
1693 break;
1694 }
1695 }
1696
1697 if (RT_SUCCESS(vrc))
1698 {
1699 VBOXGUESTCTRL_CALLBACK callback;
1700 vrc = callbackInit(&callback, VBOXGUESTCTRLCALLBACKTYPE_EXEC_START, pProgress);
1701 if (RT_SUCCESS(vrc))
1702 {
1703 /* Allocate and assign payload. */
1704 callback.cbData = sizeof(CALLBACKDATAEXECSTATUS);
1705 PCALLBACKDATAEXECSTATUS pData = (PCALLBACKDATAEXECSTATUS)RTMemAlloc(callback.cbData);
1706 AssertReturn(pData, E_OUTOFMEMORY);
1707 RT_BZERO(pData, callback.cbData);
1708 callback.pvData = pData;
1709 }
1710
1711 if (RT_SUCCESS(vrc))
1712 vrc = callbackAdd(&callback, &uContextID);
1713
1714 if (RT_SUCCESS(vrc))
1715 {
1716 VBOXHGCMSVCPARM paParms[15];
1717 int i = 0;
1718 paParms[i++].setUInt32(uContextID);
1719 paParms[i++].setPointer((void*)Utf8Command.c_str(), (uint32_t)Utf8Command.length() + 1);
1720 paParms[i++].setUInt32(aFlags);
1721 paParms[i++].setUInt32(uNumArgs);
1722 paParms[i++].setPointer((void*)pszArgs, cbArgs);
1723 paParms[i++].setUInt32(uNumEnv);
1724 paParms[i++].setUInt32(cbEnv);
1725 paParms[i++].setPointer((void*)pvEnv, cbEnv);
1726 paParms[i++].setPointer((void*)Utf8UserName.c_str(), (uint32_t)Utf8UserName.length() + 1);
1727 paParms[i++].setPointer((void*)Utf8Password.c_str(), (uint32_t)Utf8Password.length() + 1);
1728
1729 /*
1730 * If the WaitForProcessStartOnly flag is set, we only want to define and wait for a timeout
1731 * until the process was started - the process itself then gets an infinite timeout for execution.
1732 * This is handy when we want to start a process inside a worker thread within a certain timeout
1733 * but let the started process perform lengthly operations then.
1734 */
1735 if (aFlags & ExecuteProcessFlag_WaitForProcessStartOnly)
1736 paParms[i++].setUInt32(UINT32_MAX /* Infinite timeout */);
1737 else
1738 paParms[i++].setUInt32(aTimeoutMS);
1739
1740 VMMDev *pVMMDev = NULL;
1741 {
1742 /* Make sure mParent is valid, so set the read lock while using.
1743 * Do not keep this lock while doing the actual call, because in the meanwhile
1744 * another thread could request a write lock which would be a bad idea ... */
1745 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1746
1747 /* Forward the information to the VMM device. */
1748 AssertPtr(mParent);
1749 pVMMDev = mParent->getVMMDev();
1750 }
1751
1752 if (pVMMDev)
1753 {
1754 LogFlowFunc(("hgcmHostCall numParms=%d\n", i));
1755 vrc = pVMMDev->hgcmHostCall("VBoxGuestControlSvc", HOST_EXEC_CMD,
1756 i, paParms);
1757 }
1758 else
1759 vrc = VERR_INVALID_VM_HANDLE;
1760 }
1761 RTMemFree(pvEnv);
1762 }
1763 RTStrFree(pszArgs);
1764 }
1765
1766 if (RT_SUCCESS(vrc))
1767 {
1768 LogFlowFunc(("Waiting for HGCM callback (timeout=%RI32ms) ...\n", aTimeoutMS));
1769
1770 /*
1771 * Wait for the HGCM low level callback until the process
1772 * has been started (or something went wrong). This is necessary to
1773 * get the PID.
1774 */
1775
1776 PCALLBACKDATAEXECSTATUS pExecStatus = NULL;
1777
1778 /*
1779 * Wait for the first stage (=0) to complete (that is starting the process).
1780 */
1781 vrc = callbackWaitForCompletion(uContextID, 0 /* Stage */, aTimeoutMS);
1782 if (RT_SUCCESS(vrc))
1783 {
1784 vrc = callbackGetUserData(uContextID, NULL /* We know the type. */,
1785 (void**)&pExecStatus, NULL /* Don't need the size. */);
1786 if (RT_SUCCESS(vrc))
1787 {
1788 rc = executeProcessResult(Utf8Command.c_str(), Utf8UserName.c_str(), aTimeoutMS,
1789 pExecStatus, aPID);
1790 callbackFreeUserData(pExecStatus);
1791 }
1792 else
1793 {
1794 rc = setErrorNoLog(VBOX_E_IPRT_ERROR,
1795 tr("Unable to retrieve process execution status data"));
1796 }
1797 }
1798 else
1799 rc = handleErrorCompletion(vrc);
1800
1801 /*
1802 * Do *not* remove the callback yet - we might wait with the IProgress object on something
1803 * else (like end of process) ...
1804 */
1805 }
1806 else
1807 rc = handleErrorHGCM(vrc);
1808
1809 for (unsigned i = 0; i < uNumArgs; i++)
1810 RTMemFree(papszArgv[i]);
1811 RTMemFree(papszArgv);
1812 }
1813
1814 if (SUCCEEDED(rc))
1815 {
1816 /* Return the progress to the caller. */
1817 pProgress.queryInterfaceTo(aProgress);
1818 }
1819 else
1820 {
1821 if (!pRC) /* Skip logging internal calls. */
1822 LogRel(("Executing guest process \"%s\" as user \"%s\" failed with %Rrc\n",
1823 Utf8Command.c_str(), Utf8UserName.c_str(), vrc));
1824 }
1825
1826 if (pRC)
1827 *pRC = vrc;
1828 }
1829 catch (std::bad_alloc &)
1830 {
1831 rc = E_OUTOFMEMORY;
1832 }
1833 return rc;
1834}
1835#endif /* VBOX_WITH_GUEST_CONTROL */
1836
1837STDMETHODIMP Guest::SetProcessInput(ULONG aPID, ULONG aFlags, ULONG aTimeoutMS, ComSafeArrayIn(BYTE, aData), ULONG *aBytesWritten)
1838{
1839#ifndef VBOX_WITH_GUEST_CONTROL
1840 ReturnComNotImplemented();
1841#else /* VBOX_WITH_GUEST_CONTROL */
1842 using namespace guestControl;
1843
1844 CheckComArgExpr(aPID, aPID > 0);
1845 CheckComArgOutPointerValid(aBytesWritten);
1846
1847 /* Validate flags. */
1848 if (aFlags)
1849 {
1850 if (!(aFlags & ProcessInputFlag_EndOfFile))
1851 return setError(E_INVALIDARG, tr("Unknown flags (%#x)"), aFlags);
1852 }
1853
1854 AutoCaller autoCaller(this);
1855 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1856
1857 HRESULT rc = S_OK;
1858
1859 try
1860 {
1861 VBOXGUESTCTRL_PROCESS process;
1862 int vrc = processGetStatus(aPID, &process);
1863 if (RT_SUCCESS(vrc))
1864 {
1865 /* PID exists; check if process is still running. */
1866 if (process.mStatus != ExecuteProcessStatus_Started)
1867 rc = setError(VBOX_E_IPRT_ERROR,
1868 Guest::tr("Cannot inject input to not running process (PID %u)"), aPID);
1869 }
1870 else
1871 rc = setError(VBOX_E_IPRT_ERROR,
1872 Guest::tr("Cannot inject input to non-existent process (PID %u)"), aPID);
1873
1874 if (RT_SUCCESS(vrc))
1875 {
1876 uint32_t uContextID = 0;
1877
1878 /*
1879 * Create progress object.
1880 * This progress object, compared to the one in executeProgress() above,
1881 * is only single-stage local and is used to determine whether the operation
1882 * finished or got canceled.
1883 */
1884 ComObjPtr <Progress> pProgress;
1885 rc = pProgress.createObject();
1886 if (SUCCEEDED(rc))
1887 {
1888 rc = pProgress->init(static_cast<IGuest*>(this),
1889 Bstr(tr("Setting input for process")).raw(),
1890 TRUE /* Cancelable */);
1891 }
1892 if (FAILED(rc)) throw rc;
1893 ComAssert(!pProgress.isNull());
1894
1895 /* Adjust timeout. */
1896 if (aTimeoutMS == 0)
1897 aTimeoutMS = UINT32_MAX;
1898
1899 VBOXGUESTCTRL_CALLBACK callback;
1900 vrc = callbackInit(&callback, VBOXGUESTCTRLCALLBACKTYPE_EXEC_INPUT_STATUS, pProgress);
1901 if (RT_SUCCESS(vrc))
1902 {
1903 PCALLBACKDATAEXECINSTATUS pData = (PCALLBACKDATAEXECINSTATUS)callback.pvData;
1904
1905 /* Save PID + output flags for later use. */
1906 pData->u32PID = aPID;
1907 pData->u32Flags = aFlags;
1908 }
1909
1910 if (RT_SUCCESS(vrc))
1911 vrc = callbackAdd(&callback, &uContextID);
1912
1913 if (RT_SUCCESS(vrc))
1914 {
1915 com::SafeArray<BYTE> sfaData(ComSafeArrayInArg(aData));
1916 uint32_t cbSize = sfaData.size();
1917
1918 VBOXHGCMSVCPARM paParms[6];
1919 int i = 0;
1920 paParms[i++].setUInt32(uContextID);
1921 paParms[i++].setUInt32(aPID);
1922 paParms[i++].setUInt32(aFlags);
1923 paParms[i++].setPointer(sfaData.raw(), cbSize);
1924 paParms[i++].setUInt32(cbSize);
1925
1926 {
1927 VMMDev *pVMMDev = NULL;
1928 {
1929 /* Make sure mParent is valid, so set the read lock while using.
1930 * Do not keep this lock while doing the actual call, because in the meanwhile
1931 * another thread could request a write lock which would be a bad idea ... */
1932 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1933
1934 /* Forward the information to the VMM device. */
1935 AssertPtr(mParent);
1936 pVMMDev = mParent->getVMMDev();
1937 }
1938
1939 if (pVMMDev)
1940 {
1941 LogFlowFunc(("hgcmHostCall numParms=%d\n", i));
1942 vrc = pVMMDev->hgcmHostCall("VBoxGuestControlSvc", HOST_EXEC_SET_INPUT,
1943 i, paParms);
1944 if (RT_FAILURE(vrc))
1945 rc = handleErrorHGCM(vrc);
1946 }
1947 }
1948 }
1949
1950 if (RT_SUCCESS(vrc))
1951 {
1952 LogFlowFunc(("Waiting for HGCM callback ...\n"));
1953
1954 /*
1955 * Wait for getting back the input response from the guest.
1956 */
1957 vrc = callbackWaitForCompletion(uContextID, -1 /* No staging required */, aTimeoutMS);
1958 if (RT_SUCCESS(vrc))
1959 {
1960 PCALLBACKDATAEXECINSTATUS pExecStatusIn;
1961 vrc = callbackGetUserData(uContextID, NULL /* We know the type. */,
1962 (void**)&pExecStatusIn, NULL /* Don't need the size. */);
1963 if (RT_SUCCESS(vrc))
1964 {
1965 AssertPtr(pExecStatusIn);
1966 switch (pExecStatusIn->u32Status)
1967 {
1968 case INPUT_STS_WRITTEN:
1969 *aBytesWritten = pExecStatusIn->cbProcessed;
1970 break;
1971
1972 case INPUT_STS_ERROR:
1973 rc = setError(VBOX_E_IPRT_ERROR,
1974 tr("Client reported error %Rrc while processing input data"),
1975 pExecStatusIn->u32Flags);
1976 break;
1977
1978 case INPUT_STS_TERMINATED:
1979 rc = setError(VBOX_E_IPRT_ERROR,
1980 tr("Client terminated while processing input data"));
1981 break;
1982
1983 case INPUT_STS_OVERFLOW:
1984 rc = setError(VBOX_E_IPRT_ERROR,
1985 tr("Client reported buffer overflow while processing input data"));
1986 break;
1987
1988 default:
1989 /*AssertReleaseMsgFailed(("Client reported unknown input error, status=%u, flags=%u\n",
1990 pExecStatusIn->u32Status, pExecStatusIn->u32Flags));*/
1991 break;
1992 }
1993
1994 callbackFreeUserData(pExecStatusIn);
1995 }
1996 else
1997 {
1998 rc = setErrorNoLog(VBOX_E_IPRT_ERROR,
1999 tr("Unable to retrieve process input status data"));
2000 }
2001 }
2002 else
2003 rc = handleErrorCompletion(vrc);
2004 }
2005
2006 /* The callback isn't needed anymore -- just was kept locally. */
2007 callbackDestroy(uContextID);
2008
2009 /* Cleanup. */
2010 if (!pProgress.isNull())
2011 pProgress->uninit();
2012 pProgress.setNull();
2013 }
2014 }
2015 catch (std::bad_alloc &)
2016 {
2017 rc = E_OUTOFMEMORY;
2018 }
2019 return rc;
2020#endif
2021}
2022
2023STDMETHODIMP Guest::GetProcessOutput(ULONG aPID, ULONG aFlags, ULONG aTimeoutMS, LONG64 aSize, ComSafeArrayOut(BYTE, aData))
2024{
2025#ifndef VBOX_WITH_GUEST_CONTROL
2026 ReturnComNotImplemented();
2027#else /* VBOX_WITH_GUEST_CONTROL */
2028 using namespace guestControl;
2029
2030 return getProcessOutputInternal(aPID, aFlags, aTimeoutMS,
2031 aSize, ComSafeArrayOutArg(aData), NULL /* rc */);
2032#endif
2033}
2034
2035HRESULT Guest::getProcessOutputInternal(ULONG aPID, ULONG aFlags, ULONG aTimeoutMS,
2036 LONG64 aSize, ComSafeArrayOut(BYTE, aData), int *pRC)
2037{
2038/** @todo r=bird: Eventually we should clean up all the timeout parameters
2039 * in the API and have the same way of specifying infinite waits! */
2040#ifndef VBOX_WITH_GUEST_CONTROL
2041 ReturnComNotImplemented();
2042#else /* VBOX_WITH_GUEST_CONTROL */
2043 using namespace guestControl;
2044
2045 CheckComArgExpr(aPID, aPID > 0);
2046 if (aSize < 0)
2047 return setError(E_INVALIDARG, tr("The size argument (%lld) is negative"), aSize);
2048 if (aSize == 0)
2049 return setError(E_INVALIDARG, tr("The size (%lld) is zero"), aSize);
2050 if (aFlags)
2051 {
2052 if (!(aFlags & ProcessOutputFlag_StdErr))
2053 {
2054 return setError(E_INVALIDARG, tr("Unknown flags (%#x)"), aFlags);
2055 }
2056 }
2057
2058 AutoCaller autoCaller(this);
2059 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2060
2061 HRESULT rc = S_OK;
2062
2063 try
2064 {
2065 VBOXGUESTCTRL_PROCESS proc;
2066 int vrc = processGetStatus(aPID, &proc);
2067 if (RT_FAILURE(vrc))
2068 {
2069 rc = setError(VBOX_E_IPRT_ERROR,
2070 Guest::tr("Guest process (PID %u) does not exist"), aPID);
2071 }
2072 else
2073 {
2074 uint32_t uContextID = 0;
2075
2076 /*
2077 * Create progress object.
2078 * This progress object, compared to the one in executeProgress() above,
2079 * is only single-stage local and is used to determine whether the operation
2080 * finished or got canceled.
2081 */
2082 ComObjPtr <Progress> pProgress;
2083 rc = pProgress.createObject();
2084 if (SUCCEEDED(rc))
2085 {
2086 rc = pProgress->init(static_cast<IGuest*>(this),
2087 Bstr(tr("Getting output for guest process")).raw(),
2088 TRUE /* Cancelable */);
2089 }
2090 if (FAILED(rc)) throw rc;
2091 ComAssert(!pProgress.isNull());
2092
2093 /* Adjust timeout. */
2094 if (aTimeoutMS == 0)
2095 aTimeoutMS = UINT32_MAX;
2096
2097 /* Set handle ID. */
2098 uint32_t uHandleID = OUTPUT_HANDLE_ID_STDOUT; /* Default */
2099 if (aFlags & ProcessOutputFlag_StdErr)
2100 uHandleID = OUTPUT_HANDLE_ID_STDERR;
2101
2102 VBOXGUESTCTRL_CALLBACK callback;
2103 vrc = callbackInit(&callback, VBOXGUESTCTRLCALLBACKTYPE_EXEC_OUTPUT, pProgress);
2104 if (RT_SUCCESS(vrc))
2105 {
2106 PCALLBACKDATAEXECOUT pData = (PCALLBACKDATAEXECOUT)callback.pvData;
2107
2108 /* Save PID + output flags for later use. */
2109 pData->u32PID = aPID;
2110 pData->u32Flags = aFlags;
2111 }
2112
2113 if (RT_SUCCESS(vrc))
2114 vrc = callbackAdd(&callback, &uContextID);
2115
2116 if (RT_SUCCESS(vrc))
2117 {
2118 VBOXHGCMSVCPARM paParms[5];
2119 int i = 0;
2120 paParms[i++].setUInt32(uContextID);
2121 paParms[i++].setUInt32(aPID);
2122 paParms[i++].setUInt32(uHandleID);
2123 paParms[i++].setUInt32(0 /* Flags, none set yet */);
2124
2125 VMMDev *pVMMDev = NULL;
2126 {
2127 /* Make sure mParent is valid, so set the read lock while using.
2128 * Do not keep this lock while doing the actual call, because in the meanwhile
2129 * another thread could request a write lock which would be a bad idea ... */
2130 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2131
2132 /* Forward the information to the VMM device. */
2133 AssertPtr(mParent);
2134 pVMMDev = mParent->getVMMDev();
2135 }
2136
2137 if (pVMMDev)
2138 {
2139 LogFlowFunc(("hgcmHostCall numParms=%d\n", i));
2140 vrc = pVMMDev->hgcmHostCall("VBoxGuestControlSvc", HOST_EXEC_GET_OUTPUT,
2141 i, paParms);
2142 }
2143 }
2144
2145 if (RT_SUCCESS(vrc))
2146 {
2147 LogFlowFunc(("Waiting for HGCM callback (timeout=%RI32ms) ...\n", aTimeoutMS));
2148
2149 /*
2150 * Wait for the HGCM low level callback until the process
2151 * has been started (or something went wrong). This is necessary to
2152 * get the PID.
2153 */
2154
2155 /*
2156 * Wait for the first output callback notification to arrive.
2157 */
2158 vrc = callbackWaitForCompletion(uContextID, -1 /* No staging required */, aTimeoutMS);
2159 if (RT_SUCCESS(vrc))
2160 {
2161 PCALLBACKDATAEXECOUT pExecOut = NULL;
2162 vrc = callbackGetUserData(uContextID, NULL /* We know the type. */,
2163 (void**)&pExecOut, NULL /* Don't need the size. */);
2164 if (RT_SUCCESS(vrc))
2165 {
2166 com::SafeArray<BYTE> outputData((size_t)aSize);
2167
2168 if (pExecOut->cbData)
2169 {
2170 /* Do we need to resize the array? */
2171 if (pExecOut->cbData > aSize)
2172 outputData.resize(pExecOut->cbData);
2173
2174 /* Fill output in supplied out buffer. */
2175 memcpy(outputData.raw(), pExecOut->pvData, pExecOut->cbData);
2176 outputData.resize(pExecOut->cbData); /* Shrink to fit actual buffer size. */
2177 }
2178 else
2179 {
2180 /* No data within specified timeout available. */
2181 outputData.resize(0);
2182 }
2183
2184 /* Detach output buffer to output argument. */
2185 outputData.detachTo(ComSafeArrayOutArg(aData));
2186
2187 callbackFreeUserData(pExecOut);
2188 }
2189 else
2190 {
2191 rc = setErrorNoLog(VBOX_E_IPRT_ERROR,
2192 tr("Unable to retrieve process output data (%Rrc)"), vrc);
2193 }
2194 }
2195 else
2196 rc = handleErrorCompletion(vrc);
2197 }
2198 else
2199 rc = handleErrorHGCM(vrc);
2200
2201 /* The callback isn't needed anymore -- just was kept locally. */
2202 callbackDestroy(uContextID);
2203
2204 /* Cleanup. */
2205 if (!pProgress.isNull())
2206 pProgress->uninit();
2207 pProgress.setNull();
2208 }
2209
2210 if (pRC)
2211 *pRC = vrc;
2212 }
2213 catch (std::bad_alloc &)
2214 {
2215 rc = E_OUTOFMEMORY;
2216 }
2217 return rc;
2218#endif
2219}
2220
2221STDMETHODIMP Guest::GetProcessStatus(ULONG aPID, ULONG *aExitCode, ULONG *aFlags, ExecuteProcessStatus_T *aStatus)
2222{
2223#ifndef VBOX_WITH_GUEST_CONTROL
2224 ReturnComNotImplemented();
2225#else /* VBOX_WITH_GUEST_CONTROL */
2226
2227 AutoCaller autoCaller(this);
2228 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2229
2230 HRESULT rc = S_OK;
2231
2232 try
2233 {
2234 VBOXGUESTCTRL_PROCESS process;
2235 int vrc = processGetStatus(aPID, &process);
2236 if (RT_SUCCESS(vrc))
2237 {
2238 if (aExitCode)
2239 *aExitCode = process.mExitCode;
2240 if (aFlags)
2241 *aFlags = process.mFlags;
2242 if (aStatus)
2243 *aStatus = process.mStatus;
2244 }
2245 else
2246 rc = setError(VBOX_E_IPRT_ERROR,
2247 tr("Process (PID %u) not found!"), aPID);
2248 }
2249 catch (std::bad_alloc &)
2250 {
2251 rc = E_OUTOFMEMORY;
2252 }
2253 return rc;
2254#endif
2255}
2256
2257STDMETHODIMP Guest::CopyFromGuest(IN_BSTR aSource, IN_BSTR aDest,
2258 IN_BSTR aUsername, IN_BSTR aPassword,
2259 ULONG aFlags, IProgress **aProgress)
2260{
2261#ifndef VBOX_WITH_GUEST_CONTROL
2262 ReturnComNotImplemented();
2263#else /* VBOX_WITH_GUEST_CONTROL */
2264 CheckComArgStrNotEmptyOrNull(aSource);
2265 CheckComArgStrNotEmptyOrNull(aDest);
2266 CheckComArgOutPointerValid(aProgress);
2267
2268 /* Do not allow anonymous executions (with system rights). */
2269 if (RT_UNLIKELY((aUsername) == NULL || *(aUsername) == '\0'))
2270 return setError(E_INVALIDARG, tr("No user name specified"));
2271
2272 AutoCaller autoCaller(this);
2273 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2274
2275 /* Validate flags. */
2276 if (aFlags != CopyFileFlag_None)
2277 {
2278 if ( !(aFlags & CopyFileFlag_Recursive)
2279 && !(aFlags & CopyFileFlag_Update)
2280 && !(aFlags & CopyFileFlag_FollowLinks))
2281 {
2282 return setError(E_INVALIDARG, tr("Unknown flags (%#x)"), aFlags);
2283 }
2284 }
2285
2286 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2287
2288 HRESULT rc = S_OK;
2289
2290 ComObjPtr<Progress> progress;
2291 try
2292 {
2293 /* Create the progress object. */
2294 progress.createObject();
2295
2296 rc = progress->init(static_cast<IGuest*>(this),
2297 Bstr(tr("Copying file from guest to host")).raw(),
2298 TRUE /* aCancelable */);
2299 if (FAILED(rc)) throw rc;
2300
2301 /* Initialize our worker task. */
2302 GuestTask *pTask = new GuestTask(GuestTask::TaskType_CopyFileFromGuest, this, progress);
2303 AssertPtr(pTask);
2304 std::auto_ptr<GuestTask> task(pTask);
2305
2306 /* Assign data - aSource is the source file on the host,
2307 * aDest reflects the full path on the guest. */
2308 task->strSource = (Utf8Str(aSource));
2309 task->strDest = (Utf8Str(aDest));
2310 task->strUserName = (Utf8Str(aUsername));
2311 task->strPassword = (Utf8Str(aPassword));
2312 task->uFlags = aFlags;
2313
2314 rc = task->startThread();
2315 if (FAILED(rc)) throw rc;
2316
2317 /* Don't destruct on success. */
2318 task.release();
2319 }
2320 catch (HRESULT aRC)
2321 {
2322 rc = aRC;
2323 }
2324
2325 if (SUCCEEDED(rc))
2326 {
2327 /* Return progress to the caller. */
2328 progress.queryInterfaceTo(aProgress);
2329 }
2330 return rc;
2331#endif /* VBOX_WITH_GUEST_CONTROL */
2332}
2333
2334STDMETHODIMP Guest::CopyToGuest(IN_BSTR aSource, IN_BSTR aDest,
2335 IN_BSTR aUsername, IN_BSTR aPassword,
2336 ULONG aFlags, IProgress **aProgress)
2337{
2338#ifndef VBOX_WITH_GUEST_CONTROL
2339 ReturnComNotImplemented();
2340#else /* VBOX_WITH_GUEST_CONTROL */
2341 CheckComArgStrNotEmptyOrNull(aSource);
2342 CheckComArgStrNotEmptyOrNull(aDest);
2343 CheckComArgOutPointerValid(aProgress);
2344
2345 /* Do not allow anonymous executions (with system rights). */
2346 if (RT_UNLIKELY((aUsername) == NULL || *(aUsername) == '\0'))
2347 return setError(E_INVALIDARG, tr("No user name specified"));
2348
2349 AutoCaller autoCaller(this);
2350 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2351
2352 /* Validate flags. */
2353 if (aFlags != CopyFileFlag_None)
2354 {
2355 if ( !(aFlags & CopyFileFlag_Recursive)
2356 && !(aFlags & CopyFileFlag_Update)
2357 && !(aFlags & CopyFileFlag_FollowLinks))
2358 {
2359 return setError(E_INVALIDARG, tr("Unknown flags (%#x)"), aFlags);
2360 }
2361 }
2362
2363 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2364
2365 HRESULT rc = S_OK;
2366
2367 ComObjPtr<Progress> progress;
2368 try
2369 {
2370 /* Create the progress object. */
2371 progress.createObject();
2372
2373 rc = progress->init(static_cast<IGuest*>(this),
2374 Bstr(tr("Copying file from host to guest")).raw(),
2375 TRUE /* aCancelable */);
2376 if (FAILED(rc)) throw rc;
2377
2378 /* Initialize our worker task. */
2379 GuestTask *pTask = new GuestTask(GuestTask::TaskType_CopyFileToGuest, this, progress);
2380 AssertPtr(pTask);
2381 std::auto_ptr<GuestTask> task(pTask);
2382
2383 /* Assign data - aSource is the source file on the host,
2384 * aDest reflects the full path on the guest. */
2385 task->strSource = (Utf8Str(aSource));
2386 task->strDest = (Utf8Str(aDest));
2387 task->strUserName = (Utf8Str(aUsername));
2388 task->strPassword = (Utf8Str(aPassword));
2389 task->uFlags = aFlags;
2390
2391 rc = task->startThread();
2392 if (FAILED(rc)) throw rc;
2393
2394 /* Don't destruct on success. */
2395 task.release();
2396 }
2397 catch (HRESULT aRC)
2398 {
2399 rc = aRC;
2400 }
2401
2402 if (SUCCEEDED(rc))
2403 {
2404 /* Return progress to the caller. */
2405 progress.queryInterfaceTo(aProgress);
2406 }
2407 return rc;
2408#endif /* VBOX_WITH_GUEST_CONTROL */
2409}
2410
2411STDMETHODIMP Guest::UpdateGuestAdditions(IN_BSTR aSource, ULONG aFlags, IProgress **aProgress)
2412{
2413#ifndef VBOX_WITH_GUEST_CONTROL
2414 ReturnComNotImplemented();
2415#else /* VBOX_WITH_GUEST_CONTROL */
2416 CheckComArgStrNotEmptyOrNull(aSource);
2417 CheckComArgOutPointerValid(aProgress);
2418
2419 AutoCaller autoCaller(this);
2420 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2421
2422 /* Validate flags. */
2423 if (aFlags)
2424 {
2425 if (!(aFlags & AdditionsUpdateFlag_WaitForUpdateStartOnly))
2426 return setError(E_INVALIDARG, tr("Unknown flags (%#x)"), aFlags);
2427 }
2428
2429 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2430
2431 HRESULT rc = S_OK;
2432
2433 ComObjPtr<Progress> progress;
2434 try
2435 {
2436 /* Create the progress object. */
2437 progress.createObject();
2438
2439 rc = progress->init(static_cast<IGuest*>(this),
2440 Bstr(tr("Updating Guest Additions")).raw(),
2441 TRUE /* aCancelable */);
2442 if (FAILED(rc)) throw rc;
2443
2444 /* Initialize our worker task. */
2445 GuestTask *pTask = new GuestTask(GuestTask::TaskType_UpdateGuestAdditions, this, progress);
2446 AssertPtr(pTask);
2447 std::auto_ptr<GuestTask> task(pTask);
2448
2449 /* Assign data - in that case aSource is the full path
2450 * to the Guest Additions .ISO we want to mount. */
2451 task->strSource = (Utf8Str(aSource));
2452 task->uFlags = aFlags;
2453
2454 rc = task->startThread();
2455 if (FAILED(rc)) throw rc;
2456
2457 /* Don't destruct on success. */
2458 task.release();
2459 }
2460 catch (HRESULT aRC)
2461 {
2462 rc = aRC;
2463 }
2464
2465 if (SUCCEEDED(rc))
2466 {
2467 /* Return progress to the caller. */
2468 progress.queryInterfaceTo(aProgress);
2469 }
2470 return rc;
2471#endif /* VBOX_WITH_GUEST_CONTROL */
2472}
2473
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