VirtualBox

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

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

Main/GuestCtrl: Fixed file copy/existence return codes.

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