VirtualBox

source: vbox/trunk/src/VBox/Frontends/VBoxManage/VBoxManageGuestCtrl.cpp@ 29607

Last change on this file since 29607 was 29585, checked in by vboxsync, 15 years ago

VBoxManageGuestCtrl: password is optional

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 16.8 KB
Line 
1/* $Id: VBoxManageGuestCtrl.cpp 29585 2010-05-17 20:20:36Z vboxsync $ */
2/** @file
3 * VBoxManage - The 'guestcontrol' command.
4 */
5
6/*
7 * Copyright (C) 2010 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
19/*******************************************************************************
20* Header Files *
21*******************************************************************************/
22#include "VBoxManage.h"
23
24#include <VBox/com/com.h>
25#include <VBox/com/string.h>
26#include <VBox/com/array.h>
27#include <VBox/com/ErrorInfo.h>
28#include <VBox/com/errorprint.h>
29
30#include <VBox/com/VirtualBox.h>
31#include <VBox/com/EventQueue.h>
32
33#include <VBox/HostServices/GuestControlSvc.h> /* for PROC_STS_XXX */
34
35#include <VBox/log.h>
36#include <iprt/asm.h>
37#include <iprt/getopt.h>
38#include <iprt/stream.h>
39#include <iprt/string.h>
40#include <iprt/time.h>
41#include <iprt/thread.h>
42
43#ifdef USE_XPCOM_QUEUE
44# include <sys/select.h>
45# include <errno.h>
46#endif
47
48#include <signal.h>
49
50#ifdef RT_OS_DARWIN
51# include <CoreFoundation/CFRunLoop.h>
52#endif
53
54using namespace com;
55
56/**
57 * IVirtualBoxCallback implementation for handling the GuestControlCallback in
58 * relation to the "guestcontrol * wait" command.
59 */
60/** @todo */
61
62/** Set by the signal handler. */
63static volatile bool g_fExecCanceled = false;
64
65void usageGuestControl(void)
66{
67 RTPrintf("VBoxManage guestcontrol execute <vmname>|<uuid>\n"
68 " <path to program> --username <name>\n"
69 " [--password <password>]\n"
70 " [--arguments \"<arguments>\"]\n"
71 " [--environment \"<NAME>=<VALUE> [<NAME>=<VALUE>]\"]\n"
72 " [--flags <flags>] [--timeout <msec>]\n"
73 " [--verbose] [--wait-for exit,stdout,stderr||]\n"
74 "\n");
75}
76
77/**
78 * Signal handler that sets g_fCanceled.
79 *
80 * This can be executed on any thread in the process, on Windows it may even be
81 * a thread dedicated to delivering this signal. Do not doing anything
82 * unnecessary here.
83 */
84static void execProcessSignalHandler(int iSignal)
85{
86 NOREF(iSignal);
87 ASMAtomicWriteBool(&g_fExecCanceled, true);
88}
89
90static const char *getStatus(ULONG uStatus)
91{
92 switch (uStatus)
93 {
94 case guestControl::PROC_STS_STARTED:
95 return "started";
96 case guestControl::PROC_STS_TEN:
97 return "successfully terminated";
98 case guestControl::PROC_STS_TES:
99 return "terminated by signal";
100 case guestControl::PROC_STS_TEA:
101 return "abnormally aborted";
102 case guestControl::PROC_STS_TOK:
103 return "timed out";
104 case guestControl::PROC_STS_TOA:
105 return "timed out, hanging";
106 case guestControl::PROC_STS_DWN:
107 return "killed";
108 case guestControl::PROC_STS_ERROR:
109 return "error";
110 default:
111 return "unknown";
112 }
113}
114
115static int handleExecProgram(HandlerArg *a)
116{
117 /*
118 * Check the syntax. We can deduce the correct syntax from the number of
119 * arguments.
120 */
121 if (a->argc < 2) /* At least the command we want to execute in the guest should be present :-). */
122 return errorSyntax(USAGE_GUESTCONTROL, "Incorrect parameters");
123
124 Utf8Str Utf8Cmd(a->argv[1]);
125 uint32_t uFlags = 0;
126 com::SafeArray <BSTR> args;
127 com::SafeArray <BSTR> env;
128 Utf8Str Utf8UserName;
129 Utf8Str Utf8Password;
130 uint32_t u32TimeoutMS = 0;
131 bool fWaitForExit = false;
132 bool fWaitForStdOut = false;
133 bool fWaitForStdErr = false;
134 bool fVerbose = false;
135 bool fTimeout = false;
136
137 /* Always use the actual command line as argv[0]. */
138 args.push_back(Bstr(Utf8Cmd));
139
140 /* Iterate through all possible commands (if available). */
141 bool usageOK = true;
142 for (int i = 2; usageOK && i < a->argc; i++)
143 {
144 if ( !strcmp(a->argv[i], "--arguments")
145 || !strcmp(a->argv[i], "--args")
146 || !strcmp(a->argv[i], "--arg"))
147 {
148 if (i + 1 >= a->argc)
149 usageOK = false;
150 else
151 {
152 char **papszArg;
153 int cArgs;
154
155 int vrc = RTGetOptArgvFromString(&papszArg, &cArgs, a->argv[i + 1], NULL);
156 if (RT_SUCCESS(vrc))
157 {
158 for (int j = 0; j < cArgs; j++)
159 args.push_back(Bstr(papszArg[j]));
160
161 RTGetOptArgvFree(papszArg);
162 }
163 ++i;
164 }
165 }
166 else if ( !strcmp(a->argv[i], "--environment")
167 || !strcmp(a->argv[i], "--env"))
168 {
169 if (i + 1 >= a->argc)
170 usageOK = false;
171 else
172 {
173 char **papszArg;
174 int cArgs;
175
176 int vrc = RTGetOptArgvFromString(&papszArg, &cArgs, a->argv[i + 1], NULL);
177 if (RT_SUCCESS(vrc))
178 {
179 for (int j = 0; j < cArgs; j++)
180 env.push_back(Bstr(papszArg[j]));
181
182 RTGetOptArgvFree(papszArg);
183 }
184 ++i;
185 }
186 }
187 else if (!strcmp(a->argv[i], "--flags"))
188 {
189 if ( i + 1 >= a->argc
190 || RTStrToUInt32Full(a->argv[i + 1], 10, &uFlags) != VINF_SUCCESS)
191 usageOK = false;
192 else
193 ++i;
194 }
195 else if ( !strcmp(a->argv[i], "--username")
196 || !strcmp(a->argv[i], "--user"))
197 {
198 if (i + 1 >= a->argc)
199 usageOK = false;
200 else
201 {
202 Utf8UserName = a->argv[i + 1];
203 ++i;
204 }
205 }
206 else if ( !strcmp(a->argv[i], "--password")
207 || !strcmp(a->argv[i], "--pwd"))
208 {
209 if (i + 1 >= a->argc)
210 usageOK = false;
211 else
212 {
213 Utf8Password = a->argv[i + 1];
214 ++i;
215 }
216 }
217 else if (!strcmp(a->argv[i], "--timeout"))
218 {
219 if ( i + 1 >= a->argc
220 || RTStrToUInt32Full(a->argv[i + 1], 10, &u32TimeoutMS) != VINF_SUCCESS
221 || u32TimeoutMS == 0)
222 {
223 usageOK = false;
224 }
225 else
226 {
227 fTimeout = true;
228 ++i;
229 }
230 }
231 else if (!strcmp(a->argv[i], "--wait-for"))
232 {
233 if (i + 1 >= a->argc)
234 usageOK = false;
235 else
236 {
237 if (!strcmp(a->argv[i + 1], "exit"))
238 fWaitForExit = true;
239 else if (!strcmp(a->argv[i + 1], "stdout"))
240 {
241 fWaitForExit = true;
242 fWaitForStdOut = true;
243 }
244 else if (!strcmp(a->argv[i + 1], "stderr"))
245 {
246 fWaitForExit = true;
247 fWaitForStdErr = true;
248 }
249 else
250 usageOK = false;
251 ++i;
252 }
253 }
254 else if (!strcmp(a->argv[i], "--verbose"))
255 {
256 fVerbose = true;
257 }
258 /** @todo Add fancy piping stuff here. */
259 else
260 {
261 return errorSyntax(USAGE_GUESTCONTROL,
262 "Invalid parameter '%s'", Utf8Str(a->argv[i]).raw());
263 }
264 }
265
266 if (!usageOK)
267 return errorSyntax(USAGE_GUESTCONTROL, "Incorrect parameters");
268
269 if (Utf8UserName.isEmpty())
270 return errorSyntax(USAGE_GUESTCONTROL,
271 "No user name specified!");
272
273 /* lookup VM. */
274 ComPtr<IMachine> machine;
275 /* assume it's an UUID */
276 HRESULT rc = a->virtualBox->GetMachine(Bstr(a->argv[0]), machine.asOutParam());
277 if (FAILED(rc) || !machine)
278 {
279 /* must be a name */
280 CHECK_ERROR(a->virtualBox, FindMachine(Bstr(a->argv[0]), machine.asOutParam()));
281 }
282
283 if (machine)
284 {
285 do
286 {
287 Bstr uuid;
288 machine->COMGETTER(Id)(uuid.asOutParam());
289
290 /* open an existing session for VM - so the VM has to be running */
291 CHECK_ERROR_BREAK(a->virtualBox, OpenExistingSession(a->session, uuid));
292
293 /* get the mutable session machine */
294 a->session->COMGETTER(Machine)(machine.asOutParam());
295
296 /* get the associated console */
297 ComPtr<IConsole> console;
298 CHECK_ERROR_BREAK(a->session, COMGETTER(Console)(console.asOutParam()));
299
300 ComPtr<IGuest> guest;
301 CHECK_ERROR_BREAK(console, COMGETTER(Guest)(guest.asOutParam()));
302
303 ComPtr<IProgress> progress;
304 ULONG uPID = 0;
305
306 if (fVerbose)
307 {
308 if (u32TimeoutMS == 0)
309 RTPrintf("Waiting for guest to start process ...\n");
310 else
311 RTPrintf("Waiting for guest to start process (within %ums)\n", u32TimeoutMS);
312 }
313
314 /* Get current time stamp to later calculate rest of timeout left. */
315 uint64_t u64StartMS = RTTimeMilliTS();
316
317 /* Execute the process. */
318 rc = guest->ExecuteProcess(Bstr(Utf8Cmd), uFlags,
319 ComSafeArrayAsInParam(args), ComSafeArrayAsInParam(env),
320 Bstr(Utf8UserName), Bstr(Utf8Password), u32TimeoutMS,
321 &uPID, progress.asOutParam());
322 if (FAILED(rc))
323 {
324 ErrorInfo info(guest);
325 if (info.isFullAvailable())
326 RTPrintf("ERROR: %ls (%Rhrc).\n", info.getText().raw(), info.getResultCode());
327 break;
328 }
329 if (fVerbose)
330 RTPrintf("Process '%s' (PID: %u) started\n", Utf8Cmd.raw(), uPID);
331 if (fWaitForExit)
332 {
333 if (fTimeout)
334 {
335 /* Calculate timeout value left after process has been started. */
336 uint64_t u64Diff = RTTimeMilliTS() - u64StartMS;
337 /** @todo Check for uint64_t vs. uint32_t here! */
338 if (u32TimeoutMS > u64Diff) /* Is timeout still bigger than current difference? */
339 {
340 u32TimeoutMS = u32TimeoutMS - u64Diff;
341 if (fVerbose)
342 RTPrintf("Waiting for process to exit (%ums left) ...\n", u32TimeoutMS);
343 }
344 else
345 {
346 if (fVerbose)
347 RTPrintf("No time left to wait for process!\n");
348 }
349 }
350 else if (fVerbose)
351 RTPrintf("Waiting for process to exit ...\n");
352
353 /* setup signal handling if cancelable */
354 ASSERT(progress);
355 bool fCanceledAlready = false;
356 BOOL fCancelable;
357 HRESULT hrc = progress->COMGETTER(Cancelable)(&fCancelable);
358 if (FAILED(hrc))
359 fCancelable = FALSE;
360 if (fCancelable)
361 {
362 signal(SIGINT, execProcessSignalHandler);
363 #ifdef SIGBREAK
364 signal(SIGBREAK, execProcessSignalHandler);
365 #endif
366 }
367
368 /* Wait for process to exit ... */
369 BOOL fCompleted = false;
370 while (SUCCEEDED(progress->COMGETTER(Completed(&fCompleted))))
371 {
372 SafeArray<BYTE> aOutputData;
373 ULONG cbOutputData = 0;
374
375 /*
376 * Some data left to output?
377 */
378
379 if ( fWaitForStdOut
380 || fWaitForStdErr)
381 {
382 CHECK_ERROR_BREAK(guest, GetProcessOutput(uPID, 0 /* aFlags */,
383 u32TimeoutMS, _64K, ComSafeArrayAsOutParam(aOutputData)));
384 cbOutputData = aOutputData.size();
385 if (cbOutputData > 0)
386 {
387 /* aOutputData has a platform dependent line ending, standardize on
388 * Unix style, as RTStrmWrite does the LF -> CR/LF replacement on
389 * Windows. Otherwise we end up with CR/CR/LF on Windows. */
390 ULONG cbOutputDataPrint = cbOutputData;
391 for (BYTE *s = aOutputData.raw(), *d = s;
392 s - aOutputData.raw() < (ssize_t)cbOutputData;
393 s++, d++)
394 {
395 if (*s == '\r')
396 {
397 /* skip over CR, adjust destination */
398 d--;
399 cbOutputDataPrint--;
400 }
401 else if (s != d)
402 *d = *s;
403 }
404 RTStrmWrite(g_pStdOut, aOutputData.raw(), cbOutputDataPrint);
405 }
406 }
407
408 if (cbOutputData <= 0)
409 {
410 if (fCompleted)
411 break;
412
413 if ( fTimeout
414 && RTTimeMilliTS() - u64StartMS > u32TimeoutMS + 5000)
415 {
416 progress->Cancel();
417 break;
418 }
419 }
420
421 /* process async cancelation */
422 if (g_fExecCanceled && !fCanceledAlready)
423 {
424 hrc = progress->Cancel();
425 if (SUCCEEDED(hrc))
426 fCanceledAlready = true;
427 else
428 g_fExecCanceled = false;
429 }
430
431 progress->WaitForCompletion(100);
432 }
433
434 /* undo signal handling */
435 if (fCancelable)
436 {
437 signal(SIGINT, SIG_DFL);
438 #ifdef SIGBREAK
439 signal(SIGBREAK, SIG_DFL);
440 #endif
441 }
442
443 BOOL fCanceled;
444 CHECK_ERROR_RET(progress, COMGETTER(Canceled)(&fCanceled), rc);
445 if (fCanceled)
446 {
447 RTPrintf("Process execution canceled!\n");
448 }
449 else
450 {
451 if (fCompleted)
452 {
453 LONG iRc = false;
454 CHECK_ERROR_RET(progress, COMGETTER(ResultCode)(&iRc), rc);
455 if (FAILED(iRc))
456 {
457 ComPtr<IVirtualBoxErrorInfo> execError;
458 rc = progress->COMGETTER(ErrorInfo)(execError.asOutParam());
459 com::ErrorInfo info (execError);
460 RTPrintf("\n\nProcess error details:\n");
461 GluePrintErrorInfo(info);
462 RTPrintf("\n");
463 }
464 if (fVerbose)
465 {
466 ULONG uRetStatus, uRetExitCode, uRetFlags;
467 CHECK_ERROR_BREAK(guest, GetProcessStatus(uPID, &uRetExitCode, &uRetFlags, &uRetStatus));
468 RTPrintf("Exit code=%u (Status=%u [%s], Flags=%u)\n", uRetExitCode, uRetStatus, getStatus(uRetStatus), uRetFlags);
469 }
470 }
471 }
472 }
473 a->session->Close();
474 } while (0);
475 }
476 return SUCCEEDED(rc) ? 0 : 1;
477}
478
479/**
480 * Access the guest control store.
481 *
482 * @returns 0 on success, 1 on failure
483 * @note see the command line API description for parameters
484 */
485int handleGuestControl(HandlerArg *a)
486{
487 HandlerArg arg = *a;
488 arg.argc = a->argc - 1;
489 arg.argv = a->argv + 1;
490
491 if (a->argc == 0)
492 return errorSyntax(USAGE_GUESTCONTROL, "Incorrect parameters");
493
494 /* switch (cmd) */
495 if ( strcmp(a->argv[0], "exec") == 0
496 || strcmp(a->argv[0], "execute") == 0)
497 return handleExecProgram(&arg);
498
499 /* default: */
500 return errorSyntax(USAGE_GUESTCONTROL, "Incorrect parameters");
501}
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