VirtualBox

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

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

GuestCtrl: Fixed unknown PIDs after retrieving output.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 87.0 KB
Line 
1/* $Id: GuestCtrlImpl.cpp 39991 2012-02-03 16:45:00Z 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.215389.xyz. 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 /* Just reach through flags. */
734 case PROC_STS_TES:
735 case PROC_STS_TOK:
736 vrc = processSetStatus(pData->u32PID,
737 (ExecuteProcessStatus_T)pData->u32Status,
738 0 /* Exit code. */, pData->u32Flags);
739 break;
740 /* Interprete u32Flags as the guest process' exit code. */
741 default:
742 vrc = processSetStatus(pData->u32PID,
743 (ExecuteProcessStatus_T)pData->u32Status,
744 pData->u32Flags /* Exit code. */, 0 /* Flags. */);
745
746 break;
747 }
748 }
749
750 /* Do progress handling. */
751 switch (pData->u32Status)
752 {
753 case PROC_STS_STARTED:
754 vrc = callbackMoveForward(uContextID, Guest::tr("Waiting for process to exit ..."));
755 LogRel(("Guest process (PID %u) started\n", pData->u32PID)); /** @todo Add process name */
756 break;
757
758 case PROC_STS_TEN: /* Terminated normally. */
759 vrc = callbackNotifyComplete(uContextID);
760 LogRel(("Guest process (PID %u) exited normally\n", pData->u32PID)); /** @todo Add process name */
761 break;
762
763 case PROC_STS_TEA: /* Terminated abnormally. */
764 LogRel(("Guest process (PID %u) terminated abnormally with exit code = %u\n",
765 pData->u32PID, pData->u32Flags)); /** @todo Add process name */
766 errMsg = Utf8StrFmt(Guest::tr("Process terminated abnormally with status '%u'"),
767 pData->u32Flags);
768 rcCallback = VERR_GENERAL_FAILURE; /** @todo */
769 break;
770
771 case PROC_STS_TES: /* Terminated through signal. */
772 LogRel(("Guest process (PID %u) terminated through signal with exit code = %u\n",
773 pData->u32PID, pData->u32Flags)); /** @todo Add process name */
774 errMsg = Utf8StrFmt(Guest::tr("Process terminated via signal with status '%u'"),
775 pData->u32Flags);
776 rcCallback = VERR_GENERAL_FAILURE; /** @todo */
777 break;
778
779 case PROC_STS_TOK:
780 LogRel(("Guest process (PID %u) timed out and was killed\n", pData->u32PID)); /** @todo Add process name */
781 errMsg = Utf8StrFmt(Guest::tr("Process timed out and was killed"));
782 rcCallback = VERR_TIMEOUT;
783 break;
784
785 case PROC_STS_TOA:
786 LogRel(("Guest process (PID %u) timed out and could not be killed\n", pData->u32PID)); /** @todo Add process name */
787 errMsg = Utf8StrFmt(Guest::tr("Process timed out and could not be killed"));
788 rcCallback = VERR_TIMEOUT;
789 break;
790
791 case PROC_STS_DWN:
792 LogRel(("Guest process (PID %u) killed because system is shutting down\n", pData->u32PID)); /** @todo Add process name */
793 /*
794 * If u32Flags has ExecuteProcessFlag_IgnoreOrphanedProcesses set, we don't report an error to
795 * our progress object. This is helpful for waiters which rely on the success of our progress object
796 * even if the executed process was killed because the system/VBoxService is shutting down.
797 *
798 * In this case u32Flags contains the actual execution flags reached in via Guest::ExecuteProcess().
799 */
800 if (pData->u32Flags & ExecuteProcessFlag_IgnoreOrphanedProcesses)
801 {
802 vrc = callbackNotifyComplete(uContextID);
803 }
804 else
805 {
806 errMsg = Utf8StrFmt(Guest::tr("Process killed because system is shutting down"));
807 rcCallback = VERR_CANCELLED;
808 }
809 break;
810
811 case PROC_STS_ERROR:
812 if (pData->u32PID)
813 {
814 LogRel(("Guest process (PID %u) could not be started because of rc=%Rrc\n",
815 pData->u32PID, pData->u32Flags)); /** @todo Add process name */
816 }
817 else
818 {
819 switch (pData->u32Flags)
820 {
821 case VERR_MAX_PROCS_REACHED:
822 LogRel(("Guest process could not be started because maximum number of parallel guest processes has been reached\n"));
823 break;
824
825 default:
826 LogRel(("Guest process could not be started because of rc=%Rrc\n",
827 pData->u32Flags));
828 }
829
830 }
831 errMsg = Utf8StrFmt(Guest::tr("Process execution failed with rc=%Rrc"), pData->u32Flags);
832 rcCallback = pData->u32Flags; /* Report back rc. */
833 break;
834
835 default:
836 vrc = VERR_INVALID_PARAMETER;
837 break;
838 }
839 }
840 else
841 {
842 errMsg = Utf8StrFmt(Guest::tr("Process execution canceled"));
843 rcCallback = VERR_CANCELLED;
844 }
845
846 /* Do we need to handle the callback error? */
847 if (RT_FAILURE(rcCallback))
848 {
849 AssertMsg(!errMsg.isEmpty(), ("Error message must not be empty!\n"));
850
851 /* Notify all callbacks which are still waiting on something
852 * which is related to the current PID. */
853 if (pData->u32PID)
854 {
855 int rc2 = callbackNotifyAllForPID(pData->u32PID, rcCallback, errMsg.c_str());
856 if (RT_FAILURE(rc2))
857 {
858 LogFlowFunc(("Failed to notify other callbacks for PID=%u\n",
859 pData->u32PID));
860 if (RT_SUCCESS(vrc))
861 vrc = rc2;
862 }
863 }
864
865 /* Let the caller know what went wrong ... */
866 int rc2 = callbackNotifyEx(uContextID, rcCallback, errMsg.c_str());
867 if (RT_FAILURE(rc2))
868 {
869 LogFlowFunc(("Failed to notify callback CID=%u for PID=%u\n",
870 uContextID, pData->u32PID));
871 if (RT_SUCCESS(vrc))
872 vrc = rc2;
873 }
874 LogFlowFunc(("Process (CID=%u, status=%u) reported: %s\n",
875 uContextID, pData->u32Status, errMsg.c_str()));
876 }
877 LogFlowFunc(("Returned with rc=%Rrc, rcCallback=%Rrc\n",
878 vrc, rcCallback));
879 return vrc;
880}
881
882/* Function for handling the execution output notification. */
883int Guest::notifyCtrlExecOut(uint32_t u32Function,
884 PCALLBACKDATAEXECOUT pData)
885{
886 AssertReturn(u32Function, VERR_INVALID_PARAMETER);
887 AssertPtrReturn(pData, VERR_INVALID_PARAMETER);
888
889 uint32_t uContextID = pData->hdr.u32ContextID;
890 Assert(uContextID);
891
892 /* Scope write locks as much as possible. */
893 {
894 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
895
896 LogFlowFunc(("Output status (CID=%u, pData=0x%p)\n",
897 uContextID, pData));
898
899 PCALLBACKDATAEXECOUT pCallbackData =
900 (PCALLBACKDATAEXECOUT)callbackGetUserDataMutableRaw(uContextID, NULL /* cbData */);
901 if (pCallbackData)
902 {
903 pCallbackData->u32PID = pData->u32PID;
904 pCallbackData->u32HandleId = pData->u32HandleId;
905 pCallbackData->u32Flags = pData->u32Flags;
906
907 /* Make sure we really got something! */
908 if ( pData->cbData
909 && pData->pvData)
910 {
911 callbackFreeUserData(pCallbackData->pvData);
912
913 /* Allocate data buffer and copy it */
914 pCallbackData->pvData = RTMemAlloc(pData->cbData);
915 pCallbackData->cbData = pData->cbData;
916
917 AssertReturn(pCallbackData->pvData, VERR_NO_MEMORY);
918 memcpy(pCallbackData->pvData, pData->pvData, pData->cbData);
919 }
920 else /* Nothing received ... */
921 {
922 pCallbackData->pvData = NULL;
923 pCallbackData->cbData = 0;
924 }
925 }
926 /* If pCallbackData is NULL this might be an old request for which no user data
927 * might exist anymore. */
928 }
929
930 int vrc;
931 if (callbackIsCanceled(pData->u32PID))
932 {
933 vrc = callbackNotifyEx(uContextID, VERR_CANCELLED,
934 Guest::tr("The output operation was canceled"));
935 }
936 else
937 vrc = callbackNotifyComplete(uContextID);
938
939 return vrc;
940}
941
942/* Function for handling the execution input status notification. */
943int Guest::notifyCtrlExecInStatus(uint32_t u32Function,
944 PCALLBACKDATAEXECINSTATUS pData)
945{
946 AssertReturn(u32Function, VERR_INVALID_PARAMETER);
947 AssertPtrReturn(pData, VERR_INVALID_PARAMETER);
948
949 uint32_t uContextID = pData->hdr.u32ContextID;
950 Assert(uContextID);
951
952 /* Scope write locks as much as possible. */
953 {
954 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
955
956 LogFlowFunc(("Input status (CID=%u, pData=0x%p)\n",
957 uContextID, pData));
958
959 PCALLBACKDATAEXECINSTATUS pCallbackData =
960 (PCALLBACKDATAEXECINSTATUS)callbackGetUserDataMutableRaw(uContextID, NULL /* cbData */);
961 if (pCallbackData)
962 {
963 /* Save bytes processed. */
964 pCallbackData->cbProcessed = pData->cbProcessed;
965 pCallbackData->u32Status = pData->u32Status;
966 pCallbackData->u32Flags = pData->u32Flags;
967 pCallbackData->u32PID = pData->u32PID;
968 }
969 /* If pCallbackData is NULL this might be an old request for which no user data
970 * might exist anymore. */
971 }
972
973 return callbackNotifyComplete(uContextID);
974}
975
976int Guest::notifyCtrlClientDisconnected(uint32_t u32Function,
977 PCALLBACKDATACLIENTDISCONNECTED pData)
978{
979 /* u32Function is 0. */
980 AssertPtrReturn(pData, VERR_INVALID_PARAMETER);
981
982 uint32_t uContextID = pData->hdr.u32ContextID;
983 Assert(uContextID);
984
985 LogFlowFunc(("Client disconnected (CID=%u)\n,", uContextID));
986
987 return callbackNotifyEx(uContextID, VERR_CANCELLED,
988 Guest::tr("Client disconnected"));
989}
990
991/**
992 * Gets guest process information. Removes the process from the map
993 * after the process was marked as exited/terminated.
994 *
995 * @return IPRT status code.
996 * @param u32PID PID of process to get status for.
997 * @param pProcess Where to store the process information.
998 * @param fRemove Flag indicating whether to remove the
999 * process from the map when process marked a
1000 * exited/terminated.
1001 */
1002int Guest::processGetStatus(uint32_t u32PID, PVBOXGUESTCTRL_PROCESS pProcess,
1003 bool fRemove)
1004{
1005 AssertReturn(u32PID, VERR_INVALID_PARAMETER);
1006
1007 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1008
1009 GuestProcessMapIter it = mGuestProcessMap.find(u32PID);
1010 if (it != mGuestProcessMap.end())
1011 {
1012 if (pProcess)
1013 {
1014 pProcess->mStatus = it->second.mStatus;
1015 pProcess->mExitCode = it->second.mExitCode;
1016 pProcess->mFlags = it->second.mFlags;
1017 }
1018
1019 /* If the is marked as stopped/terminated
1020 * remove it from the map. */
1021 if ( fRemove
1022 && it->second.mStatus != ExecuteProcessStatus_Started)
1023 {
1024 mGuestProcessMap.erase(it);
1025 }
1026
1027 return VINF_SUCCESS;
1028 }
1029
1030 return VERR_NOT_FOUND;
1031}
1032
1033int Guest::processSetStatus(uint32_t u32PID, ExecuteProcessStatus_T enmStatus, uint32_t uExitCode, uint32_t uFlags)
1034{
1035 AssertReturn(u32PID, VERR_INVALID_PARAMETER);
1036
1037 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1038
1039 GuestProcessMapIter it = mGuestProcessMap.find(u32PID);
1040 if (it != mGuestProcessMap.end())
1041 {
1042 it->second.mStatus = enmStatus;
1043 it->second.mExitCode = uExitCode;
1044 it->second.mFlags = uFlags;
1045 }
1046 else
1047 {
1048 VBOXGUESTCTRL_PROCESS process;
1049
1050 process.mStatus = enmStatus;
1051 process.mExitCode = uExitCode;
1052 process.mFlags = uFlags;
1053
1054 mGuestProcessMap[u32PID] = process;
1055 }
1056
1057 return VINF_SUCCESS;
1058}
1059
1060HRESULT Guest::handleErrorCompletion(int rc)
1061{
1062 HRESULT hRC;
1063 if (rc == VERR_NOT_FOUND)
1064 hRC = setErrorNoLog(VBOX_E_VM_ERROR,
1065 tr("VMM device is not available (is the VM running?)"));
1066 else if (rc == VERR_CANCELLED)
1067 hRC = setErrorNoLog(VBOX_E_IPRT_ERROR,
1068 tr("Process execution has been canceled"));
1069 else if (rc == VERR_TIMEOUT)
1070 hRC= setErrorNoLog(VBOX_E_IPRT_ERROR,
1071 tr("The guest did not respond within time"));
1072 else
1073 hRC = setErrorNoLog(E_UNEXPECTED,
1074 tr("Waiting for completion failed with error %Rrc"), rc);
1075 return hRC;
1076}
1077
1078HRESULT Guest::handleErrorHGCM(int rc)
1079{
1080 HRESULT hRC;
1081 if (rc == VERR_INVALID_VM_HANDLE)
1082 hRC = setErrorNoLog(VBOX_E_VM_ERROR,
1083 tr("VMM device is not available (is the VM running?)"));
1084 else if (rc == VERR_NOT_FOUND)
1085 hRC = setErrorNoLog(VBOX_E_IPRT_ERROR,
1086 tr("The guest execution service is not ready (yet)"));
1087 else if (rc == VERR_HGCM_SERVICE_NOT_FOUND)
1088 hRC= setErrorNoLog(VBOX_E_IPRT_ERROR,
1089 tr("The guest execution service is not available"));
1090 else /* HGCM call went wrong. */
1091 hRC = setErrorNoLog(E_UNEXPECTED,
1092 tr("The HGCM call failed with error %Rrc"), rc);
1093 return hRC;
1094}
1095#endif /* VBOX_WITH_GUEST_CONTROL */
1096
1097STDMETHODIMP Guest::ExecuteProcess(IN_BSTR aCommand, ULONG aFlags,
1098 ComSafeArrayIn(IN_BSTR, aArguments), ComSafeArrayIn(IN_BSTR, aEnvironment),
1099 IN_BSTR aUsername, IN_BSTR aPassword,
1100 ULONG aTimeoutMS, ULONG *aPID, IProgress **aProgress)
1101{
1102/** @todo r=bird: Eventually we should clean up all the timeout parameters
1103 * in the API and have the same way of specifying infinite waits! */
1104#ifndef VBOX_WITH_GUEST_CONTROL
1105 ReturnComNotImplemented();
1106#else /* VBOX_WITH_GUEST_CONTROL */
1107 using namespace guestControl;
1108
1109 CheckComArgStrNotEmptyOrNull(aCommand);
1110 CheckComArgOutPointerValid(aPID);
1111 CheckComArgOutPointerValid(aProgress);
1112
1113 /* Do not allow anonymous executions (with system rights). */
1114 if (RT_UNLIKELY((aUsername) == NULL || *(aUsername) == '\0'))
1115 return setError(E_INVALIDARG, tr("No user name specified"));
1116
1117 LogRel(("Executing guest process \"%s\" as user \"%s\" ...\n",
1118 Utf8Str(aCommand).c_str(), Utf8Str(aUsername).c_str()));
1119
1120 return executeProcessInternal(aCommand, aFlags, ComSafeArrayInArg(aArguments),
1121 ComSafeArrayInArg(aEnvironment),
1122 aUsername, aPassword, aTimeoutMS, aPID, aProgress, NULL /* rc */);
1123#endif
1124}
1125
1126#ifdef VBOX_WITH_GUEST_CONTROL
1127/**
1128 * Executes and waits for an internal tool (that is, a tool which is integrated into
1129 * VBoxService, beginning with "vbox_" (e.g. "vbox_ls")) to finish its operation.
1130 *
1131 * @return HRESULT
1132 * @param aTool Name of tool to execute.
1133 * @param aDescription Friendly description of the operation.
1134 * @param aFlags Execution flags.
1135 * @param aUsername Username to execute tool under.
1136 * @param aPassword The user's password.
1137 * @param uFlagsToAdd ExecuteProcessFlag flags to add to the execution operation.
1138 * @param aProgress Pointer which receives the tool's progress object. Optional.
1139 * @param aPID Pointer which receives the tool's PID. Optional.
1140 */
1141HRESULT Guest::executeAndWaitForTool(IN_BSTR aTool, IN_BSTR aDescription,
1142 ComSafeArrayIn(IN_BSTR, aArguments), ComSafeArrayIn(IN_BSTR, aEnvironment),
1143 IN_BSTR aUsername, IN_BSTR aPassword,
1144 ULONG uFlagsToAdd,
1145 GuestCtrlStreamObjects *pObjStdOut, GuestCtrlStreamObjects *pObjStdErr,
1146 IProgress **aProgress, ULONG *aPID)
1147{
1148 ComPtr<IProgress> progressTool;
1149 ULONG uPID;
1150 ULONG uFlags = ExecuteProcessFlag_Hidden;
1151 if (uFlagsToAdd)
1152 uFlags |= uFlagsToAdd;
1153
1154 bool fWaitForOutput = false;
1155 if ( ( (uFlags & ExecuteProcessFlag_WaitForStdOut)
1156 && pObjStdOut)
1157 || ( (uFlags & ExecuteProcessFlag_WaitForStdErr)
1158 && pObjStdErr))
1159 {
1160 fWaitForOutput = true;
1161 }
1162
1163 HRESULT rc = ExecuteProcess(aTool,
1164 uFlags,
1165 ComSafeArrayInArg(aArguments),
1166 ComSafeArrayInArg(aEnvironment),
1167 aUsername, aPassword,
1168 0 /* No timeout. */,
1169 &uPID, progressTool.asOutParam());
1170 if ( SUCCEEDED(rc)
1171 && fWaitForOutput)
1172 {
1173 BOOL fCompleted;
1174 while ( SUCCEEDED(progressTool->COMGETTER(Completed)(&fCompleted))
1175 && !fCompleted)
1176 {
1177 BOOL fCanceled;
1178 rc = progressTool->COMGETTER(Canceled)(&fCanceled);
1179 AssertComRC(rc);
1180 if (fCanceled)
1181 {
1182 rc = setErrorNoLog(VBOX_E_IPRT_ERROR,
1183 tr("%s was cancelled"), Utf8Str(aDescription).c_str());
1184 break;
1185 }
1186
1187 if ( (uFlags & ExecuteProcessFlag_WaitForStdOut)
1188 && pObjStdOut)
1189 {
1190 rc = executeStreamParse(uPID, ProcessOutputFlag_None /* StdOut */, *pObjStdOut);
1191 }
1192
1193 if ( (uFlags & ExecuteProcessFlag_WaitForStdErr)
1194 && pObjStdErr)
1195 {
1196 rc = executeStreamParse(uPID, ProcessOutputFlag_StdErr, *pObjStdErr);
1197 }
1198
1199 if (FAILED(rc))
1200 break;
1201 }
1202 }
1203
1204 if (SUCCEEDED(rc))
1205 {
1206 if (aProgress)
1207 {
1208 /* Return the progress to the caller. */
1209 progressTool.queryInterfaceTo(aProgress);
1210 }
1211
1212 if (aPID)
1213 *aPID = uPID;
1214 }
1215
1216 return rc;
1217}
1218
1219HRESULT Guest::executeProcessResult(const char *pszCommand, const char *pszUser, ULONG ulTimeout,
1220 PCALLBACKDATAEXECSTATUS pExecStatus, ULONG *puPID)
1221{
1222 AssertPtrReturn(pExecStatus, E_INVALIDARG);
1223 AssertPtrReturn(puPID, E_INVALIDARG);
1224
1225 HRESULT rc = S_OK;
1226
1227 /* Did we get some status? */
1228 switch (pExecStatus->u32Status)
1229 {
1230 case PROC_STS_STARTED:
1231 /* Process is (still) running; get PID. */
1232 *puPID = pExecStatus->u32PID;
1233 break;
1234
1235 /* In any other case the process either already
1236 * terminated or something else went wrong, so no PID ... */
1237 case PROC_STS_TEN: /* Terminated normally. */
1238 case PROC_STS_TEA: /* Terminated abnormally. */
1239 case PROC_STS_TES: /* Terminated through signal. */
1240 case PROC_STS_TOK:
1241 case PROC_STS_TOA:
1242 case PROC_STS_DWN:
1243 /*
1244 * Process (already) ended, but we want to get the
1245 * PID anyway to retrieve the output in a later call.
1246 */
1247 *puPID = pExecStatus->u32PID;
1248 break;
1249
1250 case PROC_STS_ERROR:
1251 {
1252 int vrc = pExecStatus->u32Flags; /* u32Flags member contains IPRT error code. */
1253 if (vrc == VERR_FILE_NOT_FOUND) /* This is the most likely error. */
1254 rc = setErrorNoLog(VBOX_E_IPRT_ERROR,
1255 tr("The file '%s' was not found on guest"), pszCommand);
1256 else if (vrc == VERR_PATH_NOT_FOUND)
1257 rc = setErrorNoLog(VBOX_E_IPRT_ERROR,
1258 tr("The path to file '%s' was not found on guest"), pszCommand);
1259 else if (vrc == VERR_BAD_EXE_FORMAT)
1260 rc = setErrorNoLog(VBOX_E_IPRT_ERROR,
1261 tr("The file '%s' is not an executable format on guest"), pszCommand);
1262 else if (vrc == VERR_AUTHENTICATION_FAILURE)
1263 rc = setErrorNoLog(VBOX_E_IPRT_ERROR,
1264 tr("The specified user '%s' was not able to logon on guest"), pszUser);
1265 else if (vrc == VERR_TIMEOUT)
1266 rc = setErrorNoLog(VBOX_E_IPRT_ERROR,
1267 tr("The guest did not respond within time (%ums)"), ulTimeout);
1268 else if (vrc == VERR_CANCELLED)
1269 rc = setErrorNoLog(VBOX_E_IPRT_ERROR,
1270 tr("The execution operation was canceled"));
1271 else if (vrc == VERR_PERMISSION_DENIED)
1272 rc = setErrorNoLog(VBOX_E_IPRT_ERROR,
1273 tr("Invalid user/password credentials"));
1274 else if (vrc == VERR_MAX_PROCS_REACHED)
1275 rc = setErrorNoLog(VBOX_E_IPRT_ERROR,
1276 tr("Concurrent guest process limit is reached"));
1277 else
1278 {
1279 if (pExecStatus && pExecStatus->u32Status == PROC_STS_ERROR)
1280 rc = setErrorNoLog(VBOX_E_IPRT_ERROR,
1281 tr("Process could not be started: %Rrc"), pExecStatus->u32Flags);
1282 else
1283 rc = setErrorNoLog(E_UNEXPECTED,
1284 tr("The service call failed with error %Rrc"), vrc);
1285 }
1286 }
1287 break;
1288
1289 case PROC_STS_UNDEFINED: /* . */
1290 rc = setErrorNoLog(VBOX_E_IPRT_ERROR,
1291 tr("The operation did not complete within time"));
1292 break;
1293
1294 default:
1295 AssertReleaseMsgFailed(("Process (PID %u) reported back an undefined state!\n",
1296 pExecStatus->u32PID));
1297 rc = E_UNEXPECTED;
1298 break;
1299 }
1300
1301 return rc;
1302}
1303
1304/**
1305 * TODO
1306 *
1307 * @return HRESULT
1308 * @param aObjName
1309 * @param pStreamBlock
1310 * @param pObjInfo
1311 * @param enmAddAttribs
1312 */
1313int Guest::executeStreamQueryFsObjInfo(IN_BSTR aObjName,
1314 GuestProcessStreamBlock &streamBlock,
1315 PRTFSOBJINFO pObjInfo,
1316 RTFSOBJATTRADD enmAddAttribs)
1317{
1318 Utf8Str Utf8ObjName(aObjName);
1319 int64_t iVal;
1320 int rc = streamBlock.GetInt64Ex("st_size", &iVal);
1321 if (RT_SUCCESS(rc))
1322 pObjInfo->cbObject = iVal;
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 LogFlowFunc(("Getting next stream block of PID=%u, Flags=%u; cbStrmSize=%u, cbStrmOff=%u\n",
1389 ulPID, ulFlags, stream.GetSize(), stream.GetOffset()));
1390
1391 int rc;
1392
1393 uint32_t cPairs = 0;
1394 bool fDrainStream = true;
1395
1396 do
1397 {
1398 rc = stream.ParseBlock(streamBlock);
1399 LogFlowFunc(("Parsing block rc=%Rrc, strmBlockCnt=%ld\n",
1400 rc, streamBlock.GetCount()));
1401
1402 if (RT_FAILURE(rc)) /* More data needed or empty buffer? */
1403 {
1404 if (fDrainStream)
1405 {
1406 SafeArray<BYTE> aData;
1407 HRESULT hr = getProcessOutputInternal(ulPID, ulFlags,
1408 0 /* Infinite timeout */,
1409 _64K, ComSafeArrayAsOutParam(aData), &rc);
1410 if (SUCCEEDED(hr))
1411 {
1412 LogFlowFunc(("Got %ld bytes of additional data\n", aData.size()));
1413
1414 if (aData.size())
1415 {
1416 rc = stream.AddData(aData.raw(), aData.size());
1417 if (RT_UNLIKELY(RT_FAILURE(rc)))
1418 break;
1419 }
1420
1421 /* Reset found pairs to not break out too early and let all the new
1422 * data to be parsed as well. */
1423 cPairs = 0;
1424 continue; /* Try one more time. */
1425 }
1426 else
1427 {
1428 LogFlowFunc(("Getting output returned hr=%Rhrc\n", hr));
1429
1430 /* No more output to drain from stream. */
1431 if (rc == VERR_NOT_FOUND)
1432 {
1433 fDrainStream = false;
1434 continue;
1435 }
1436
1437 break;
1438 }
1439 }
1440 else
1441 {
1442 /* We haved drained the stream as much as we can and reached the
1443 * end of our stream buffer -- that means that there simply is no
1444 * stream block anymore, which is ok. */
1445 if (rc == VERR_NO_DATA)
1446 rc = VINF_SUCCESS;
1447 break;
1448 }
1449 }
1450 else
1451 cPairs = streamBlock.GetCount();
1452 }
1453 while (!cPairs);
1454
1455 LogFlowFunc(("Returned with strmBlockCnt=%ld, cPairs=%ld, rc=%Rrc\n",
1456 streamBlock.GetCount(), cPairs, rc));
1457 return rc;
1458}
1459
1460/**
1461 * Tries to get the next upcoming value block from a started guest process
1462 * by first draining its output and then processing the received guest stream.
1463 *
1464 * @return IPRT status code.
1465 * @param ulPID PID of process to get/parse the output from.
1466 * @param ulFlags ?
1467 * @param stream Reference to process stream object to use.
1468 * @param streamBlock Reference that receives the next stream block data.
1469 *
1470 */
1471int Guest::executeStreamParseNextBlock(ULONG ulPID,
1472 ULONG ulFlags,
1473 GuestProcessStream &stream,
1474 GuestProcessStreamBlock &streamBlock)
1475{
1476 AssertReturn(!streamBlock.GetCount(), VERR_INVALID_PARAMETER);
1477
1478 int rc;
1479 do
1480 {
1481 rc = stream.ParseBlock(streamBlock);
1482 if (RT_FAILURE(rc))
1483 break;
1484 }
1485 while (!streamBlock.GetCount());
1486
1487 return rc;
1488}
1489
1490/**
1491 * Gets output from a formerly started guest process, tries to parse all of its guest
1492 * stream (as long as data is available) and returns a stream object which can contain
1493 * multiple stream blocks (which in turn then can contain key=value pairs).
1494 *
1495 * @return HRESULT
1496 * @param ulPID PID of process to get/parse the output from.
1497 * @param ulFlags ?
1498 * @param streamObjects Reference to a guest stream object structure for
1499 * storing the parsed data.
1500 */
1501HRESULT Guest::executeStreamParse(ULONG ulPID, ULONG ulFlags, GuestCtrlStreamObjects &streamObjects)
1502{
1503 GuestProcessStream stream;
1504 int rc = executeStreamDrain(ulPID, ulFlags, stream);
1505 if (RT_SUCCESS(rc))
1506 {
1507 do
1508 {
1509 /* Try to parse the stream output we gathered until now. If we still need more
1510 * data the parsing routine will tell us and we just do another poll round. */
1511 GuestProcessStreamBlock curBlock;
1512 rc = executeStreamParseNextBlock(ulPID, ulFlags, stream, curBlock);
1513 if (RT_SUCCESS(rc))
1514 streamObjects.push_back(curBlock);
1515 } while (RT_SUCCESS(rc));
1516
1517 if (rc == VERR_NO_DATA) /* End of data reached. */
1518 rc = VINF_SUCCESS;
1519 }
1520
1521 if (RT_FAILURE(rc))
1522 return setError(VBOX_E_IPRT_ERROR,
1523 tr("Error while parsing guest output (%Rrc)"), rc);
1524 return rc;
1525}
1526
1527/**
1528 * Waits for a fomerly started guest process to exit using its progress
1529 * object and returns its final status. Returns E_ABORT if guest process
1530 * was canceled.
1531 *
1532 * @return IPRT status code.
1533 * @param uPID PID of guest process to wait for.
1534 * @param pProgress Progress object to wait for.
1535 * @param uTimeoutMS Timeout (in ms) for waiting; use 0 for
1536 * an indefinite timeout.
1537 * @param pRetStatus Pointer where to store the final process
1538 * status. Optional.
1539 * @param puRetExitCode Pointer where to store the final process
1540 * exit code. Optional.
1541 */
1542HRESULT Guest::executeWaitForExit(ULONG uPID, ComPtr<IProgress> pProgress, ULONG uTimeoutMS,
1543 ExecuteProcessStatus_T *pRetStatus, ULONG *puRetExitCode)
1544{
1545 HRESULT rc = S_OK;
1546
1547 BOOL fCanceled = FALSE;
1548 if ( SUCCEEDED(pProgress->COMGETTER(Canceled(&fCanceled)))
1549 && fCanceled)
1550 {
1551 return E_ABORT;
1552 }
1553
1554 BOOL fCompleted = FALSE;
1555 if ( SUCCEEDED(pProgress->COMGETTER(Completed(&fCompleted)))
1556 && !fCompleted)
1557 {
1558 rc = pProgress->WaitForCompletion( !uTimeoutMS
1559 ? -1 /* No timeout */
1560 : uTimeoutMS);
1561 if (FAILED(rc))
1562 rc = setError(VBOX_E_IPRT_ERROR,
1563 tr("Waiting for guest process to end failed (%Rhrc)"),
1564 rc);
1565 }
1566
1567 if (SUCCEEDED(rc))
1568 {
1569 ULONG uExitCode, uRetFlags;
1570 ExecuteProcessStatus_T enmStatus;
1571 HRESULT hRC = GetProcessStatus(uPID, &uExitCode, &uRetFlags, &enmStatus);
1572 if (FAILED(hRC))
1573 return hRC;
1574
1575 if (pRetStatus)
1576 *pRetStatus = enmStatus;
1577 if (puRetExitCode)
1578 *puRetExitCode = uExitCode;
1579 /** @todo Flags? */
1580 }
1581
1582 return rc;
1583}
1584
1585/**
1586 * Does the actual guest process execution, internal function.
1587 *
1588 * @return HRESULT
1589 * @param aCommand Command line to execute.
1590 * @param aFlags Execution flags.
1591 * @param Username Username to execute the process with.
1592 * @param aPassword The user's password.
1593 * @param aTimeoutMS Timeout (in ms) to wait for the execution operation.
1594 * @param aPID Pointer that receives the guest process' PID.
1595 * @param aProgress Pointer that receives the guest process' progress object.
1596 * @param pRC Pointer that receives the internal IPRT return code. Optional.
1597 */
1598HRESULT Guest::executeProcessInternal(IN_BSTR aCommand, ULONG aFlags,
1599 ComSafeArrayIn(IN_BSTR, aArguments), ComSafeArrayIn(IN_BSTR, aEnvironment),
1600 IN_BSTR aUsername, IN_BSTR aPassword,
1601 ULONG aTimeoutMS, ULONG *aPID, IProgress **aProgress, int *pRC)
1602{
1603/** @todo r=bird: Eventually we should clean up all the timeout parameters
1604 * in the API and have the same way of specifying infinite waits! */
1605 using namespace guestControl;
1606
1607 AutoCaller autoCaller(this);
1608 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1609
1610 /* Validate flags. */
1611 if (aFlags != ExecuteProcessFlag_None)
1612 {
1613 if ( !(aFlags & ExecuteProcessFlag_IgnoreOrphanedProcesses)
1614 && !(aFlags & ExecuteProcessFlag_WaitForProcessStartOnly)
1615 && !(aFlags & ExecuteProcessFlag_Hidden)
1616 && !(aFlags & ExecuteProcessFlag_NoProfile)
1617 && !(aFlags & ExecuteProcessFlag_WaitForStdOut)
1618 && !(aFlags & ExecuteProcessFlag_WaitForStdErr))
1619 {
1620 if (pRC)
1621 *pRC = VERR_INVALID_PARAMETER;
1622 return setError(E_INVALIDARG, tr("Unknown flags (%#x)"), aFlags);
1623 }
1624 }
1625
1626 HRESULT rc = S_OK;
1627
1628 try
1629 {
1630 /*
1631 * Create progress object. Note that this is a multi operation
1632 * object to perform the following steps:
1633 * - Operation 1 (0): Create/start process.
1634 * - Operation 2 (1): Wait for process to exit.
1635 * If this progress completed successfully (S_OK), the process
1636 * started and exited normally. In any other case an error/exception
1637 * occurred.
1638 */
1639 ComObjPtr <Progress> pProgress;
1640 rc = pProgress.createObject();
1641 if (SUCCEEDED(rc))
1642 {
1643 rc = pProgress->init(static_cast<IGuest*>(this),
1644 Bstr(tr("Executing process")).raw(),
1645 TRUE,
1646 2, /* Number of operations. */
1647 Bstr(tr("Starting process ...")).raw()); /* Description of first stage. */
1648 }
1649 ComAssertComRC(rc);
1650
1651 /*
1652 * Prepare process execution.
1653 */
1654 int vrc = VINF_SUCCESS;
1655 Utf8Str Utf8Command(aCommand);
1656
1657 /* Adjust timeout. If set to 0, we define
1658 * an infinite timeout. */
1659 if (aTimeoutMS == 0)
1660 aTimeoutMS = UINT32_MAX;
1661
1662 /* Prepare arguments. */
1663 char **papszArgv = NULL;
1664 uint32_t uNumArgs = 0;
1665 if (aArguments)
1666 {
1667 com::SafeArray<IN_BSTR> args(ComSafeArrayInArg(aArguments));
1668 uNumArgs = args.size();
1669 papszArgv = (char**)RTMemAlloc(sizeof(char*) * (uNumArgs + 1));
1670 AssertReturn(papszArgv, E_OUTOFMEMORY);
1671 for (unsigned i = 0; RT_SUCCESS(vrc) && i < uNumArgs; i++)
1672 vrc = RTUtf16ToUtf8(args[i], &papszArgv[i]);
1673 papszArgv[uNumArgs] = NULL;
1674 }
1675
1676 Utf8Str Utf8UserName(aUsername);
1677 Utf8Str Utf8Password(aPassword);
1678 if (RT_SUCCESS(vrc))
1679 {
1680 uint32_t uContextID = 0;
1681
1682 char *pszArgs = NULL;
1683 if (uNumArgs > 0)
1684 vrc = RTGetOptArgvToString(&pszArgs, papszArgv, RTGETOPTARGV_CNV_QUOTE_MS_CRT);
1685 if (RT_SUCCESS(vrc))
1686 {
1687 uint32_t cbArgs = pszArgs ? strlen(pszArgs) + 1 : 0; /* Include terminating zero. */
1688
1689 /* Prepare environment. */
1690 void *pvEnv = NULL;
1691 uint32_t uNumEnv = 0;
1692 uint32_t cbEnv = 0;
1693 if (aEnvironment)
1694 {
1695 com::SafeArray<IN_BSTR> env(ComSafeArrayInArg(aEnvironment));
1696
1697 for (unsigned i = 0; i < env.size(); i++)
1698 {
1699 vrc = prepareExecuteEnv(Utf8Str(env[i]).c_str(), &pvEnv, &cbEnv, &uNumEnv);
1700 if (RT_FAILURE(vrc))
1701 break;
1702 }
1703 }
1704
1705 if (RT_SUCCESS(vrc))
1706 {
1707 VBOXGUESTCTRL_CALLBACK callback;
1708 vrc = callbackInit(&callback, VBOXGUESTCTRLCALLBACKTYPE_EXEC_START, pProgress);
1709 if (RT_SUCCESS(vrc))
1710 {
1711 /* Allocate and assign payload. */
1712 callback.cbData = sizeof(CALLBACKDATAEXECSTATUS);
1713 PCALLBACKDATAEXECSTATUS pData = (PCALLBACKDATAEXECSTATUS)RTMemAlloc(callback.cbData);
1714 AssertReturn(pData, E_OUTOFMEMORY);
1715 RT_BZERO(pData, callback.cbData);
1716 callback.pvData = pData;
1717 }
1718
1719 if (RT_SUCCESS(vrc))
1720 vrc = callbackAdd(&callback, &uContextID);
1721
1722 if (RT_SUCCESS(vrc))
1723 {
1724 VBOXHGCMSVCPARM paParms[15];
1725 int i = 0;
1726 paParms[i++].setUInt32(uContextID);
1727 paParms[i++].setPointer((void*)Utf8Command.c_str(), (uint32_t)Utf8Command.length() + 1);
1728 paParms[i++].setUInt32(aFlags);
1729 paParms[i++].setUInt32(uNumArgs);
1730 paParms[i++].setPointer((void*)pszArgs, cbArgs);
1731 paParms[i++].setUInt32(uNumEnv);
1732 paParms[i++].setUInt32(cbEnv);
1733 paParms[i++].setPointer((void*)pvEnv, cbEnv);
1734 paParms[i++].setPointer((void*)Utf8UserName.c_str(), (uint32_t)Utf8UserName.length() + 1);
1735 paParms[i++].setPointer((void*)Utf8Password.c_str(), (uint32_t)Utf8Password.length() + 1);
1736
1737 /*
1738 * If the WaitForProcessStartOnly flag is set, we only want to define and wait for a timeout
1739 * until the process was started - the process itself then gets an infinite timeout for execution.
1740 * This is handy when we want to start a process inside a worker thread within a certain timeout
1741 * but let the started process perform lengthly operations then.
1742 */
1743 if (aFlags & ExecuteProcessFlag_WaitForProcessStartOnly)
1744 paParms[i++].setUInt32(UINT32_MAX /* Infinite timeout */);
1745 else
1746 paParms[i++].setUInt32(aTimeoutMS);
1747
1748 VMMDev *pVMMDev = NULL;
1749 {
1750 /* Make sure mParent is valid, so set the read lock while using.
1751 * Do not keep this lock while doing the actual call, because in the meanwhile
1752 * another thread could request a write lock which would be a bad idea ... */
1753 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1754
1755 /* Forward the information to the VMM device. */
1756 AssertPtr(mParent);
1757 pVMMDev = mParent->getVMMDev();
1758 }
1759
1760 if (pVMMDev)
1761 {
1762 LogFlowFunc(("hgcmHostCall numParms=%d\n", i));
1763 vrc = pVMMDev->hgcmHostCall("VBoxGuestControlSvc", HOST_EXEC_CMD,
1764 i, paParms);
1765 }
1766 else
1767 vrc = VERR_INVALID_VM_HANDLE;
1768 }
1769 RTMemFree(pvEnv);
1770 }
1771 RTStrFree(pszArgs);
1772 }
1773
1774 if (RT_SUCCESS(vrc))
1775 {
1776 LogFlowFunc(("Waiting for HGCM callback (timeout=%RI32ms) ...\n", aTimeoutMS));
1777
1778 /*
1779 * Wait for the HGCM low level callback until the process
1780 * has been started (or something went wrong). This is necessary to
1781 * get the PID.
1782 */
1783
1784 PCALLBACKDATAEXECSTATUS pExecStatus = NULL;
1785
1786 /*
1787 * Wait for the first stage (=0) to complete (that is starting the process).
1788 */
1789 vrc = callbackWaitForCompletion(uContextID, 0 /* Stage */, aTimeoutMS);
1790 if (RT_SUCCESS(vrc))
1791 {
1792 vrc = callbackGetUserData(uContextID, NULL /* We know the type. */,
1793 (void**)&pExecStatus, NULL /* Don't need the size. */);
1794 if (RT_SUCCESS(vrc))
1795 {
1796 rc = executeProcessResult(Utf8Command.c_str(), Utf8UserName.c_str(), aTimeoutMS,
1797 pExecStatus, aPID);
1798 callbackFreeUserData(pExecStatus);
1799 }
1800 else
1801 {
1802 rc = setErrorNoLog(VBOX_E_IPRT_ERROR,
1803 tr("Unable to retrieve process execution status data"));
1804 }
1805 }
1806 else
1807 rc = handleErrorCompletion(vrc);
1808
1809 /*
1810 * Do *not* remove the callback yet - we might wait with the IProgress object on something
1811 * else (like end of process) ...
1812 */
1813 }
1814 else
1815 rc = handleErrorHGCM(vrc);
1816
1817 for (unsigned i = 0; i < uNumArgs; i++)
1818 RTMemFree(papszArgv[i]);
1819 RTMemFree(papszArgv);
1820 }
1821
1822 if (SUCCEEDED(rc))
1823 {
1824 /* Return the progress to the caller. */
1825 pProgress.queryInterfaceTo(aProgress);
1826 }
1827 else
1828 {
1829 if (!pRC) /* Skip logging internal calls. */
1830 LogRel(("Executing guest process \"%s\" as user \"%s\" failed with %Rrc\n",
1831 Utf8Command.c_str(), Utf8UserName.c_str(), vrc));
1832 }
1833
1834 if (pRC)
1835 *pRC = vrc;
1836 }
1837 catch (std::bad_alloc &)
1838 {
1839 rc = E_OUTOFMEMORY;
1840 }
1841 return rc;
1842}
1843#endif /* VBOX_WITH_GUEST_CONTROL */
1844
1845STDMETHODIMP Guest::SetProcessInput(ULONG aPID, ULONG aFlags, ULONG aTimeoutMS, ComSafeArrayIn(BYTE, aData), ULONG *aBytesWritten)
1846{
1847#ifndef VBOX_WITH_GUEST_CONTROL
1848 ReturnComNotImplemented();
1849#else /* VBOX_WITH_GUEST_CONTROL */
1850 using namespace guestControl;
1851
1852 CheckComArgExpr(aPID, aPID > 0);
1853 CheckComArgOutPointerValid(aBytesWritten);
1854
1855 /* Validate flags. */
1856 if (aFlags)
1857 {
1858 if (!(aFlags & ProcessInputFlag_EndOfFile))
1859 return setError(E_INVALIDARG, tr("Unknown flags (%#x)"), aFlags);
1860 }
1861
1862 AutoCaller autoCaller(this);
1863 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1864
1865 HRESULT rc = S_OK;
1866
1867 try
1868 {
1869 VBOXGUESTCTRL_PROCESS process;
1870 int vrc = processGetStatus(aPID, &process, false /* Don't remove */);
1871 if (RT_SUCCESS(vrc))
1872 {
1873 /* PID exists; check if process is still running. */
1874 if (process.mStatus != ExecuteProcessStatus_Started)
1875 rc = setError(VBOX_E_IPRT_ERROR,
1876 Guest::tr("Cannot inject input to not running process (PID %u)"), aPID);
1877 }
1878 else
1879 rc = setError(VBOX_E_IPRT_ERROR,
1880 Guest::tr("Cannot inject input to non-existent process (PID %u)"), aPID);
1881
1882 if (RT_SUCCESS(vrc))
1883 {
1884 uint32_t uContextID = 0;
1885
1886 /*
1887 * Create progress object.
1888 * This progress object, compared to the one in executeProgress() above,
1889 * is only single-stage local and is used to determine whether the operation
1890 * finished or got canceled.
1891 */
1892 ComObjPtr <Progress> pProgress;
1893 rc = pProgress.createObject();
1894 if (SUCCEEDED(rc))
1895 {
1896 rc = pProgress->init(static_cast<IGuest*>(this),
1897 Bstr(tr("Setting input for process")).raw(),
1898 TRUE /* Cancelable */);
1899 }
1900 if (FAILED(rc)) throw rc;
1901 ComAssert(!pProgress.isNull());
1902
1903 /* Adjust timeout. */
1904 if (aTimeoutMS == 0)
1905 aTimeoutMS = UINT32_MAX;
1906
1907 VBOXGUESTCTRL_CALLBACK callback;
1908 vrc = callbackInit(&callback, VBOXGUESTCTRLCALLBACKTYPE_EXEC_INPUT_STATUS, pProgress);
1909 if (RT_SUCCESS(vrc))
1910 {
1911 PCALLBACKDATAEXECINSTATUS pData = (PCALLBACKDATAEXECINSTATUS)callback.pvData;
1912
1913 /* Save PID + output flags for later use. */
1914 pData->u32PID = aPID;
1915 pData->u32Flags = aFlags;
1916 }
1917
1918 if (RT_SUCCESS(vrc))
1919 vrc = callbackAdd(&callback, &uContextID);
1920
1921 if (RT_SUCCESS(vrc))
1922 {
1923 com::SafeArray<BYTE> sfaData(ComSafeArrayInArg(aData));
1924 uint32_t cbSize = sfaData.size();
1925
1926 VBOXHGCMSVCPARM paParms[6];
1927 int i = 0;
1928 paParms[i++].setUInt32(uContextID);
1929 paParms[i++].setUInt32(aPID);
1930 paParms[i++].setUInt32(aFlags);
1931 paParms[i++].setPointer(sfaData.raw(), cbSize);
1932 paParms[i++].setUInt32(cbSize);
1933
1934 {
1935 VMMDev *pVMMDev = NULL;
1936 {
1937 /* Make sure mParent is valid, so set the read lock while using.
1938 * Do not keep this lock while doing the actual call, because in the meanwhile
1939 * another thread could request a write lock which would be a bad idea ... */
1940 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1941
1942 /* Forward the information to the VMM device. */
1943 AssertPtr(mParent);
1944 pVMMDev = mParent->getVMMDev();
1945 }
1946
1947 if (pVMMDev)
1948 {
1949 LogFlowFunc(("hgcmHostCall numParms=%d\n", i));
1950 vrc = pVMMDev->hgcmHostCall("VBoxGuestControlSvc", HOST_EXEC_SET_INPUT,
1951 i, paParms);
1952 if (RT_FAILURE(vrc))
1953 rc = handleErrorHGCM(vrc);
1954 }
1955 }
1956 }
1957
1958 if (RT_SUCCESS(vrc))
1959 {
1960 LogFlowFunc(("Waiting for HGCM callback ...\n"));
1961
1962 /*
1963 * Wait for getting back the input response from the guest.
1964 */
1965 vrc = callbackWaitForCompletion(uContextID, -1 /* No staging required */, aTimeoutMS);
1966 if (RT_SUCCESS(vrc))
1967 {
1968 PCALLBACKDATAEXECINSTATUS pExecStatusIn;
1969 vrc = callbackGetUserData(uContextID, NULL /* We know the type. */,
1970 (void**)&pExecStatusIn, NULL /* Don't need the size. */);
1971 if (RT_SUCCESS(vrc))
1972 {
1973 AssertPtr(pExecStatusIn);
1974 switch (pExecStatusIn->u32Status)
1975 {
1976 case INPUT_STS_WRITTEN:
1977 *aBytesWritten = pExecStatusIn->cbProcessed;
1978 break;
1979
1980 case INPUT_STS_ERROR:
1981 rc = setError(VBOX_E_IPRT_ERROR,
1982 tr("Client reported error %Rrc while processing input data"),
1983 pExecStatusIn->u32Flags);
1984 break;
1985
1986 case INPUT_STS_TERMINATED:
1987 rc = setError(VBOX_E_IPRT_ERROR,
1988 tr("Client terminated while processing input data"));
1989 break;
1990
1991 case INPUT_STS_OVERFLOW:
1992 rc = setError(VBOX_E_IPRT_ERROR,
1993 tr("Client reported buffer overflow while processing input data"));
1994 break;
1995
1996 default:
1997 /*AssertReleaseMsgFailed(("Client reported unknown input error, status=%u, flags=%u\n",
1998 pExecStatusIn->u32Status, pExecStatusIn->u32Flags));*/
1999 break;
2000 }
2001
2002 callbackFreeUserData(pExecStatusIn);
2003 }
2004 else
2005 {
2006 rc = setErrorNoLog(VBOX_E_IPRT_ERROR,
2007 tr("Unable to retrieve process input status data"));
2008 }
2009 }
2010 else
2011 rc = handleErrorCompletion(vrc);
2012 }
2013
2014 /* The callback isn't needed anymore -- just was kept locally. */
2015 callbackDestroy(uContextID);
2016
2017 /* Cleanup. */
2018 if (!pProgress.isNull())
2019 pProgress->uninit();
2020 pProgress.setNull();
2021 }
2022 }
2023 catch (std::bad_alloc &)
2024 {
2025 rc = E_OUTOFMEMORY;
2026 }
2027 return rc;
2028#endif
2029}
2030
2031STDMETHODIMP Guest::GetProcessOutput(ULONG aPID, ULONG aFlags, ULONG aTimeoutMS, LONG64 aSize, ComSafeArrayOut(BYTE, aData))
2032{
2033#ifndef VBOX_WITH_GUEST_CONTROL
2034 ReturnComNotImplemented();
2035#else /* VBOX_WITH_GUEST_CONTROL */
2036 using namespace guestControl;
2037
2038 return getProcessOutputInternal(aPID, aFlags, aTimeoutMS,
2039 aSize, ComSafeArrayOutArg(aData), NULL /* rc */);
2040#endif
2041}
2042
2043HRESULT Guest::getProcessOutputInternal(ULONG aPID, ULONG aFlags, ULONG aTimeoutMS,
2044 LONG64 aSize, ComSafeArrayOut(BYTE, aData), int *pRC)
2045{
2046/** @todo r=bird: Eventually we should clean up all the timeout parameters
2047 * in the API and have the same way of specifying infinite waits! */
2048#ifndef VBOX_WITH_GUEST_CONTROL
2049 ReturnComNotImplemented();
2050#else /* VBOX_WITH_GUEST_CONTROL */
2051 using namespace guestControl;
2052
2053 CheckComArgExpr(aPID, aPID > 0);
2054 if (aSize < 0)
2055 return setError(E_INVALIDARG, tr("The size argument (%lld) is negative"), aSize);
2056 if (aSize == 0)
2057 return setError(E_INVALIDARG, tr("The size (%lld) is zero"), aSize);
2058 if (aFlags)
2059 {
2060 if (!(aFlags & ProcessOutputFlag_StdErr))
2061 {
2062 return setError(E_INVALIDARG, tr("Unknown flags (%#x)"), aFlags);
2063 }
2064 }
2065
2066 AutoCaller autoCaller(this);
2067 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2068
2069 HRESULT rc = S_OK;
2070
2071 try
2072 {
2073 VBOXGUESTCTRL_PROCESS proc;
2074 int vrc = processGetStatus(aPID, &proc, false /* Don't remove */);
2075 if (RT_FAILURE(vrc))
2076 {
2077 rc = setError(VBOX_E_IPRT_ERROR,
2078 Guest::tr("Guest process (PID %u) does not exist"), aPID);
2079 }
2080 else
2081 {
2082 uint32_t uContextID = 0;
2083
2084 /*
2085 * Create progress object.
2086 * This progress object, compared to the one in executeProgress() above,
2087 * is only single-stage local and is used to determine whether the operation
2088 * finished or got canceled.
2089 */
2090 ComObjPtr <Progress> pProgress;
2091 rc = pProgress.createObject();
2092 if (SUCCEEDED(rc))
2093 {
2094 rc = pProgress->init(static_cast<IGuest*>(this),
2095 Bstr(tr("Getting output for guest process")).raw(),
2096 TRUE /* Cancelable */);
2097 }
2098 if (FAILED(rc)) throw rc;
2099 ComAssert(!pProgress.isNull());
2100
2101 /* Adjust timeout. */
2102 if (aTimeoutMS == 0)
2103 aTimeoutMS = UINT32_MAX;
2104
2105 /* Set handle ID. */
2106 uint32_t uHandleID = OUTPUT_HANDLE_ID_STDOUT; /* Default */
2107 if (aFlags & ProcessOutputFlag_StdErr)
2108 uHandleID = OUTPUT_HANDLE_ID_STDERR;
2109
2110 VBOXGUESTCTRL_CALLBACK callback;
2111 vrc = callbackInit(&callback, VBOXGUESTCTRLCALLBACKTYPE_EXEC_OUTPUT, pProgress);
2112 if (RT_SUCCESS(vrc))
2113 {
2114 PCALLBACKDATAEXECOUT pData = (PCALLBACKDATAEXECOUT)callback.pvData;
2115
2116 /* Save PID + output flags for later use. */
2117 pData->u32PID = aPID;
2118 pData->u32Flags = aFlags;
2119 }
2120
2121 if (RT_SUCCESS(vrc))
2122 vrc = callbackAdd(&callback, &uContextID);
2123
2124 if (RT_SUCCESS(vrc))
2125 {
2126 VBOXHGCMSVCPARM paParms[5];
2127 int i = 0;
2128 paParms[i++].setUInt32(uContextID);
2129 paParms[i++].setUInt32(aPID);
2130 paParms[i++].setUInt32(uHandleID);
2131 paParms[i++].setUInt32(0 /* Flags, none set yet */);
2132
2133 VMMDev *pVMMDev = NULL;
2134 {
2135 /* Make sure mParent is valid, so set the read lock while using.
2136 * Do not keep this lock while doing the actual call, because in the meanwhile
2137 * another thread could request a write lock which would be a bad idea ... */
2138 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2139
2140 /* Forward the information to the VMM device. */
2141 AssertPtr(mParent);
2142 pVMMDev = mParent->getVMMDev();
2143 }
2144
2145 if (pVMMDev)
2146 {
2147 LogFlowFunc(("hgcmHostCall numParms=%d\n", i));
2148 vrc = pVMMDev->hgcmHostCall("VBoxGuestControlSvc", HOST_EXEC_GET_OUTPUT,
2149 i, paParms);
2150 }
2151 }
2152
2153 if (RT_SUCCESS(vrc))
2154 {
2155 LogFlowFunc(("Waiting for HGCM callback (timeout=%RI32ms) ...\n", aTimeoutMS));
2156
2157 /*
2158 * Wait for the HGCM low level callback until the process
2159 * has been started (or something went wrong). This is necessary to
2160 * get the PID.
2161 */
2162
2163 /*
2164 * Wait for the first output callback notification to arrive.
2165 */
2166 vrc = callbackWaitForCompletion(uContextID, -1 /* No staging required */, aTimeoutMS);
2167 if (RT_SUCCESS(vrc))
2168 {
2169 PCALLBACKDATAEXECOUT pExecOut = NULL;
2170 vrc = callbackGetUserData(uContextID, NULL /* We know the type. */,
2171 (void**)&pExecOut, NULL /* Don't need the size. */);
2172 if (RT_SUCCESS(vrc))
2173 {
2174 com::SafeArray<BYTE> outputData((size_t)aSize);
2175
2176 if (pExecOut->cbData)
2177 {
2178 /* Do we need to resize the array? */
2179 if (pExecOut->cbData > aSize)
2180 outputData.resize(pExecOut->cbData);
2181
2182 /* Fill output in supplied out buffer. */
2183 memcpy(outputData.raw(), pExecOut->pvData, pExecOut->cbData);
2184 outputData.resize(pExecOut->cbData); /* Shrink to fit actual buffer size. */
2185 }
2186 else
2187 {
2188 /* No data within specified timeout available. */
2189 outputData.resize(0);
2190 }
2191
2192 /* Detach output buffer to output argument. */
2193 outputData.detachTo(ComSafeArrayOutArg(aData));
2194
2195 callbackFreeUserData(pExecOut);
2196 }
2197 else
2198 {
2199 rc = setErrorNoLog(VBOX_E_IPRT_ERROR,
2200 tr("Unable to retrieve process output data (%Rrc)"), vrc);
2201 }
2202 }
2203 else
2204 rc = handleErrorCompletion(vrc);
2205 }
2206 else
2207 rc = handleErrorHGCM(vrc);
2208
2209 /* The callback isn't needed anymore -- just was kept locally. */
2210 callbackDestroy(uContextID);
2211
2212 /* Cleanup. */
2213 if (!pProgress.isNull())
2214 pProgress->uninit();
2215 pProgress.setNull();
2216 }
2217
2218 if (pRC)
2219 *pRC = vrc;
2220 }
2221 catch (std::bad_alloc &)
2222 {
2223 rc = E_OUTOFMEMORY;
2224 }
2225 return rc;
2226#endif
2227}
2228
2229STDMETHODIMP Guest::GetProcessStatus(ULONG aPID, ULONG *aExitCode, ULONG *aFlags, ExecuteProcessStatus_T *aStatus)
2230{
2231#ifndef VBOX_WITH_GUEST_CONTROL
2232 ReturnComNotImplemented();
2233#else /* VBOX_WITH_GUEST_CONTROL */
2234
2235 AutoCaller autoCaller(this);
2236 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2237
2238 HRESULT rc = S_OK;
2239
2240 try
2241 {
2242 VBOXGUESTCTRL_PROCESS process;
2243 int vrc = processGetStatus(aPID, &process,
2244 true /* Remove when terminated */);
2245 if (RT_SUCCESS(vrc))
2246 {
2247 if (aExitCode)
2248 *aExitCode = process.mExitCode;
2249 if (aFlags)
2250 *aFlags = process.mFlags;
2251 if (aStatus)
2252 *aStatus = process.mStatus;
2253 }
2254 else
2255 rc = setError(VBOX_E_IPRT_ERROR,
2256 tr("Process (PID %u) not found!"), aPID);
2257 }
2258 catch (std::bad_alloc &)
2259 {
2260 rc = E_OUTOFMEMORY;
2261 }
2262 return rc;
2263#endif
2264}
2265
2266STDMETHODIMP Guest::CopyFromGuest(IN_BSTR aSource, IN_BSTR aDest,
2267 IN_BSTR aUsername, IN_BSTR aPassword,
2268 ULONG aFlags, IProgress **aProgress)
2269{
2270#ifndef VBOX_WITH_GUEST_CONTROL
2271 ReturnComNotImplemented();
2272#else /* VBOX_WITH_GUEST_CONTROL */
2273 CheckComArgStrNotEmptyOrNull(aSource);
2274 CheckComArgStrNotEmptyOrNull(aDest);
2275 CheckComArgOutPointerValid(aProgress);
2276
2277 /* Do not allow anonymous executions (with system rights). */
2278 if (RT_UNLIKELY((aUsername) == NULL || *(aUsername) == '\0'))
2279 return setError(E_INVALIDARG, tr("No user name specified"));
2280
2281 AutoCaller autoCaller(this);
2282 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2283
2284 /* Validate flags. */
2285 if (aFlags != CopyFileFlag_None)
2286 {
2287 if ( !(aFlags & CopyFileFlag_Recursive)
2288 && !(aFlags & CopyFileFlag_Update)
2289 && !(aFlags & CopyFileFlag_FollowLinks))
2290 {
2291 return setError(E_INVALIDARG, tr("Unknown flags (%#x)"), aFlags);
2292 }
2293 }
2294
2295 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2296
2297 HRESULT rc = S_OK;
2298
2299 ComObjPtr<Progress> progress;
2300 try
2301 {
2302 /* Create the progress object. */
2303 progress.createObject();
2304
2305 rc = progress->init(static_cast<IGuest*>(this),
2306 Bstr(tr("Copying file from guest to host")).raw(),
2307 TRUE /* aCancelable */);
2308 if (FAILED(rc)) throw rc;
2309
2310 /* Initialize our worker task. */
2311 GuestTask *pTask = new GuestTask(GuestTask::TaskType_CopyFileFromGuest, this, progress);
2312 AssertPtr(pTask);
2313 std::auto_ptr<GuestTask> task(pTask);
2314
2315 /* Assign data - aSource is the source file on the host,
2316 * aDest reflects the full path on the guest. */
2317 task->strSource = (Utf8Str(aSource));
2318 task->strDest = (Utf8Str(aDest));
2319 task->strUserName = (Utf8Str(aUsername));
2320 task->strPassword = (Utf8Str(aPassword));
2321 task->uFlags = aFlags;
2322
2323 rc = task->startThread();
2324 if (FAILED(rc)) throw rc;
2325
2326 /* Don't destruct on success. */
2327 task.release();
2328 }
2329 catch (HRESULT aRC)
2330 {
2331 rc = aRC;
2332 }
2333
2334 if (SUCCEEDED(rc))
2335 {
2336 /* Return progress to the caller. */
2337 progress.queryInterfaceTo(aProgress);
2338 }
2339 return rc;
2340#endif /* VBOX_WITH_GUEST_CONTROL */
2341}
2342
2343STDMETHODIMP Guest::CopyToGuest(IN_BSTR aSource, IN_BSTR aDest,
2344 IN_BSTR aUsername, IN_BSTR aPassword,
2345 ULONG aFlags, IProgress **aProgress)
2346{
2347#ifndef VBOX_WITH_GUEST_CONTROL
2348 ReturnComNotImplemented();
2349#else /* VBOX_WITH_GUEST_CONTROL */
2350 CheckComArgStrNotEmptyOrNull(aSource);
2351 CheckComArgStrNotEmptyOrNull(aDest);
2352 CheckComArgOutPointerValid(aProgress);
2353
2354 /* Do not allow anonymous executions (with system rights). */
2355 if (RT_UNLIKELY((aUsername) == NULL || *(aUsername) == '\0'))
2356 return setError(E_INVALIDARG, tr("No user name specified"));
2357
2358 AutoCaller autoCaller(this);
2359 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2360
2361 /* Validate flags. */
2362 if (aFlags != CopyFileFlag_None)
2363 {
2364 if ( !(aFlags & CopyFileFlag_Recursive)
2365 && !(aFlags & CopyFileFlag_Update)
2366 && !(aFlags & CopyFileFlag_FollowLinks))
2367 {
2368 return setError(E_INVALIDARG, tr("Unknown flags (%#x)"), aFlags);
2369 }
2370 }
2371
2372 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2373
2374 HRESULT rc = S_OK;
2375
2376 ComObjPtr<Progress> progress;
2377 try
2378 {
2379 /* Create the progress object. */
2380 progress.createObject();
2381
2382 rc = progress->init(static_cast<IGuest*>(this),
2383 Bstr(tr("Copying file from host to guest")).raw(),
2384 TRUE /* aCancelable */);
2385 if (FAILED(rc)) throw rc;
2386
2387 /* Initialize our worker task. */
2388 GuestTask *pTask = new GuestTask(GuestTask::TaskType_CopyFileToGuest, this, progress);
2389 AssertPtr(pTask);
2390 std::auto_ptr<GuestTask> task(pTask);
2391
2392 /* Assign data - aSource is the source file on the host,
2393 * aDest reflects the full path on the guest. */
2394 task->strSource = (Utf8Str(aSource));
2395 task->strDest = (Utf8Str(aDest));
2396 task->strUserName = (Utf8Str(aUsername));
2397 task->strPassword = (Utf8Str(aPassword));
2398 task->uFlags = aFlags;
2399
2400 rc = task->startThread();
2401 if (FAILED(rc)) throw rc;
2402
2403 /* Don't destruct on success. */
2404 task.release();
2405 }
2406 catch (HRESULT aRC)
2407 {
2408 rc = aRC;
2409 }
2410
2411 if (SUCCEEDED(rc))
2412 {
2413 /* Return progress to the caller. */
2414 progress.queryInterfaceTo(aProgress);
2415 }
2416 return rc;
2417#endif /* VBOX_WITH_GUEST_CONTROL */
2418}
2419
2420STDMETHODIMP Guest::UpdateGuestAdditions(IN_BSTR aSource, ULONG aFlags, IProgress **aProgress)
2421{
2422#ifndef VBOX_WITH_GUEST_CONTROL
2423 ReturnComNotImplemented();
2424#else /* VBOX_WITH_GUEST_CONTROL */
2425 CheckComArgStrNotEmptyOrNull(aSource);
2426 CheckComArgOutPointerValid(aProgress);
2427
2428 AutoCaller autoCaller(this);
2429 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2430
2431 /* Validate flags. */
2432 if (aFlags)
2433 {
2434 if (!(aFlags & AdditionsUpdateFlag_WaitForUpdateStartOnly))
2435 return setError(E_INVALIDARG, tr("Unknown flags (%#x)"), aFlags);
2436 }
2437
2438 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2439
2440 HRESULT rc = S_OK;
2441
2442 ComObjPtr<Progress> progress;
2443 try
2444 {
2445 /* Create the progress object. */
2446 progress.createObject();
2447
2448 rc = progress->init(static_cast<IGuest*>(this),
2449 Bstr(tr("Updating Guest Additions")).raw(),
2450 TRUE /* aCancelable */);
2451 if (FAILED(rc)) throw rc;
2452
2453 /* Initialize our worker task. */
2454 GuestTask *pTask = new GuestTask(GuestTask::TaskType_UpdateGuestAdditions, this, progress);
2455 AssertPtr(pTask);
2456 std::auto_ptr<GuestTask> task(pTask);
2457
2458 /* Assign data - in that case aSource is the full path
2459 * to the Guest Additions .ISO we want to mount. */
2460 task->strSource = (Utf8Str(aSource));
2461 task->uFlags = aFlags;
2462
2463 rc = task->startThread();
2464 if (FAILED(rc)) throw rc;
2465
2466 /* Don't destruct on success. */
2467 task.release();
2468 }
2469 catch (HRESULT aRC)
2470 {
2471 rc = aRC;
2472 }
2473
2474 if (SUCCEEDED(rc))
2475 {
2476 /* Return progress to the caller. */
2477 progress.queryInterfaceTo(aProgress);
2478 }
2479 return rc;
2480#endif /* VBOX_WITH_GUEST_CONTROL */
2481}
2482
Note: See TracBrowser for help on using the repository browser.

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette