VirtualBox

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

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

GuestCtrl: More bugfixing.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 85.7 KB
Line 
1/* $Id: GuestCtrlImpl.cpp 39487 2011-12-01 10:58:19Z 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
1143 ULONG uFlags = ExecuteProcessFlag_Hidden
1144 | ExecuteProcessFlag_WaitForProcessStartOnly;
1145 if (uFlagsToAdd)
1146 uFlags |= uFlagsToAdd;
1147
1148 bool fWaitForOutput = false;
1149 if ( ( (uFlags & ExecuteProcessFlag_WaitForStdOut)
1150 && pObjStdOut)
1151 || ( (uFlags & ExecuteProcessFlag_WaitForStdErr)
1152 && pObjStdErr))
1153 {
1154 fWaitForOutput = true;
1155 }
1156
1157 HRESULT rc = ExecuteProcess(aTool,
1158 uFlags,
1159 ComSafeArrayInArg(aArguments),
1160 ComSafeArrayInArg(aEnvironment),
1161 aUsername, aPassword,
1162 0 /* No timeout. */,
1163 &uPID, progressTool.asOutParam());
1164 if ( SUCCEEDED(rc)
1165 && fWaitForOutput)
1166 {
1167 BOOL fCompleted;
1168 while ( SUCCEEDED(progressTool->COMGETTER(Completed)(&fCompleted))
1169 && !fCompleted)
1170 {
1171 BOOL fCanceled;
1172 rc = progressTool->COMGETTER(Canceled)(&fCanceled);
1173 AssertComRC(rc);
1174 if (fCanceled)
1175 {
1176 rc = setErrorNoLog(VBOX_E_IPRT_ERROR,
1177 tr("%s was cancelled"), Utf8Str(aDescription).c_str());
1178 break;
1179 }
1180
1181 if ( (uFlags & ExecuteProcessFlag_WaitForStdOut)
1182 && pObjStdOut)
1183 {
1184 rc = executeStreamParse(uPID, ProcessOutputFlag_None /* StdOut */, *pObjStdOut);
1185 }
1186
1187 if ( (uFlags & ExecuteProcessFlag_WaitForStdErr)
1188 && pObjStdErr)
1189 {
1190 rc = executeStreamParse(uPID, ProcessOutputFlag_StdErr, *pObjStdErr);
1191 }
1192
1193 if (FAILED(rc))
1194 break;
1195 }
1196 }
1197
1198 if (SUCCEEDED(rc))
1199 {
1200 if (aProgress)
1201 {
1202 /* Return the progress to the caller. */
1203 progressTool.queryInterfaceTo(aProgress);
1204 }
1205
1206 if (aPID)
1207 *aPID = uPID;
1208 }
1209
1210 return rc;
1211}
1212
1213HRESULT Guest::executeProcessResult(const char *pszCommand, const char *pszUser, ULONG ulTimeout,
1214 PCALLBACKDATAEXECSTATUS pExecStatus, ULONG *puPID)
1215{
1216 AssertPtrReturn(pExecStatus, E_INVALIDARG);
1217 AssertPtrReturn(puPID, E_INVALIDARG);
1218
1219 HRESULT rc = S_OK;
1220
1221 /* Did we get some status? */
1222 switch (pExecStatus->u32Status)
1223 {
1224 case PROC_STS_STARTED:
1225 /* Process is (still) running; get PID. */
1226 *puPID = pExecStatus->u32PID;
1227 break;
1228
1229 /* In any other case the process either already
1230 * terminated or something else went wrong, so no PID ... */
1231 case PROC_STS_TEN: /* Terminated normally. */
1232 case PROC_STS_TEA: /* Terminated abnormally. */
1233 case PROC_STS_TES: /* Terminated through signal. */
1234 case PROC_STS_TOK:
1235 case PROC_STS_TOA:
1236 case PROC_STS_DWN:
1237 /*
1238 * Process (already) ended, but we want to get the
1239 * PID anyway to retrieve the output in a later call.
1240 */
1241 *puPID = pExecStatus->u32PID;
1242 break;
1243
1244 case PROC_STS_ERROR:
1245 {
1246 int vrc = pExecStatus->u32Flags; /* u32Flags member contains IPRT error code. */
1247 if (vrc == VERR_FILE_NOT_FOUND) /* This is the most likely error. */
1248 rc = setErrorNoLog(VBOX_E_IPRT_ERROR,
1249 tr("The file '%s' was not found on guest"), pszCommand);
1250 else if (vrc == VERR_PATH_NOT_FOUND)
1251 rc = setErrorNoLog(VBOX_E_IPRT_ERROR,
1252 tr("The path to file '%s' was not found on guest"), pszCommand);
1253 else if (vrc == VERR_BAD_EXE_FORMAT)
1254 rc = setErrorNoLog(VBOX_E_IPRT_ERROR,
1255 tr("The file '%s' is not an executable format on guest"), pszCommand);
1256 else if (vrc == VERR_AUTHENTICATION_FAILURE)
1257 rc = setErrorNoLog(VBOX_E_IPRT_ERROR,
1258 tr("The specified user '%s' was not able to logon on guest"), pszUser);
1259 else if (vrc == VERR_TIMEOUT)
1260 rc = setErrorNoLog(VBOX_E_IPRT_ERROR,
1261 tr("The guest did not respond within time (%ums)"), ulTimeout);
1262 else if (vrc == VERR_CANCELLED)
1263 rc = setErrorNoLog(VBOX_E_IPRT_ERROR,
1264 tr("The execution operation was canceled"));
1265 else if (vrc == VERR_PERMISSION_DENIED)
1266 rc = setErrorNoLog(VBOX_E_IPRT_ERROR,
1267 tr("Invalid user/password credentials"));
1268 else if (vrc == VERR_MAX_PROCS_REACHED)
1269 rc = setErrorNoLog(VBOX_E_IPRT_ERROR,
1270 tr("Concurrent guest process limit is reached"));
1271 else
1272 {
1273 if (pExecStatus && pExecStatus->u32Status == PROC_STS_ERROR)
1274 rc = setErrorNoLog(VBOX_E_IPRT_ERROR,
1275 tr("Process could not be started: %Rrc"), pExecStatus->u32Flags);
1276 else
1277 rc = setErrorNoLog(E_UNEXPECTED,
1278 tr("The service call failed with error %Rrc"), vrc);
1279 }
1280 }
1281 break;
1282
1283 case PROC_STS_UNDEFINED: /* . */
1284 rc = setErrorNoLog(VBOX_E_IPRT_ERROR,
1285 tr("The operation did not complete within time"));
1286 break;
1287
1288 default:
1289 AssertReleaseMsgFailed(("Process (PID %u) reported back an undefined state!\n",
1290 pExecStatus->u32PID));
1291 rc = E_UNEXPECTED;
1292 break;
1293 }
1294
1295 return rc;
1296}
1297
1298/**
1299 * TODO
1300 *
1301 * @return HRESULT
1302 * @param aObjName
1303 * @param pStreamBlock
1304 * @param pObjInfo
1305 * @param enmAddAttribs
1306 */
1307HRESULT Guest::executeStreamQueryFsObjInfo(IN_BSTR aObjName,
1308 GuestProcessStreamBlock &streamBlock,
1309 PRTFSOBJINFO pObjInfo,
1310 RTFSOBJATTRADD enmAddAttribs)
1311{
1312 HRESULT rc = S_OK;
1313 Utf8Str Utf8ObjName(aObjName);
1314
1315 int64_t iVal;
1316 int vrc = streamBlock.GetInt64Ex("st_size", &iVal);
1317 if (RT_SUCCESS(vrc))
1318 pObjInfo->cbObject = iVal;
1319 else
1320 rc = setError(VBOX_E_IPRT_ERROR,
1321 tr("Unable to retrieve size for \"%s\" (%Rrc)"),
1322 Utf8ObjName.c_str(), vrc);
1323 /** @todo Add more stuff! */
1324 return rc;
1325}
1326
1327/**
1328 * Tries to drain the guest's output and fill it into
1329 * a guest process stream object for later usage.
1330 *
1331 * @todo What's about specifying stderr?
1332 * @return IPRT status code.
1333 * @param aPID PID of process to get the output from.
1334 * @param aFlags Which stream to drain (stdout or stderr).
1335 * @param stream Reference to guest process stream to fill.
1336 */
1337int Guest::executeStreamDrain(ULONG aPID, ULONG aFlags, GuestProcessStream &stream)
1338{
1339 AssertReturn(aPID, VERR_INVALID_PARAMETER);
1340
1341 int rc = VINF_SUCCESS;
1342 for (;;)
1343 {
1344 SafeArray<BYTE> aData;
1345 HRESULT hr = getProcessOutputInternal(aPID, aFlags,
1346 0 /* Infinite timeout */,
1347 _64K, ComSafeArrayAsOutParam(aData), &rc);
1348 if (SUCCEEDED(hr))
1349 {
1350 if (aData.size())
1351 {
1352 rc = stream.AddData(aData.raw(), aData.size());
1353 if (RT_UNLIKELY(RT_FAILURE(rc)))
1354 break;
1355 }
1356
1357 continue; /* Try one more time. */
1358 }
1359 else /* No more output and/or error! */
1360 {
1361 if (rc == VERR_NOT_FOUND)
1362 rc = VINF_SUCCESS;
1363 break;
1364 }
1365 }
1366
1367 return rc;
1368}
1369
1370/**
1371 * Tries to retrieve the next stream block of a given stream and
1372 * drains the process output only as much as needed to get this next
1373 * stream block.
1374 *
1375 * @return IPRT status code.
1376 * @param ulPID
1377 * @param ulFlags
1378 * @param stream
1379 * @param streamBlock
1380 */
1381int Guest::executeStreamGetNextBlock(ULONG ulPID,
1382 ULONG ulFlags,
1383 GuestProcessStream &stream,
1384 GuestProcessStreamBlock &streamBlock)
1385{
1386 AssertReturn(!streamBlock.GetCount(), VERR_INVALID_PARAMETER);
1387
1388 bool fDrainStream = true;
1389 int rc;
1390 do
1391 {
1392 rc = stream.ParseBlock(streamBlock);
1393 if (RT_FAILURE(rc)) /* More data needed or empty buffer? */
1394 {
1395 if (fDrainStream)
1396 {
1397 SafeArray<BYTE> aData;
1398 HRESULT hr = getProcessOutputInternal(ulPID, ulFlags,
1399 0 /* Infinite timeout */,
1400 _64K, ComSafeArrayAsOutParam(aData), &rc);
1401 if (SUCCEEDED(hr))
1402 {
1403 if (aData.size())
1404 {
1405 rc = stream.AddData(aData.raw(), aData.size());
1406 if (RT_UNLIKELY(RT_FAILURE(rc)))
1407 break;
1408 }
1409
1410 continue; /* Try one more time. */
1411 }
1412 else
1413 {
1414 /* No more output to drain from stream. */
1415 if (rc == VERR_NOT_FOUND)
1416 {
1417 fDrainStream = false;
1418 continue;
1419 }
1420
1421 break;
1422 }
1423 }
1424 else
1425 {
1426 /* We haved drained the stream as much as we can and reached the
1427 * end of our stream buffer -- that means that there simply is no
1428 * stream block anymore, which is ok. */
1429 if (rc == VERR_NO_DATA)
1430 rc = VINF_SUCCESS;
1431 break;
1432 }
1433 }
1434 }
1435 while (!streamBlock.GetCount());
1436
1437 return rc;
1438}
1439
1440/**
1441 * Tries to get the next upcoming value block from a started guest process
1442 * by first draining its output and then processing the received guest stream.
1443 *
1444 * @return IPRT status code.
1445 * @param ulPID PID of process to get/parse the output from.
1446 * @param ulFlags ?
1447 * @param stream Reference to process stream object to use.
1448 * @param streamBlock Reference that receives the next stream block data.
1449 *
1450 */
1451int Guest::executeStreamParseNextBlock(ULONG ulPID,
1452 ULONG ulFlags,
1453 GuestProcessStream &stream,
1454 GuestProcessStreamBlock &streamBlock)
1455{
1456 AssertReturn(!streamBlock.GetCount(), VERR_INVALID_PARAMETER);
1457
1458 int rc;
1459 do
1460 {
1461 rc = stream.ParseBlock(streamBlock);
1462 if (RT_FAILURE(rc))
1463 break;
1464 }
1465 while (!streamBlock.GetCount());
1466
1467 return rc;
1468}
1469
1470/**
1471 * Gets output from a formerly started guest process, tries to parse all of its guest
1472 * stream (as long as data is available) and returns a stream object which can contain
1473 * multiple stream blocks (which in turn then can contain key=value pairs).
1474 *
1475 * @return HRESULT
1476 * @param ulPID PID of process to get/parse the output from.
1477 * @param ulFlags ?
1478 * @param streamObjects Reference to a guest stream object structure for
1479 * storing the parsed data.
1480 */
1481HRESULT Guest::executeStreamParse(ULONG ulPID, ULONG ulFlags, GuestCtrlStreamObjects &streamObjects)
1482{
1483 GuestProcessStream stream;
1484 int rc = executeStreamDrain(ulPID, ulFlags, stream);
1485 if (RT_SUCCESS(rc))
1486 {
1487 do
1488 {
1489 /* Try to parse the stream output we gathered until now. If we still need more
1490 * data the parsing routine will tell us and we just do another poll round. */
1491 GuestProcessStreamBlock curBlock;
1492 rc = executeStreamParseNextBlock(ulPID, ulFlags, stream, curBlock);
1493 if (RT_SUCCESS(rc))
1494 streamObjects.push_back(curBlock);
1495 } while (RT_SUCCESS(rc));
1496
1497 if (rc == VERR_NO_DATA) /* End of data reached. */
1498 rc = VINF_SUCCESS;
1499 }
1500
1501 if (RT_FAILURE(rc))
1502 return setError(VBOX_E_IPRT_ERROR,
1503 tr("Error while parsing guest output (%Rrc)"), rc);
1504 return rc;
1505}
1506
1507/**
1508 * Waits for a fomerly started guest process to exit using its progress
1509 * object and returns its final status. Returns E_ABORT if guest process
1510 * was canceled.
1511 *
1512 * @return IPRT status code.
1513 * @param uPID PID of guest process to wait for.
1514 * @param pProgress Progress object to wait for.
1515 * @param uTimeoutMS Timeout (in ms) for waiting; use 0 for
1516 * an indefinite timeout.
1517 * @param pRetStatus Pointer where to store the final process
1518 * status. Optional.
1519 * @param puRetExitCode Pointer where to store the final process
1520 * exit code. Optional.
1521 */
1522HRESULT Guest::executeWaitForExit(ULONG uPID, ComPtr<IProgress> pProgress, ULONG uTimeoutMS,
1523 ExecuteProcessStatus_T *pRetStatus, ULONG *puRetExitCode)
1524{
1525 HRESULT rc = S_OK;
1526
1527 BOOL fCanceled = FALSE;
1528 if ( SUCCEEDED(pProgress->COMGETTER(Canceled(&fCanceled)))
1529 && fCanceled)
1530 {
1531 return E_ABORT;
1532 }
1533
1534 BOOL fCompleted = FALSE;
1535 if ( SUCCEEDED(pProgress->COMGETTER(Completed(&fCompleted)))
1536 && !fCompleted)
1537 {
1538 rc = pProgress->WaitForCompletion( !uTimeoutMS
1539 ? -1 /* No timeout */
1540 : uTimeoutMS);
1541 if (FAILED(rc))
1542 rc = setError(VBOX_E_IPRT_ERROR,
1543 tr("Waiting for guest process to end failed (%Rhrc)"),
1544 rc);
1545 }
1546
1547 if (SUCCEEDED(rc))
1548 {
1549 ULONG uExitCode, uRetFlags;
1550 ExecuteProcessStatus_T enmStatus;
1551 HRESULT hRC = GetProcessStatus(uPID, &uExitCode, &uRetFlags, &enmStatus);
1552 if (FAILED(hRC))
1553 return hRC;
1554
1555 if (pRetStatus)
1556 *pRetStatus = enmStatus;
1557 if (puRetExitCode)
1558 *puRetExitCode = uExitCode;
1559 /** @todo Flags? */
1560 }
1561
1562 return rc;
1563}
1564
1565/**
1566 * Does the actual guest process execution, internal function.
1567 *
1568 * @return HRESULT
1569 * @param aCommand Command line to execute.
1570 * @param aFlags Execution flags.
1571 * @param Username Username to execute the process with.
1572 * @param aPassword The user's password.
1573 * @param aTimeoutMS Timeout (in ms) to wait for the execution operation.
1574 * @param aPID Pointer that receives the guest process' PID.
1575 * @param aProgress Pointer that receives the guest process' progress object.
1576 * @param pRC Pointer that receives the internal IPRT return code. Optional.
1577 */
1578HRESULT Guest::executeProcessInternal(IN_BSTR aCommand, ULONG aFlags,
1579 ComSafeArrayIn(IN_BSTR, aArguments), ComSafeArrayIn(IN_BSTR, aEnvironment),
1580 IN_BSTR aUsername, IN_BSTR aPassword,
1581 ULONG aTimeoutMS, ULONG *aPID, IProgress **aProgress, int *pRC)
1582{
1583/** @todo r=bird: Eventually we should clean up all the timeout parameters
1584 * in the API and have the same way of specifying infinite waits! */
1585 using namespace guestControl;
1586
1587 AutoCaller autoCaller(this);
1588 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1589
1590 /* Validate flags. */
1591 if (aFlags != ExecuteProcessFlag_None)
1592 {
1593 if ( !(aFlags & ExecuteProcessFlag_IgnoreOrphanedProcesses)
1594 && !(aFlags & ExecuteProcessFlag_WaitForProcessStartOnly)
1595 && !(aFlags & ExecuteProcessFlag_Hidden)
1596 && !(aFlags & ExecuteProcessFlag_NoProfile)
1597 && !(aFlags & ExecuteProcessFlag_WaitForStdOut)
1598 && !(aFlags & ExecuteProcessFlag_WaitForStdErr))
1599 {
1600 if (pRC)
1601 *pRC = VERR_INVALID_PARAMETER;
1602 return setError(E_INVALIDARG, tr("Unknown flags (%#x)"), aFlags);
1603 }
1604 }
1605
1606 HRESULT rc = S_OK;
1607
1608 try
1609 {
1610 /*
1611 * Create progress object. Note that this is a multi operation
1612 * object to perform the following steps:
1613 * - Operation 1 (0): Create/start process.
1614 * - Operation 2 (1): Wait for process to exit.
1615 * If this progress completed successfully (S_OK), the process
1616 * started and exited normally. In any other case an error/exception
1617 * occurred.
1618 */
1619 ComObjPtr <Progress> pProgress;
1620 rc = pProgress.createObject();
1621 if (SUCCEEDED(rc))
1622 {
1623 rc = pProgress->init(static_cast<IGuest*>(this),
1624 Bstr(tr("Executing process")).raw(),
1625 TRUE,
1626 2, /* Number of operations. */
1627 Bstr(tr("Starting process ...")).raw()); /* Description of first stage. */
1628 }
1629 ComAssertComRC(rc);
1630
1631 /*
1632 * Prepare process execution.
1633 */
1634 int vrc = VINF_SUCCESS;
1635 Utf8Str Utf8Command(aCommand);
1636
1637 /* Adjust timeout. If set to 0, we define
1638 * an infinite timeout. */
1639 if (aTimeoutMS == 0)
1640 aTimeoutMS = UINT32_MAX;
1641
1642 /* Prepare arguments. */
1643 char **papszArgv = NULL;
1644 uint32_t uNumArgs = 0;
1645 if (aArguments)
1646 {
1647 com::SafeArray<IN_BSTR> args(ComSafeArrayInArg(aArguments));
1648 uNumArgs = args.size();
1649 papszArgv = (char**)RTMemAlloc(sizeof(char*) * (uNumArgs + 1));
1650 AssertReturn(papszArgv, E_OUTOFMEMORY);
1651 for (unsigned i = 0; RT_SUCCESS(vrc) && i < uNumArgs; i++)
1652 vrc = RTUtf16ToUtf8(args[i], &papszArgv[i]);
1653 papszArgv[uNumArgs] = NULL;
1654 }
1655
1656 Utf8Str Utf8UserName(aUsername);
1657 Utf8Str Utf8Password(aPassword);
1658 if (RT_SUCCESS(vrc))
1659 {
1660 uint32_t uContextID = 0;
1661
1662 char *pszArgs = NULL;
1663 if (uNumArgs > 0)
1664 vrc = RTGetOptArgvToString(&pszArgs, papszArgv, RTGETOPTARGV_CNV_QUOTE_MS_CRT);
1665 if (RT_SUCCESS(vrc))
1666 {
1667 uint32_t cbArgs = pszArgs ? strlen(pszArgs) + 1 : 0; /* Include terminating zero. */
1668
1669 /* Prepare environment. */
1670 void *pvEnv = NULL;
1671 uint32_t uNumEnv = 0;
1672 uint32_t cbEnv = 0;
1673 if (aEnvironment)
1674 {
1675 com::SafeArray<IN_BSTR> env(ComSafeArrayInArg(aEnvironment));
1676
1677 for (unsigned i = 0; i < env.size(); i++)
1678 {
1679 vrc = prepareExecuteEnv(Utf8Str(env[i]).c_str(), &pvEnv, &cbEnv, &uNumEnv);
1680 if (RT_FAILURE(vrc))
1681 break;
1682 }
1683 }
1684
1685 if (RT_SUCCESS(vrc))
1686 {
1687 VBOXGUESTCTRL_CALLBACK callback;
1688 vrc = callbackInit(&callback, VBOXGUESTCTRLCALLBACKTYPE_EXEC_START, pProgress);
1689 if (RT_SUCCESS(vrc))
1690 {
1691 /* Allocate and assign payload. */
1692 callback.cbData = sizeof(CALLBACKDATAEXECSTATUS);
1693 PCALLBACKDATAEXECSTATUS pData = (PCALLBACKDATAEXECSTATUS)RTMemAlloc(callback.cbData);
1694 AssertReturn(pData, E_OUTOFMEMORY);
1695 RT_BZERO(pData, callback.cbData);
1696 callback.pvData = pData;
1697 }
1698
1699 if (RT_SUCCESS(vrc))
1700 vrc = callbackAdd(&callback, &uContextID);
1701
1702 if (RT_SUCCESS(vrc))
1703 {
1704 VBOXHGCMSVCPARM paParms[15];
1705 int i = 0;
1706 paParms[i++].setUInt32(uContextID);
1707 paParms[i++].setPointer((void*)Utf8Command.c_str(), (uint32_t)Utf8Command.length() + 1);
1708 paParms[i++].setUInt32(aFlags);
1709 paParms[i++].setUInt32(uNumArgs);
1710 paParms[i++].setPointer((void*)pszArgs, cbArgs);
1711 paParms[i++].setUInt32(uNumEnv);
1712 paParms[i++].setUInt32(cbEnv);
1713 paParms[i++].setPointer((void*)pvEnv, cbEnv);
1714 paParms[i++].setPointer((void*)Utf8UserName.c_str(), (uint32_t)Utf8UserName.length() + 1);
1715 paParms[i++].setPointer((void*)Utf8Password.c_str(), (uint32_t)Utf8Password.length() + 1);
1716
1717 /*
1718 * If the WaitForProcessStartOnly flag is set, we only want to define and wait for a timeout
1719 * until the process was started - the process itself then gets an infinite timeout for execution.
1720 * This is handy when we want to start a process inside a worker thread within a certain timeout
1721 * but let the started process perform lengthly operations then.
1722 */
1723 if (aFlags & ExecuteProcessFlag_WaitForProcessStartOnly)
1724 paParms[i++].setUInt32(UINT32_MAX /* Infinite timeout */);
1725 else
1726 paParms[i++].setUInt32(aTimeoutMS);
1727
1728 VMMDev *pVMMDev = NULL;
1729 {
1730 /* Make sure mParent is valid, so set the read lock while using.
1731 * Do not keep this lock while doing the actual call, because in the meanwhile
1732 * another thread could request a write lock which would be a bad idea ... */
1733 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1734
1735 /* Forward the information to the VMM device. */
1736 AssertPtr(mParent);
1737 pVMMDev = mParent->getVMMDev();
1738 }
1739
1740 if (pVMMDev)
1741 {
1742 LogFlowFunc(("hgcmHostCall numParms=%d\n", i));
1743 vrc = pVMMDev->hgcmHostCall("VBoxGuestControlSvc", HOST_EXEC_CMD,
1744 i, paParms);
1745 }
1746 else
1747 vrc = VERR_INVALID_VM_HANDLE;
1748 }
1749 RTMemFree(pvEnv);
1750 }
1751 RTStrFree(pszArgs);
1752 }
1753
1754 if (RT_SUCCESS(vrc))
1755 {
1756 LogFlowFunc(("Waiting for HGCM callback (timeout=%RI32ms) ...\n", aTimeoutMS));
1757
1758 /*
1759 * Wait for the HGCM low level callback until the process
1760 * has been started (or something went wrong). This is necessary to
1761 * get the PID.
1762 */
1763
1764 PCALLBACKDATAEXECSTATUS pExecStatus = NULL;
1765
1766 /*
1767 * Wait for the first stage (=0) to complete (that is starting the process).
1768 */
1769 vrc = callbackWaitForCompletion(uContextID, 0 /* Stage */, aTimeoutMS);
1770 if (RT_SUCCESS(vrc))
1771 {
1772 vrc = callbackGetUserData(uContextID, NULL /* We know the type. */,
1773 (void**)&pExecStatus, NULL /* Don't need the size. */);
1774 if (RT_SUCCESS(vrc))
1775 {
1776 rc = executeProcessResult(Utf8Command.c_str(), Utf8UserName.c_str(), aTimeoutMS,
1777 pExecStatus, aPID);
1778 callbackFreeUserData(pExecStatus);
1779 }
1780 else
1781 {
1782 rc = setErrorNoLog(VBOX_E_IPRT_ERROR,
1783 tr("Unable to retrieve process execution status data"));
1784 }
1785 }
1786 else
1787 rc = handleErrorCompletion(vrc);
1788
1789 /*
1790 * Do *not* remove the callback yet - we might wait with the IProgress object on something
1791 * else (like end of process) ...
1792 */
1793 }
1794 else
1795 rc = handleErrorHGCM(vrc);
1796
1797 for (unsigned i = 0; i < uNumArgs; i++)
1798 RTMemFree(papszArgv[i]);
1799 RTMemFree(papszArgv);
1800 }
1801
1802 if (SUCCEEDED(rc))
1803 {
1804 /* Return the progress to the caller. */
1805 pProgress.queryInterfaceTo(aProgress);
1806 }
1807 else
1808 {
1809 if (!pRC) /* Skip logging internal calls. */
1810 LogRel(("Executing guest process \"%s\" as user \"%s\" failed with %Rrc\n",
1811 Utf8Command.c_str(), Utf8UserName.c_str(), vrc));
1812 }
1813
1814 if (pRC)
1815 *pRC = vrc;
1816 }
1817 catch (std::bad_alloc &)
1818 {
1819 rc = E_OUTOFMEMORY;
1820 }
1821 return rc;
1822}
1823#endif /* VBOX_WITH_GUEST_CONTROL */
1824
1825STDMETHODIMP Guest::SetProcessInput(ULONG aPID, ULONG aFlags, ULONG aTimeoutMS, ComSafeArrayIn(BYTE, aData), ULONG *aBytesWritten)
1826{
1827#ifndef VBOX_WITH_GUEST_CONTROL
1828 ReturnComNotImplemented();
1829#else /* VBOX_WITH_GUEST_CONTROL */
1830 using namespace guestControl;
1831
1832 CheckComArgExpr(aPID, aPID > 0);
1833 CheckComArgOutPointerValid(aBytesWritten);
1834
1835 /* Validate flags. */
1836 if (aFlags)
1837 {
1838 if (!(aFlags & ProcessInputFlag_EndOfFile))
1839 return setError(E_INVALIDARG, tr("Unknown flags (%#x)"), aFlags);
1840 }
1841
1842 AutoCaller autoCaller(this);
1843 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1844
1845 HRESULT rc = S_OK;
1846
1847 try
1848 {
1849 VBOXGUESTCTRL_PROCESS process;
1850 int vrc = processGetStatus(aPID, &process);
1851 if (RT_SUCCESS(vrc))
1852 {
1853 /* PID exists; check if process is still running. */
1854 if (process.mStatus != ExecuteProcessStatus_Started)
1855 rc = setError(VBOX_E_IPRT_ERROR,
1856 Guest::tr("Cannot inject input to not running process (PID %u)"), aPID);
1857 }
1858 else
1859 rc = setError(VBOX_E_IPRT_ERROR,
1860 Guest::tr("Cannot inject input to non-existent process (PID %u)"), aPID);
1861
1862 if (RT_SUCCESS(vrc))
1863 {
1864 uint32_t uContextID = 0;
1865
1866 /*
1867 * Create progress object.
1868 * This progress object, compared to the one in executeProgress() above,
1869 * is only single-stage local and is used to determine whether the operation
1870 * finished or got canceled.
1871 */
1872 ComObjPtr <Progress> pProgress;
1873 rc = pProgress.createObject();
1874 if (SUCCEEDED(rc))
1875 {
1876 rc = pProgress->init(static_cast<IGuest*>(this),
1877 Bstr(tr("Setting input for process")).raw(),
1878 TRUE /* Cancelable */);
1879 }
1880 if (FAILED(rc)) throw rc;
1881 ComAssert(!pProgress.isNull());
1882
1883 /* Adjust timeout. */
1884 if (aTimeoutMS == 0)
1885 aTimeoutMS = UINT32_MAX;
1886
1887 VBOXGUESTCTRL_CALLBACK callback;
1888 vrc = callbackInit(&callback, VBOXGUESTCTRLCALLBACKTYPE_EXEC_INPUT_STATUS, pProgress);
1889 if (RT_SUCCESS(vrc))
1890 {
1891 PCALLBACKDATAEXECINSTATUS pData = (PCALLBACKDATAEXECINSTATUS)callback.pvData;
1892
1893 /* Save PID + output flags for later use. */
1894 pData->u32PID = aPID;
1895 pData->u32Flags = aFlags;
1896 }
1897
1898 if (RT_SUCCESS(vrc))
1899 vrc = callbackAdd(&callback, &uContextID);
1900
1901 if (RT_SUCCESS(vrc))
1902 {
1903 com::SafeArray<BYTE> sfaData(ComSafeArrayInArg(aData));
1904 uint32_t cbSize = sfaData.size();
1905
1906 VBOXHGCMSVCPARM paParms[6];
1907 int i = 0;
1908 paParms[i++].setUInt32(uContextID);
1909 paParms[i++].setUInt32(aPID);
1910 paParms[i++].setUInt32(aFlags);
1911 paParms[i++].setPointer(sfaData.raw(), cbSize);
1912 paParms[i++].setUInt32(cbSize);
1913
1914 {
1915 VMMDev *pVMMDev = NULL;
1916 {
1917 /* Make sure mParent is valid, so set the read lock while using.
1918 * Do not keep this lock while doing the actual call, because in the meanwhile
1919 * another thread could request a write lock which would be a bad idea ... */
1920 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1921
1922 /* Forward the information to the VMM device. */
1923 AssertPtr(mParent);
1924 pVMMDev = mParent->getVMMDev();
1925 }
1926
1927 if (pVMMDev)
1928 {
1929 LogFlowFunc(("hgcmHostCall numParms=%d\n", i));
1930 vrc = pVMMDev->hgcmHostCall("VBoxGuestControlSvc", HOST_EXEC_SET_INPUT,
1931 i, paParms);
1932 if (RT_FAILURE(vrc))
1933 rc = handleErrorHGCM(vrc);
1934 }
1935 }
1936 }
1937
1938 if (RT_SUCCESS(vrc))
1939 {
1940 LogFlowFunc(("Waiting for HGCM callback ...\n"));
1941
1942 /*
1943 * Wait for getting back the input response from the guest.
1944 */
1945 vrc = callbackWaitForCompletion(uContextID, -1 /* No staging required */, aTimeoutMS);
1946 if (RT_SUCCESS(vrc))
1947 {
1948 PCALLBACKDATAEXECINSTATUS pExecStatusIn;
1949 vrc = callbackGetUserData(uContextID, NULL /* We know the type. */,
1950 (void**)&pExecStatusIn, NULL /* Don't need the size. */);
1951 if (RT_SUCCESS(vrc))
1952 {
1953 AssertPtr(pExecStatusIn);
1954 switch (pExecStatusIn->u32Status)
1955 {
1956 case INPUT_STS_WRITTEN:
1957 *aBytesWritten = pExecStatusIn->cbProcessed;
1958 break;
1959
1960 case INPUT_STS_ERROR:
1961 rc = setError(VBOX_E_IPRT_ERROR,
1962 tr("Client reported error %Rrc while processing input data"),
1963 pExecStatusIn->u32Flags);
1964 break;
1965
1966 case INPUT_STS_TERMINATED:
1967 rc = setError(VBOX_E_IPRT_ERROR,
1968 tr("Client terminated while processing input data"));
1969 break;
1970
1971 case INPUT_STS_OVERFLOW:
1972 rc = setError(VBOX_E_IPRT_ERROR,
1973 tr("Client reported buffer overflow while processing input data"));
1974 break;
1975
1976 default:
1977 /*AssertReleaseMsgFailed(("Client reported unknown input error, status=%u, flags=%u\n",
1978 pExecStatusIn->u32Status, pExecStatusIn->u32Flags));*/
1979 break;
1980 }
1981
1982 callbackFreeUserData(pExecStatusIn);
1983 }
1984 else
1985 {
1986 rc = setErrorNoLog(VBOX_E_IPRT_ERROR,
1987 tr("Unable to retrieve process input status data"));
1988 }
1989 }
1990 else
1991 rc = handleErrorCompletion(vrc);
1992 }
1993
1994 /* The callback isn't needed anymore -- just was kept locally. */
1995 callbackDestroy(uContextID);
1996
1997 /* Cleanup. */
1998 if (!pProgress.isNull())
1999 pProgress->uninit();
2000 pProgress.setNull();
2001 }
2002 }
2003 catch (std::bad_alloc &)
2004 {
2005 rc = E_OUTOFMEMORY;
2006 }
2007 return rc;
2008#endif
2009}
2010
2011STDMETHODIMP Guest::GetProcessOutput(ULONG aPID, ULONG aFlags, ULONG aTimeoutMS, LONG64 aSize, ComSafeArrayOut(BYTE, aData))
2012{
2013#ifndef VBOX_WITH_GUEST_CONTROL
2014 ReturnComNotImplemented();
2015#else /* VBOX_WITH_GUEST_CONTROL */
2016 using namespace guestControl;
2017
2018 return getProcessOutputInternal(aPID, aFlags, aTimeoutMS,
2019 aSize, ComSafeArrayOutArg(aData), NULL /* rc */);
2020#endif
2021}
2022
2023HRESULT Guest::getProcessOutputInternal(ULONG aPID, ULONG aFlags, ULONG aTimeoutMS,
2024 LONG64 aSize, ComSafeArrayOut(BYTE, aData), int *pRC)
2025{
2026/** @todo r=bird: Eventually we should clean up all the timeout parameters
2027 * in the API and have the same way of specifying infinite waits! */
2028#ifndef VBOX_WITH_GUEST_CONTROL
2029 ReturnComNotImplemented();
2030#else /* VBOX_WITH_GUEST_CONTROL */
2031 using namespace guestControl;
2032
2033 CheckComArgExpr(aPID, aPID > 0);
2034 if (aSize < 0)
2035 return setError(E_INVALIDARG, tr("The size argument (%lld) is negative"), aSize);
2036 if (aSize == 0)
2037 return setError(E_INVALIDARG, tr("The size (%lld) is zero"), aSize);
2038 if (aFlags)
2039 {
2040 if (!(aFlags & ProcessOutputFlag_StdErr))
2041 {
2042 return setError(E_INVALIDARG, tr("Unknown flags (%#x)"), aFlags);
2043 }
2044 }
2045
2046 AutoCaller autoCaller(this);
2047 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2048
2049 HRESULT rc = S_OK;
2050
2051 try
2052 {
2053 VBOXGUESTCTRL_PROCESS proc;
2054 int vrc = processGetStatus(aPID, &proc);
2055 if (RT_FAILURE(vrc))
2056 {
2057 rc = setError(VBOX_E_IPRT_ERROR,
2058 Guest::tr("Guest process (PID %u) does not exist"), aPID);
2059 }
2060 else
2061 {
2062 uint32_t uContextID = 0;
2063
2064 /*
2065 * Create progress object.
2066 * This progress object, compared to the one in executeProgress() above,
2067 * is only single-stage local and is used to determine whether the operation
2068 * finished or got canceled.
2069 */
2070 ComObjPtr <Progress> pProgress;
2071 rc = pProgress.createObject();
2072 if (SUCCEEDED(rc))
2073 {
2074 rc = pProgress->init(static_cast<IGuest*>(this),
2075 Bstr(tr("Getting output for guest process")).raw(),
2076 TRUE /* Cancelable */);
2077 }
2078 if (FAILED(rc)) throw rc;
2079 ComAssert(!pProgress.isNull());
2080
2081 /* Adjust timeout. */
2082 if (aTimeoutMS == 0)
2083 aTimeoutMS = UINT32_MAX;
2084
2085 /* Set handle ID. */
2086 uint32_t uHandleID = OUTPUT_HANDLE_ID_STDOUT; /* Default */
2087 if (aFlags & ProcessOutputFlag_StdErr)
2088 uHandleID = OUTPUT_HANDLE_ID_STDERR;
2089
2090 VBOXGUESTCTRL_CALLBACK callback;
2091 vrc = callbackInit(&callback, VBOXGUESTCTRLCALLBACKTYPE_EXEC_OUTPUT, pProgress);
2092 if (RT_SUCCESS(vrc))
2093 {
2094 PCALLBACKDATAEXECOUT pData = (PCALLBACKDATAEXECOUT)callback.pvData;
2095
2096 /* Save PID + output flags for later use. */
2097 pData->u32PID = aPID;
2098 pData->u32Flags = aFlags;
2099 }
2100
2101 if (RT_SUCCESS(vrc))
2102 vrc = callbackAdd(&callback, &uContextID);
2103
2104 if (RT_SUCCESS(vrc))
2105 {
2106 VBOXHGCMSVCPARM paParms[5];
2107 int i = 0;
2108 paParms[i++].setUInt32(uContextID);
2109 paParms[i++].setUInt32(aPID);
2110 paParms[i++].setUInt32(uHandleID);
2111 paParms[i++].setUInt32(0 /* Flags, none set yet */);
2112
2113 VMMDev *pVMMDev = NULL;
2114 {
2115 /* Make sure mParent is valid, so set the read lock while using.
2116 * Do not keep this lock while doing the actual call, because in the meanwhile
2117 * another thread could request a write lock which would be a bad idea ... */
2118 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2119
2120 /* Forward the information to the VMM device. */
2121 AssertPtr(mParent);
2122 pVMMDev = mParent->getVMMDev();
2123 }
2124
2125 if (pVMMDev)
2126 {
2127 LogFlowFunc(("hgcmHostCall numParms=%d\n", i));
2128 vrc = pVMMDev->hgcmHostCall("VBoxGuestControlSvc", HOST_EXEC_GET_OUTPUT,
2129 i, paParms);
2130 }
2131 }
2132
2133 if (RT_SUCCESS(vrc))
2134 {
2135 LogFlowFunc(("Waiting for HGCM callback (timeout=%RI32ms) ...\n", aTimeoutMS));
2136
2137 /*
2138 * Wait for the HGCM low level callback until the process
2139 * has been started (or something went wrong). This is necessary to
2140 * get the PID.
2141 */
2142
2143 /*
2144 * Wait for the first output callback notification to arrive.
2145 */
2146 vrc = callbackWaitForCompletion(uContextID, -1 /* No staging required */, aTimeoutMS);
2147 if (RT_SUCCESS(vrc))
2148 {
2149 PCALLBACKDATAEXECOUT pExecOut = NULL;
2150 vrc = callbackGetUserData(uContextID, NULL /* We know the type. */,
2151 (void**)&pExecOut, NULL /* Don't need the size. */);
2152 if (RT_SUCCESS(vrc))
2153 {
2154 com::SafeArray<BYTE> outputData((size_t)aSize);
2155
2156 if (pExecOut->cbData)
2157 {
2158 /* Do we need to resize the array? */
2159 if (pExecOut->cbData > aSize)
2160 outputData.resize(pExecOut->cbData);
2161
2162 /* Fill output in supplied out buffer. */
2163 memcpy(outputData.raw(), pExecOut->pvData, pExecOut->cbData);
2164 outputData.resize(pExecOut->cbData); /* Shrink to fit actual buffer size. */
2165 }
2166 else
2167 {
2168 /* No data within specified timeout available. */
2169 outputData.resize(0);
2170 }
2171
2172 /* Detach output buffer to output argument. */
2173 outputData.detachTo(ComSafeArrayOutArg(aData));
2174
2175 callbackFreeUserData(pExecOut);
2176 }
2177 else
2178 {
2179 rc = setErrorNoLog(VBOX_E_IPRT_ERROR,
2180 tr("Unable to retrieve process output data"));
2181 }
2182 }
2183 else
2184 rc = handleErrorCompletion(vrc);
2185 }
2186 else
2187 rc = handleErrorHGCM(vrc);
2188
2189 /* The callback isn't needed anymore -- just was kept locally. */
2190 callbackDestroy(uContextID);
2191
2192 /* Cleanup. */
2193 if (!pProgress.isNull())
2194 pProgress->uninit();
2195 pProgress.setNull();
2196 }
2197
2198 if (pRC)
2199 *pRC = vrc;
2200 }
2201 catch (std::bad_alloc &)
2202 {
2203 rc = E_OUTOFMEMORY;
2204 }
2205 return rc;
2206#endif
2207}
2208
2209STDMETHODIMP Guest::GetProcessStatus(ULONG aPID, ULONG *aExitCode, ULONG *aFlags, ExecuteProcessStatus_T *aStatus)
2210{
2211#ifndef VBOX_WITH_GUEST_CONTROL
2212 ReturnComNotImplemented();
2213#else /* VBOX_WITH_GUEST_CONTROL */
2214
2215 AutoCaller autoCaller(this);
2216 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2217
2218 HRESULT rc = S_OK;
2219
2220 try
2221 {
2222 VBOXGUESTCTRL_PROCESS process;
2223 int vrc = processGetStatus(aPID, &process);
2224 if (RT_SUCCESS(vrc))
2225 {
2226 if (aExitCode)
2227 *aExitCode = process.mExitCode;
2228 if (aFlags)
2229 *aFlags = process.mFlags;
2230 if (aStatus)
2231 *aStatus = process.mStatus;
2232 }
2233 else
2234 rc = setError(VBOX_E_IPRT_ERROR,
2235 tr("Process (PID %u) not found!"), aPID);
2236 }
2237 catch (std::bad_alloc &)
2238 {
2239 rc = E_OUTOFMEMORY;
2240 }
2241 return rc;
2242#endif
2243}
2244
2245STDMETHODIMP Guest::CopyFromGuest(IN_BSTR aSource, IN_BSTR aDest,
2246 IN_BSTR aUsername, IN_BSTR aPassword,
2247 ULONG aFlags, IProgress **aProgress)
2248{
2249#ifndef VBOX_WITH_GUEST_CONTROL
2250 ReturnComNotImplemented();
2251#else /* VBOX_WITH_GUEST_CONTROL */
2252 CheckComArgStrNotEmptyOrNull(aSource);
2253 CheckComArgStrNotEmptyOrNull(aDest);
2254 CheckComArgStrNotEmptyOrNull(aUsername);
2255 CheckComArgStrNotEmptyOrNull(aPassword);
2256 CheckComArgOutPointerValid(aProgress);
2257
2258 AutoCaller autoCaller(this);
2259 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2260
2261 /* Validate flags. */
2262 if (aFlags != CopyFileFlag_None)
2263 {
2264 if ( !(aFlags & CopyFileFlag_Recursive)
2265 && !(aFlags & CopyFileFlag_Update)
2266 && !(aFlags & CopyFileFlag_FollowLinks))
2267 {
2268 return setError(E_INVALIDARG, tr("Unknown flags (%#x)"), aFlags);
2269 }
2270 }
2271
2272 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2273
2274 HRESULT rc = S_OK;
2275
2276 ComObjPtr<Progress> progress;
2277 try
2278 {
2279 /* Create the progress object. */
2280 progress.createObject();
2281
2282 rc = progress->init(static_cast<IGuest*>(this),
2283 Bstr(tr("Copying file from guest to host")).raw(),
2284 TRUE /* aCancelable */);
2285 if (FAILED(rc)) throw rc;
2286
2287 /* Initialize our worker task. */
2288 GuestTask *pTask = new GuestTask(GuestTask::TaskType_CopyFileFromGuest, this, progress);
2289 AssertPtr(pTask);
2290 std::auto_ptr<GuestTask> task(pTask);
2291
2292 /* Assign data - aSource is the source file on the host,
2293 * aDest reflects the full path on the guest. */
2294 task->strSource = (Utf8Str(aSource));
2295 task->strDest = (Utf8Str(aDest));
2296 task->strUserName = (Utf8Str(aUsername));
2297 task->strPassword = (Utf8Str(aPassword));
2298 task->uFlags = aFlags;
2299
2300 rc = task->startThread();
2301 if (FAILED(rc)) throw rc;
2302
2303 /* Don't destruct on success. */
2304 task.release();
2305 }
2306 catch (HRESULT aRC)
2307 {
2308 rc = aRC;
2309 }
2310
2311 if (SUCCEEDED(rc))
2312 {
2313 /* Return progress to the caller. */
2314 progress.queryInterfaceTo(aProgress);
2315 }
2316 return rc;
2317#endif /* VBOX_WITH_GUEST_CONTROL */
2318}
2319
2320STDMETHODIMP Guest::CopyToGuest(IN_BSTR aSource, IN_BSTR aDest,
2321 IN_BSTR aUsername, IN_BSTR aPassword,
2322 ULONG aFlags, IProgress **aProgress)
2323{
2324#ifndef VBOX_WITH_GUEST_CONTROL
2325 ReturnComNotImplemented();
2326#else /* VBOX_WITH_GUEST_CONTROL */
2327 CheckComArgStrNotEmptyOrNull(aSource);
2328 CheckComArgStrNotEmptyOrNull(aDest);
2329 CheckComArgStrNotEmptyOrNull(aUsername);
2330 CheckComArgStrNotEmptyOrNull(aPassword);
2331 CheckComArgOutPointerValid(aProgress);
2332
2333 AutoCaller autoCaller(this);
2334 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2335
2336 /* Validate flags. */
2337 if (aFlags != CopyFileFlag_None)
2338 {
2339 if ( !(aFlags & CopyFileFlag_Recursive)
2340 && !(aFlags & CopyFileFlag_Update)
2341 && !(aFlags & CopyFileFlag_FollowLinks))
2342 {
2343 return setError(E_INVALIDARG, tr("Unknown flags (%#x)"), aFlags);
2344 }
2345 }
2346
2347 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2348
2349 HRESULT rc = S_OK;
2350
2351 ComObjPtr<Progress> progress;
2352 try
2353 {
2354 /* Create the progress object. */
2355 progress.createObject();
2356
2357 rc = progress->init(static_cast<IGuest*>(this),
2358 Bstr(tr("Copying file from host to guest")).raw(),
2359 TRUE /* aCancelable */);
2360 if (FAILED(rc)) throw rc;
2361
2362 /* Initialize our worker task. */
2363 GuestTask *pTask = new GuestTask(GuestTask::TaskType_CopyFileToGuest, this, progress);
2364 AssertPtr(pTask);
2365 std::auto_ptr<GuestTask> task(pTask);
2366
2367 /* Assign data - aSource is the source file on the host,
2368 * aDest reflects the full path on the guest. */
2369 task->strSource = (Utf8Str(aSource));
2370 task->strDest = (Utf8Str(aDest));
2371 task->strUserName = (Utf8Str(aUsername));
2372 task->strPassword = (Utf8Str(aPassword));
2373 task->uFlags = aFlags;
2374
2375 rc = task->startThread();
2376 if (FAILED(rc)) throw rc;
2377
2378 /* Don't destruct on success. */
2379 task.release();
2380 }
2381 catch (HRESULT aRC)
2382 {
2383 rc = aRC;
2384 }
2385
2386 if (SUCCEEDED(rc))
2387 {
2388 /* Return progress to the caller. */
2389 progress.queryInterfaceTo(aProgress);
2390 }
2391 return rc;
2392#endif /* VBOX_WITH_GUEST_CONTROL */
2393}
2394
2395STDMETHODIMP Guest::UpdateGuestAdditions(IN_BSTR aSource, ULONG aFlags, IProgress **aProgress)
2396{
2397#ifndef VBOX_WITH_GUEST_CONTROL
2398 ReturnComNotImplemented();
2399#else /* VBOX_WITH_GUEST_CONTROL */
2400 CheckComArgStrNotEmptyOrNull(aSource);
2401 CheckComArgOutPointerValid(aProgress);
2402
2403 AutoCaller autoCaller(this);
2404 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2405
2406 /* Validate flags. */
2407 if (aFlags)
2408 {
2409 if (!(aFlags & AdditionsUpdateFlag_WaitForUpdateStartOnly))
2410 return setError(E_INVALIDARG, tr("Unknown flags (%#x)"), aFlags);
2411 }
2412
2413 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2414
2415 HRESULT rc = S_OK;
2416
2417 ComObjPtr<Progress> progress;
2418 try
2419 {
2420 /* Create the progress object. */
2421 progress.createObject();
2422
2423 rc = progress->init(static_cast<IGuest*>(this),
2424 Bstr(tr("Updating Guest Additions")).raw(),
2425 TRUE /* aCancelable */);
2426 if (FAILED(rc)) throw rc;
2427
2428 /* Initialize our worker task. */
2429 GuestTask *pTask = new GuestTask(GuestTask::TaskType_UpdateGuestAdditions, this, progress);
2430 AssertPtr(pTask);
2431 std::auto_ptr<GuestTask> task(pTask);
2432
2433 /* Assign data - in that case aSource is the full path
2434 * to the Guest Additions .ISO we want to mount. */
2435 task->strSource = (Utf8Str(aSource));
2436 task->uFlags = aFlags;
2437
2438 rc = task->startThread();
2439 if (FAILED(rc)) throw rc;
2440
2441 /* Don't destruct on success. */
2442 task.release();
2443 }
2444 catch (HRESULT aRC)
2445 {
2446 rc = aRC;
2447 }
2448
2449 if (SUCCEEDED(rc))
2450 {
2451 /* Return progress to the caller. */
2452 progress.queryInterfaceTo(aProgress);
2453 }
2454 return rc;
2455#endif /* VBOX_WITH_GUEST_CONTROL */
2456}
2457
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