VirtualBox

source: vbox/trunk/src/VBox/Additions/common/VBoxService/VBoxServiceToolBox.cpp@ 86877

Last change on this file since 86877 was 84005, checked in by vboxsync, 5 years ago

VBoxServiceToolBox.cpp: Just go with %Rrc when reporting cat input file errors.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 63.9 KB
Line 
1/* $Id: VBoxServiceToolBox.cpp 84005 2020-04-27 12:11:07Z vboxsync $ */
2/** @file
3 * VBoxServiceToolbox - Internal (BusyBox-like) toolbox.
4 */
5
6/*
7 * Copyright (C) 2012-2020 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 <stdio.h>
23
24#include <iprt/assert.h>
25#include <iprt/buildconfig.h>
26#include <iprt/dir.h>
27#include <iprt/file.h>
28#include <iprt/getopt.h>
29#include <iprt/list.h>
30#include <iprt/mem.h>
31#include <iprt/message.h>
32#include <iprt/path.h>
33#include <iprt/string.h>
34#include <iprt/stream.h>
35#include <iprt/symlink.h>
36
37#ifndef RT_OS_WINDOWS
38# include <sys/stat.h> /* need umask */
39#endif
40
41#include <VBox/VBoxGuestLib.h>
42#include <VBox/version.h>
43
44#include <VBox/GuestHost/GuestControl.h>
45
46#include "VBoxServiceInternal.h"
47#include "VBoxServiceToolBox.h"
48#include "VBoxServiceUtils.h"
49
50using namespace guestControl;
51
52
53/*********************************************************************************************************************************
54* Defined Constants And Macros *
55*********************************************************************************************************************************/
56
57/** Generic option indices for commands. */
58enum
59{
60 VBOXSERVICETOOLBOXOPT_MACHINE_READABLE = 1000,
61 VBOXSERVICETOOLBOXOPT_VERBOSE
62};
63
64/** Options indices for "vbox_cat". */
65typedef enum VBOXSERVICETOOLBOXCATOPT
66{
67 VBOXSERVICETOOLBOXCATOPT_NO_CONTENT_INDEXED = 1000
68} VBOXSERVICETOOLBOXCATOPT;
69
70/** Flags for "vbox_ls". */
71typedef enum VBOXSERVICETOOLBOXLSFLAG
72{
73 VBOXSERVICETOOLBOXLSFLAG_NONE,
74 VBOXSERVICETOOLBOXLSFLAG_RECURSIVE,
75 VBOXSERVICETOOLBOXLSFLAG_SYMLINKS
76} VBOXSERVICETOOLBOXLSFLAG;
77
78/** Flags for fs object output. */
79typedef enum VBOXSERVICETOOLBOXOUTPUTFLAG
80{
81 VBOXSERVICETOOLBOXOUTPUTFLAG_NONE,
82 VBOXSERVICETOOLBOXOUTPUTFLAG_LONG,
83 VBOXSERVICETOOLBOXOUTPUTFLAG_PARSEABLE
84} VBOXSERVICETOOLBOXOUTPUTFLAG;
85
86/** The size of the directory entry buffer we're using. */
87#define VBOXSERVICETOOLBOX_DIRENTRY_BUF_SIZE (sizeof(RTDIRENTRYEX) + RTPATH_MAX)
88
89
90/*********************************************************************************************************************************
91* Structures and Typedefs *
92*********************************************************************************************************************************/
93/** Pointer to a tool handler function. */
94typedef RTEXITCODE (*PFNHANDLER)(int , char **);
95
96/** Definition for a specific toolbox tool. */
97typedef struct VBOXSERVICETOOLBOXTOOL
98{
99 /** Friendly name of the tool. */
100 const char *pszName;
101 /** Main handler to be invoked to use the tool. */
102 RTEXITCODE (*pfnHandler)(int argc, char **argv);
103 /** Conversion routine to convert the tool's exit code back to an IPRT rc. Optional.
104 *
105 * @todo r=bird: You better revert this, i.e. having pfnHandler return a VBox
106 * status code and have a routine for converting it to RTEXITCODE.
107 * Unless, what you really want to do here is to get a cached status, in
108 * which case you better call it what it is.
109 */
110 int (*pfnExitCodeConvertToRc)(RTEXITCODE rcExit);
111} VBOXSERVICETOOLBOXTOOL;
112/** Pointer to a const tool definition. */
113typedef VBOXSERVICETOOLBOXTOOL const *PCVBOXSERVICETOOLBOXTOOL;
114
115/**
116 * An file/directory entry. Used to cache
117 * file names/paths for later processing.
118 */
119typedef struct VBOXSERVICETOOLBOXPATHENTRY
120{
121 /** Our node. */
122 RTLISTNODE Node;
123 /** Name of the entry. */
124 char *pszName;
125} VBOXSERVICETOOLBOXPATHENTRY, *PVBOXSERVICETOOLBOXPATHENTRY;
126
127/** ID cache entry. */
128typedef struct VGSVCTOOLBOXUIDENTRY
129{
130 /** The identifier name. */
131 uint32_t id;
132 /** Set if UID, clear if GID. */
133 bool fIsUid;
134 /** The name. */
135 char szName[128 - 4 - 1];
136} VGSVCTOOLBOXUIDENTRY;
137typedef VGSVCTOOLBOXUIDENTRY *PVGSVCTOOLBOXUIDENTRY;
138
139
140/** ID cache. */
141typedef struct VGSVCTOOLBOXIDCACHE
142{
143 /** Number of valid cache entries. */
144 uint32_t cEntries;
145 /** The next entry to replace. */
146 uint32_t iNextReplace;
147 /** The cache entries. */
148 VGSVCTOOLBOXUIDENTRY aEntries[16];
149} VGSVCTOOLBOXIDCACHE;
150typedef VGSVCTOOLBOXIDCACHE *PVGSVCTOOLBOXIDCACHE;
151
152
153/*********************************************************************************************************************************
154* Internal Functions *
155*********************************************************************************************************************************/
156static RTEXITCODE vgsvcToolboxCat(int argc, char **argv);
157static RTEXITCODE vgsvcToolboxLs(int argc, char **argv);
158static RTEXITCODE vgsvcToolboxRm(int argc, char **argv);
159static RTEXITCODE vgsvcToolboxMkTemp(int argc, char **argv);
160static RTEXITCODE vgsvcToolboxMkDir(int argc, char **argv);
161static RTEXITCODE vgsvcToolboxStat(int argc, char **argv);
162
163
164/*********************************************************************************************************************************
165* Global Variables *
166*********************************************************************************************************************************/
167/** Tool definitions. */
168static VBOXSERVICETOOLBOXTOOL const g_aTools[] =
169{
170 { VBOXSERVICE_TOOL_CAT, vgsvcToolboxCat , NULL },
171 { VBOXSERVICE_TOOL_LS, vgsvcToolboxLs , NULL },
172 { VBOXSERVICE_TOOL_RM, vgsvcToolboxRm , NULL },
173 { VBOXSERVICE_TOOL_MKTEMP, vgsvcToolboxMkTemp, NULL },
174 { VBOXSERVICE_TOOL_MKDIR, vgsvcToolboxMkDir , NULL },
175 { VBOXSERVICE_TOOL_STAT, vgsvcToolboxStat , NULL }
176};
177
178
179
180
181/**
182 * Displays a common header for all help text to stdout.
183 */
184static void vgsvcToolboxShowUsageHeader(void)
185{
186 RTPrintf(VBOX_PRODUCT " Guest Toolbox Version "
187 VBOX_VERSION_STRING "\n"
188 "(C) " VBOX_C_YEAR " " VBOX_VENDOR "\n"
189 "All rights reserved.\n"
190 "\n");
191 RTPrintf("Usage:\n\n");
192}
193
194
195/**
196 * Displays a help text to stdout.
197 */
198static void vgsvcToolboxShowUsage(void)
199{
200 vgsvcToolboxShowUsageHeader();
201 RTPrintf(" VBoxService [--use-toolbox] vbox_<command> [<general options>] <parameters>\n\n"
202 "General options:\n\n"
203 " --machinereadable produce all output in machine-readable form\n"
204 " -V print version number and exit\n"
205 "\n"
206 "Commands:\n\n"
207 " vbox_cat [<general options>] <file>...\n"
208 " vbox_ls [<general options>] [--dereference|-L] [-l] [-R]\n"
209 " [--verbose|-v] [<file>...]\n"
210 " vbox_rm [<general options>] [-r|-R] <file>...\n"
211 " vbox_mktemp [<general options>] [--directory|-d] [--mode|-m <mode>]\n"
212 " [--secure|-s] [--tmpdir|-t <path>] <template>\n"
213 " vbox_mkdir [<general options>] [--mode|-m <mode>] [--parents|-p]\n"
214 " [--verbose|-v] <directory>...\n"
215 " vbox_stat [<general options>] [--file-system|-f]\n"
216 " [--dereference|-L] [--terse|-t] [--verbose|-v] <file>...\n"
217 "\n");
218}
219
220
221/**
222 * Displays the program's version number.
223 */
224static void vgsvcToolboxShowVersion(void)
225{
226 RTPrintf("%sr%d\n", VBOX_VERSION_STRING, RTBldCfgRevision());
227}
228
229
230/**
231 * Initializes the parseable stream(s).
232 *
233 * @return IPRT status code.
234 */
235static int vgsvcToolboxStrmInit(void)
236{
237 /* Set stdout's mode to binary. This is required for outputting all the machine-readable
238 * data correctly. */
239 int rc = RTStrmSetMode(g_pStdOut, 1 /* Binary mode */, -1 /* Current code set, not changed */);
240 if (RT_FAILURE(rc))
241 RTMsgError("Unable to set stdout to binary mode, rc=%Rrc\n", rc);
242
243 return rc;
244}
245
246
247/**
248 * Prints a parseable stream header which contains the actual tool
249 * which was called/used along with its stream version.
250 *
251 * @param pszToolName Name of the tool being used, e.g. "vbt_ls".
252 * @param uVersion Stream version name. Handy for distinguishing
253 * different stream versions later.
254 */
255static void vgsvcToolboxPrintStrmHeader(const char *pszToolName, uint32_t uVersion)
256{
257 AssertPtrReturnVoid(pszToolName);
258 RTPrintf("hdr_id=%s%chdr_ver=%u%c", pszToolName, 0, uVersion, 0);
259}
260
261
262/**
263 * Prints a standardized termination sequence indicating that the
264 * parseable stream just ended.
265 *
266 */
267static void vgsvcToolboxPrintStrmTermination()
268{
269 RTPrintf("%c%c%c%c", 0, 0, 0, 0);
270}
271
272
273/**
274 * Parse a file mode string from the command line (currently octal only)
275 * and print an error message and return an error if necessary.
276 */
277static int vgsvcToolboxParseMode(const char *pcszMode, RTFMODE *pfMode)
278{
279 int rc = RTStrToUInt32Ex(pcszMode, NULL, 8 /* Base */, pfMode);
280 if (RT_FAILURE(rc)) /* Only octet based values supported right now! */
281 RTMsgError("Mode flag strings not implemented yet! Use octal numbers instead. (%s)\n", pcszMode);
282 return rc;
283}
284
285
286/**
287 * Destroys a path buffer list.
288 *
289 * @return IPRT status code.
290 * @param pList Pointer to list to destroy.
291 */
292static void vgsvcToolboxPathBufDestroy(PRTLISTNODE pList)
293{
294 if (!pList)
295 return;
296
297 PVBOXSERVICETOOLBOXPATHENTRY pEntry, pEntryNext;
298 RTListForEachSafe(pList, pEntry, pEntryNext, VBOXSERVICETOOLBOXPATHENTRY, Node)
299 {
300 RTListNodeRemove(&pEntry->Node);
301
302 RTStrFree(pEntry->pszName);
303 RTMemFree(pEntry);
304 }
305}
306
307
308/**
309 * Adds a path entry (file/directory/whatever) to a given path buffer list.
310 *
311 * @return IPRT status code.
312 * @param pList Pointer to list to add entry to.
313 * @param pszName Name of entry to add.
314 */
315static int vgsvcToolboxPathBufAddPathEntry(PRTLISTNODE pList, const char *pszName)
316{
317 AssertPtrReturn(pList, VERR_INVALID_PARAMETER);
318
319 int rc = VINF_SUCCESS;
320 PVBOXSERVICETOOLBOXPATHENTRY pNode = (PVBOXSERVICETOOLBOXPATHENTRY)RTMemAlloc(sizeof(VBOXSERVICETOOLBOXPATHENTRY));
321 if (pNode)
322 {
323 pNode->pszName = RTStrDup(pszName);
324 AssertPtr(pNode->pszName);
325
326 RTListAppend(pList, &pNode->Node);
327 }
328 else
329 rc = VERR_NO_MEMORY;
330 return rc;
331}
332
333
334/**
335 * Performs the actual output operation of "vbox_cat".
336 *
337 * @return IPRT status code.
338 * @param hInput Handle of input file (if any) to use;
339 * else stdin will be used.
340 * @param hOutput Handle of output file (if any) to use;
341 * else stdout will be used.
342 */
343static int vgsvcToolboxCatOutput(RTFILE hInput, RTFILE hOutput)
344{
345 int rc = VINF_SUCCESS;
346 if (hInput == NIL_RTFILE)
347 {
348 rc = RTFileFromNative(&hInput, RTFILE_NATIVE_STDIN);
349 if (RT_FAILURE(rc))
350 RTMsgError("Could not translate input file to native handle, rc=%Rrc\n", rc);
351 }
352
353 if (hOutput == NIL_RTFILE)
354 {
355 rc = RTFileFromNative(&hOutput, RTFILE_NATIVE_STDOUT);
356 if (RT_FAILURE(rc))
357 RTMsgError("Could not translate output file to native handle, rc=%Rrc\n", rc);
358 }
359
360 if (RT_SUCCESS(rc))
361 {
362 uint8_t abBuf[_64K];
363 size_t cbRead;
364 for (;;)
365 {
366 rc = RTFileRead(hInput, abBuf, sizeof(abBuf), &cbRead);
367 if (RT_SUCCESS(rc) && cbRead > 0)
368 {
369 rc = RTFileWrite(hOutput, abBuf, cbRead, NULL /* Try to write all at once! */);
370 if (RT_FAILURE(rc))
371 {
372 RTMsgError("Error while writing output, rc=%Rrc\n", rc);
373 break;
374 }
375 }
376 else
377 {
378 if (rc == VERR_BROKEN_PIPE)
379 rc = VINF_SUCCESS;
380 else if (RT_FAILURE(rc))
381 RTMsgError("Error while reading input, rc=%Rrc\n", rc);
382 break;
383 }
384 }
385 }
386 return rc;
387}
388
389
390/** @todo Document options! */
391static char g_paszCatHelp[] =
392 " VBoxService [--use-toolbox] vbox_cat [<general options>] <file>...\n\n"
393 "Concatenate files, or standard input, to standard output.\n"
394 "\n";
395
396
397/**
398 * Main function for tool "vbox_cat".
399 *
400 * @return RTEXITCODE.
401 * @param argc Number of arguments.
402 * @param argv Pointer to argument array.
403 */
404static RTEXITCODE vgsvcToolboxCat(int argc, char **argv)
405{
406 static const RTGETOPTDEF s_aOptions[] =
407 {
408 /* Sorted by short ops. */
409 { "--show-all", 'a', RTGETOPT_REQ_NOTHING },
410 { "--number-nonblank", 'b', RTGETOPT_REQ_NOTHING},
411 { NULL, 'e', RTGETOPT_REQ_NOTHING},
412 { NULL, 'E', RTGETOPT_REQ_NOTHING},
413 { "--flags", 'f', RTGETOPT_REQ_STRING},
414 { "--no-content-indexed", VBOXSERVICETOOLBOXCATOPT_NO_CONTENT_INDEXED, RTGETOPT_REQ_NOTHING},
415 { "--number", 'n', RTGETOPT_REQ_NOTHING},
416 { "--output", 'o', RTGETOPT_REQ_STRING},
417 { "--squeeze-blank", 's', RTGETOPT_REQ_NOTHING},
418 { NULL, 't', RTGETOPT_REQ_NOTHING},
419 { "--show-tabs", 'T', RTGETOPT_REQ_NOTHING},
420 { NULL, 'u', RTGETOPT_REQ_NOTHING},
421 { "--show-noneprinting", 'v', RTGETOPT_REQ_NOTHING}
422 };
423
424 int ch;
425 RTGETOPTUNION ValueUnion;
426 RTGETOPTSTATE GetState;
427
428 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1 /*iFirst*/, 0 /*fFlags*/);
429
430 int rc = VINF_SUCCESS;
431
432 const char *pszOutput = NULL;
433 RTFILE hOutput = NIL_RTFILE;
434 uint32_t fFlags = RTFILE_O_CREATE_REPLACE /* Output file flags. */
435 | RTFILE_O_WRITE
436 | RTFILE_O_DENY_WRITE;
437
438 /* Init directory list. */
439 RTLISTANCHOR inputList;
440 RTListInit(&inputList);
441
442 while ( (ch = RTGetOpt(&GetState, &ValueUnion))
443 && RT_SUCCESS(rc))
444 {
445 /* For options that require an argument, ValueUnion has received the value. */
446 switch (ch)
447 {
448 case 'a':
449 case 'b':
450 case 'e':
451 case 'E':
452 case 'n':
453 case 's':
454 case 't':
455 case 'T':
456 case 'v':
457 RTMsgError("Sorry, option '%s' is not implemented yet!\n",
458 ValueUnion.pDef->pszLong);
459 rc = VERR_INVALID_PARAMETER;
460 break;
461
462 case 'h':
463 vgsvcToolboxShowUsageHeader();
464 RTPrintf("%s", g_paszCatHelp);
465 return RTEXITCODE_SUCCESS;
466
467 case 'o':
468 pszOutput = ValueUnion.psz;
469 break;
470
471 case 'u':
472 /* Ignored. */
473 break;
474
475 case 'V':
476 vgsvcToolboxShowVersion();
477 return RTEXITCODE_SUCCESS;
478
479 case VBOXSERVICETOOLBOXCATOPT_NO_CONTENT_INDEXED:
480 fFlags |= RTFILE_O_NOT_CONTENT_INDEXED;
481 break;
482
483 case VINF_GETOPT_NOT_OPTION:
484 /* Add file(s) to buffer. This enables processing multiple paths
485 * at once.
486 *
487 * Since the non-options (RTGETOPTINIT_FLAGS_OPTS_FIRST) come last when
488 * processing this loop it's safe to immediately exit on syntax errors
489 * or showing the help text (see above). */
490 rc = vgsvcToolboxPathBufAddPathEntry(&inputList, ValueUnion.psz);
491 break;
492
493 default:
494 return RTGetOptPrintError(ch, &ValueUnion);
495 }
496 }
497
498 if (RT_SUCCESS(rc))
499 {
500 if (pszOutput)
501 {
502 rc = RTFileOpen(&hOutput, pszOutput, fFlags);
503 if (RT_FAILURE(rc))
504 RTMsgError("Could not create output file '%s', rc=%Rrc\n", pszOutput, rc);
505 }
506
507 if (RT_SUCCESS(rc))
508 {
509 /* Process each input file. */
510 RTFILE hInput = NIL_RTFILE;
511 PVBOXSERVICETOOLBOXPATHENTRY pNodeIt;
512 RTListForEach(&inputList, pNodeIt, VBOXSERVICETOOLBOXPATHENTRY, Node)
513 {
514 rc = RTFileOpen(&hInput, pNodeIt->pszName,
515 RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE);
516 if (RT_SUCCESS(rc))
517 {
518 rc = vgsvcToolboxCatOutput(hInput, hOutput);
519 RTFileClose(hInput);
520 }
521 else
522 RTMsgError("Could not open input file '%s': %Rrc\n", pNodeIt->pszName, rc);
523 if (RT_FAILURE(rc))
524 break;
525 }
526
527 /* If no input files were defined, process stdin. */
528 if (RTListNodeIsFirst(&inputList, &inputList))
529 rc = vgsvcToolboxCatOutput(hInput, hOutput);
530 }
531 }
532
533 if (hOutput != NIL_RTFILE)
534 RTFileClose(hOutput);
535 vgsvcToolboxPathBufDestroy(&inputList);
536
537 if (RT_FAILURE(rc))
538 {
539 switch (rc)
540 {
541 case VERR_ACCESS_DENIED:
542 return (RTEXITCODE)VBOXSERVICETOOLBOX_CAT_EXITCODE_ACCESS_DENIED;
543
544 case VERR_FILE_NOT_FOUND:
545 return (RTEXITCODE)VBOXSERVICETOOLBOX_CAT_EXITCODE_FILE_NOT_FOUND;
546
547 case VERR_PATH_NOT_FOUND:
548 return (RTEXITCODE)VBOXSERVICETOOLBOX_CAT_EXITCODE_PATH_NOT_FOUND;
549
550 case VERR_SHARING_VIOLATION:
551 return (RTEXITCODE)VBOXSERVICETOOLBOX_CAT_EXITCODE_SHARING_VIOLATION;
552
553 case VERR_IS_A_DIRECTORY:
554 return (RTEXITCODE)VBOXSERVICETOOLBOX_CAT_EXITCODE_IS_A_DIRECTORY;
555
556 default:
557#ifdef DEBUG_andy
558 AssertMsgFailed(("Exit code for %Rrc not implemented\n", rc));
559#endif
560 break;
561 }
562
563 return RTEXITCODE_FAILURE;
564 }
565
566 return RTEXITCODE_SUCCESS;
567}
568
569
570/**
571 * Resolves the UID to a name as best as we can.
572 *
573 * @returns Read-only name string. Only valid till the next cache call.
574 * @param pIdCache The ID cache.
575 * @param uid The UID to resolve.
576 * @param pszEntry The filename of the UID.
577 * @param pszRelativeTo What @a pszEntry is relative to, NULL if absolute.
578 */
579static const char *vgsvcToolboxIdCacheGetUidName(PVGSVCTOOLBOXIDCACHE pIdCache, RTUID uid,
580 const char *pszEntry, const char *pszRelativeTo)
581{
582 /* Check cached entries. */
583 for (uint32_t i = 0; i < pIdCache->cEntries; i++)
584 if ( pIdCache->aEntries[i].id == uid
585 && pIdCache->aEntries[i].fIsUid)
586 return pIdCache->aEntries[i].szName;
587
588 /* Miss. */
589 RTFSOBJINFO ObjInfo;
590 RT_ZERO(ObjInfo); /* shut up msc */
591 int rc;
592 if (!pszRelativeTo)
593 rc = RTPathQueryInfoEx(pszEntry, &ObjInfo, RTFSOBJATTRADD_UNIX_OWNER, RTPATH_F_ON_LINK);
594 else
595 {
596 char szPath[RTPATH_MAX];
597 rc = RTPathJoin(szPath, sizeof(szPath), pszRelativeTo, pszEntry);
598 if (RT_SUCCESS(rc))
599 rc = RTPathQueryInfoEx(szPath, &ObjInfo, RTFSOBJATTRADD_UNIX_OWNER, RTPATH_F_ON_LINK);
600 }
601
602 if ( RT_SUCCESS(rc)
603 && ObjInfo.Attr.u.UnixOwner.uid == uid)
604 {
605 uint32_t i = pIdCache->cEntries;
606 if (i < RT_ELEMENTS(pIdCache->aEntries))
607 pIdCache->cEntries = i + 1;
608 else
609 i = pIdCache->iNextReplace++ % RT_ELEMENTS(pIdCache->aEntries);
610 pIdCache->aEntries[i].id = uid;
611 pIdCache->aEntries[i].fIsUid = true;
612 RTStrCopy(pIdCache->aEntries[i].szName, sizeof(pIdCache->aEntries[i].szName), ObjInfo.Attr.u.UnixOwner.szName);
613 return pIdCache->aEntries[i].szName;
614 }
615 return "";
616}
617
618
619/**
620 * Resolves the GID to a name as best as we can.
621 *
622 * @returns Read-only name string. Only valid till the next cache call.
623 * @param pIdCache The ID cache.
624 * @param gid The GID to resolve.
625 * @param pszEntry The filename of the GID.
626 * @param pszRelativeTo What @a pszEntry is relative to, NULL if absolute.
627 */
628static const char *vgsvcToolboxIdCacheGetGidName(PVGSVCTOOLBOXIDCACHE pIdCache, RTGID gid,
629 const char *pszEntry, const char *pszRelativeTo)
630{
631 /* Check cached entries. */
632 for (uint32_t i = 0; i < pIdCache->cEntries; i++)
633 if ( pIdCache->aEntries[i].id == gid
634 && !pIdCache->aEntries[i].fIsUid)
635 return pIdCache->aEntries[i].szName;
636
637 /* Miss. */
638 RTFSOBJINFO ObjInfo;
639 RT_ZERO(ObjInfo); /* shut up msc */
640 int rc;
641 if (!pszRelativeTo)
642 rc = RTPathQueryInfoEx(pszEntry, &ObjInfo, RTFSOBJATTRADD_UNIX_GROUP, RTPATH_F_ON_LINK);
643 else
644 {
645 char szPath[RTPATH_MAX];
646 rc = RTPathJoin(szPath, sizeof(szPath), pszRelativeTo, pszEntry);
647 if (RT_SUCCESS(rc))
648 rc = RTPathQueryInfoEx(szPath, &ObjInfo, RTFSOBJATTRADD_UNIX_GROUP, RTPATH_F_ON_LINK);
649 }
650
651 if ( RT_SUCCESS(rc)
652 && ObjInfo.Attr.u.UnixGroup.gid == gid)
653 {
654 uint32_t i = pIdCache->cEntries;
655 if (i < RT_ELEMENTS(pIdCache->aEntries))
656 pIdCache->cEntries = i + 1;
657 else
658 i = pIdCache->iNextReplace++ % RT_ELEMENTS(pIdCache->aEntries);
659 pIdCache->aEntries[i].id = gid;
660 pIdCache->aEntries[i].fIsUid = false;
661 RTStrCopy(pIdCache->aEntries[i].szName, sizeof(pIdCache->aEntries[i].szName), ObjInfo.Attr.u.UnixGroup.szName);
662 return pIdCache->aEntries[i].szName;
663 }
664 return "";
665}
666
667
668/**
669 * Prints information (based on given flags) of a file system object (file/directory/...)
670 * to stdout.
671 *
672 * @return IPRT status code.
673 * @param pszName Object name.
674 * @param cchName Length of pszName.
675 * @param fOutputFlags Output / handling flags of type
676 * VBOXSERVICETOOLBOXOUTPUTFLAG.
677 * @param pszRelativeTo What pszName is relative to.
678 * @param pIdCache The ID cache.
679 * @param pObjInfo Pointer to object information.
680 */
681static int vgsvcToolboxPrintFsInfo(const char *pszName, size_t cchName, uint32_t fOutputFlags, const char *pszRelativeTo,
682 PVGSVCTOOLBOXIDCACHE pIdCache, PRTFSOBJINFO pObjInfo)
683{
684 AssertPtrReturn(pszName, VERR_INVALID_POINTER);
685 AssertReturn(cchName, VERR_INVALID_PARAMETER);
686 AssertPtrReturn(pObjInfo, VERR_INVALID_POINTER);
687
688 RTFMODE fMode = pObjInfo->Attr.fMode;
689 char chFileType;
690 switch (fMode & RTFS_TYPE_MASK)
691 {
692 case RTFS_TYPE_FIFO: chFileType = 'f'; break;
693 case RTFS_TYPE_DEV_CHAR: chFileType = 'c'; break;
694 case RTFS_TYPE_DIRECTORY: chFileType = 'd'; break;
695 case RTFS_TYPE_DEV_BLOCK: chFileType = 'b'; break;
696 case RTFS_TYPE_FILE: chFileType = '-'; break;
697 case RTFS_TYPE_SYMLINK: chFileType = 'l'; break;
698 case RTFS_TYPE_SOCKET: chFileType = 's'; break;
699 case RTFS_TYPE_WHITEOUT: chFileType = 'w'; break;
700 default: chFileType = '?'; break;
701 }
702 /** @todo sticy bits++ */
703
704/** @todo r=bird: turns out the host doesn't use or need cname_len, so perhaps we could drop it? */
705 if (!(fOutputFlags & VBOXSERVICETOOLBOXOUTPUTFLAG_LONG))
706 {
707 if (fOutputFlags & VBOXSERVICETOOLBOXOUTPUTFLAG_PARSEABLE)
708 {
709 RTPrintf("ftype=%c%cnode_id=%RU64%inode_dev=%RU32%ccname_len=%zu%cname=%s%c",
710 chFileType, 0, (uint64_t)pObjInfo->Attr.u.Unix.INodeId, 0,
711 (uint32_t)pObjInfo->Attr.u.Unix.INodeIdDevice, 0, cchName, 0, pszName, 0);
712 RTPrintf("%c%c", 0, 0);
713 }
714 else
715 RTPrintf("%c %#18llx %3zu %s\n", chFileType, (uint64_t)pObjInfo->Attr.u.Unix.INodeId, cchName, pszName);
716 }
717 else
718 {
719 char szTimeBirth[RTTIME_STR_LEN];
720 char szTimeChange[RTTIME_STR_LEN];
721 char szTimeModification[RTTIME_STR_LEN];
722 char szTimeAccess[RTTIME_STR_LEN];
723
724 if (fOutputFlags & VBOXSERVICETOOLBOXOUTPUTFLAG_PARSEABLE)
725 {
726 RTPrintf("ftype=%c%c", chFileType, 0);
727 if (pObjInfo->Attr.u.Unix.INodeId || pObjInfo->Attr.u.Unix.INodeIdDevice)
728 RTPrintf("node_id=%RU64%cinode_dev=%RU32%c", (uint64_t)pObjInfo->Attr.u.Unix.INodeId, 0,
729 (uint32_t)pObjInfo->Attr.u.Unix.INodeIdDevice, 0);
730 RTPrintf("owner_mask=%c%c%c%c",
731 fMode & RTFS_UNIX_IRUSR ? 'r' : '-',
732 fMode & RTFS_UNIX_IWUSR ? 'w' : '-',
733 fMode & RTFS_UNIX_IXUSR ? 'x' : '-', 0);
734 RTPrintf("group_mask=%c%c%c%c",
735 fMode & RTFS_UNIX_IRGRP ? 'r' : '-',
736 fMode & RTFS_UNIX_IWGRP ? 'w' : '-',
737 fMode & RTFS_UNIX_IXGRP ? 'x' : '-', 0);
738 RTPrintf("other_mask=%c%c%c%c",
739 fMode & RTFS_UNIX_IROTH ? 'r' : '-',
740 fMode & RTFS_UNIX_IWOTH ? 'w' : '-',
741 fMode & RTFS_UNIX_IXOTH ? 'x' : '-', 0);
742 /** @todo sticky bits. */
743 RTPrintf("dos_mask=%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c",
744 fMode & RTFS_DOS_READONLY ? 'R' : '-',
745 fMode & RTFS_DOS_HIDDEN ? 'H' : '-',
746 fMode & RTFS_DOS_SYSTEM ? 'S' : '-',
747 fMode & RTFS_DOS_DIRECTORY ? 'D' : '-',
748 fMode & RTFS_DOS_ARCHIVED ? 'A' : '-',
749 fMode & RTFS_DOS_NT_DEVICE ? 'd' : '-',
750 fMode & RTFS_DOS_NT_NORMAL ? 'N' : '-',
751 fMode & RTFS_DOS_NT_TEMPORARY ? 'T' : '-',
752 fMode & RTFS_DOS_NT_SPARSE_FILE ? 'P' : '-',
753 fMode & RTFS_DOS_NT_REPARSE_POINT ? 'J' : '-',
754 fMode & RTFS_DOS_NT_COMPRESSED ? 'C' : '-',
755 fMode & RTFS_DOS_NT_OFFLINE ? 'O' : '-',
756 fMode & RTFS_DOS_NT_NOT_CONTENT_INDEXED ? 'I' : '-',
757 fMode & RTFS_DOS_NT_ENCRYPTED ? 'E' : '-', 0);
758 RTPrintf("hlinks=%RU32%cst_size=%RI64%calloc=%RI64%c",
759 pObjInfo->Attr.u.Unix.cHardlinks, 0,
760 pObjInfo->cbObject, 0,
761 pObjInfo->cbAllocated, 0);
762 RTPrintf("st_birthtime=%s%cst_ctime=%s%cst_mtime=%s%cst_atime=%s%c",
763 RTTimeSpecToString(&pObjInfo->BirthTime, szTimeBirth, sizeof(szTimeBirth)), 0,
764 RTTimeSpecToString(&pObjInfo->ChangeTime, szTimeChange, sizeof(szTimeChange)), 0,
765 RTTimeSpecToString(&pObjInfo->ModificationTime, szTimeModification, sizeof(szTimeModification)), 0,
766 RTTimeSpecToString(&pObjInfo->AccessTime, szTimeAccess, sizeof(szTimeAccess)), 0);
767 if (pObjInfo->Attr.u.Unix.uid != NIL_RTUID)
768 RTPrintf("uid=%RU32%cusername=%s%c", pObjInfo->Attr.u.Unix.uid, 0,
769 vgsvcToolboxIdCacheGetUidName(pIdCache, pObjInfo->Attr.u.Unix.uid, pszName, pszRelativeTo), 0);
770 if (pObjInfo->Attr.u.Unix.gid != NIL_RTGID)
771 RTPrintf("gid=%RU32%cgroupname=%s%c", pObjInfo->Attr.u.Unix.gid, 0,
772 vgsvcToolboxIdCacheGetGidName(pIdCache, pObjInfo->Attr.u.Unix.gid, pszName, pszRelativeTo), 0);
773 if ( (RTFS_IS_DEV_BLOCK(pObjInfo->Attr.fMode) || RTFS_IS_DEV_CHAR(pObjInfo->Attr.fMode))
774 && pObjInfo->Attr.u.Unix.Device)
775 RTPrintf("st_rdev=%RU32%c", pObjInfo->Attr.u.Unix.Device, 0);
776 if (pObjInfo->Attr.u.Unix.GenerationId)
777 RTPrintf("st_gen=%RU32%c", pObjInfo->Attr.u.Unix.GenerationId, 0);
778 if (pObjInfo->Attr.u.Unix.fFlags)
779 RTPrintf("st_flags=%RU32%c", pObjInfo->Attr.u.Unix.fFlags, 0);
780 RTPrintf("cname_len=%zu%cname=%s%c", cchName, 0, pszName, 0);
781 RTPrintf("%c%c", 0, 0); /* End of data block. */
782 }
783 else
784 {
785 RTPrintf("%c", chFileType);
786 RTPrintf("%c%c%c",
787 fMode & RTFS_UNIX_IRUSR ? 'r' : '-',
788 fMode & RTFS_UNIX_IWUSR ? 'w' : '-',
789 fMode & RTFS_UNIX_IXUSR ? 'x' : '-');
790 RTPrintf("%c%c%c",
791 fMode & RTFS_UNIX_IRGRP ? 'r' : '-',
792 fMode & RTFS_UNIX_IWGRP ? 'w' : '-',
793 fMode & RTFS_UNIX_IXGRP ? 'x' : '-');
794 RTPrintf("%c%c%c",
795 fMode & RTFS_UNIX_IROTH ? 'r' : '-',
796 fMode & RTFS_UNIX_IWOTH ? 'w' : '-',
797 fMode & RTFS_UNIX_IXOTH ? 'x' : '-');
798 RTPrintf(" %c%c%c%c%c%c%c%c%c%c%c%c%c%c",
799 fMode & RTFS_DOS_READONLY ? 'R' : '-',
800 fMode & RTFS_DOS_HIDDEN ? 'H' : '-',
801 fMode & RTFS_DOS_SYSTEM ? 'S' : '-',
802 fMode & RTFS_DOS_DIRECTORY ? 'D' : '-',
803 fMode & RTFS_DOS_ARCHIVED ? 'A' : '-',
804 fMode & RTFS_DOS_NT_DEVICE ? 'd' : '-',
805 fMode & RTFS_DOS_NT_NORMAL ? 'N' : '-',
806 fMode & RTFS_DOS_NT_TEMPORARY ? 'T' : '-',
807 fMode & RTFS_DOS_NT_SPARSE_FILE ? 'P' : '-',
808 fMode & RTFS_DOS_NT_REPARSE_POINT ? 'J' : '-',
809 fMode & RTFS_DOS_NT_COMPRESSED ? 'C' : '-',
810 fMode & RTFS_DOS_NT_OFFLINE ? 'O' : '-',
811 fMode & RTFS_DOS_NT_NOT_CONTENT_INDEXED ? 'I' : '-',
812 fMode & RTFS_DOS_NT_ENCRYPTED ? 'E' : '-');
813 RTPrintf(" %d %4d %4d %10lld %10lld",
814 pObjInfo->Attr.u.Unix.cHardlinks,
815 pObjInfo->Attr.u.Unix.uid,
816 pObjInfo->Attr.u.Unix.gid,
817 pObjInfo->cbObject,
818 pObjInfo->cbAllocated);
819 RTPrintf(" %s %s %s %s",
820 RTTimeSpecToString(&pObjInfo->BirthTime, szTimeBirth, sizeof(szTimeBirth)),
821 RTTimeSpecToString(&pObjInfo->ChangeTime, szTimeChange, sizeof(szTimeChange)),
822 RTTimeSpecToString(&pObjInfo->ModificationTime, szTimeModification, sizeof(szTimeModification)),
823 RTTimeSpecToString(&pObjInfo->AccessTime, szTimeAccess, sizeof(szTimeAccess)) );
824 RTPrintf(" %2zu %s\n", cchName, pszName);
825 }
826 }
827
828 return VINF_SUCCESS;
829}
830
831/**
832 * Helper routine for ls tool for handling sub directories.
833 *
834 * @return IPRT status code.
835 * @param pszDir Pointer to the directory buffer.
836 * @param cchDir The length of pszDir in pszDir.
837 * @param pDirEntry Pointer to the directory entry.
838 * @param fFlags Flags of type VBOXSERVICETOOLBOXLSFLAG.
839 * @param fOutputFlags Flags of type VBOXSERVICETOOLBOXOUTPUTFLAG.
840 * @param pIdCache The ID cache.
841 */
842static int vgsvcToolboxLsHandleDirSub(char *pszDir, size_t cchDir, PRTDIRENTRYEX pDirEntry,
843 uint32_t fFlags, uint32_t fOutputFlags, PVGSVCTOOLBOXIDCACHE pIdCache)
844{
845 Assert(cchDir > 0); Assert(pszDir[cchDir] == '\0');
846
847 if (fOutputFlags & VBOXSERVICETOOLBOXOUTPUTFLAG_PARSEABLE)
848 RTPrintf("dname=%s%c", pszDir, 0);
849 else if (fFlags & VBOXSERVICETOOLBOXLSFLAG_RECURSIVE)
850 RTPrintf("%s:\n", pszDir);
851
852 /* Make sure we've got some room in the path, to save us extra work further down. */
853 if (cchDir + 3 >= RTPATH_MAX)
854 {
855 if (!(fOutputFlags & VBOXSERVICETOOLBOXOUTPUTFLAG_PARSEABLE))
856 RTMsgError("Path too long: '%s'\n", pszDir);
857 return VERR_BUFFER_OVERFLOW;
858 }
859
860 /* Open directory. */
861 RTDIR hDir;
862 int rc = RTDirOpen(&hDir, pszDir);
863 if (RT_FAILURE(rc))
864 {
865 if (!(fOutputFlags & VBOXSERVICETOOLBOXOUTPUTFLAG_PARSEABLE))
866 RTMsgError("Failed to open directory '%s', rc=%Rrc\n", pszDir, rc);
867 return rc;
868 }
869
870 /* Ensure we've got a trailing slash (there is space for it see above). */
871 if (!RTPATH_IS_SEP(pszDir[cchDir - 1]))
872 {
873 pszDir[cchDir++] = RTPATH_SLASH;
874 pszDir[cchDir] = '\0';
875 }
876
877 /*
878 * Process the files and subdirs.
879 */
880 for (;;)
881 {
882 /* Get the next directory. */
883 size_t cbDirEntry = VBOXSERVICETOOLBOX_DIRENTRY_BUF_SIZE;
884 rc = RTDirReadEx(hDir, pDirEntry, &cbDirEntry, RTFSOBJATTRADD_UNIX, RTPATH_F_ON_LINK);
885 if (RT_FAILURE(rc))
886 break;
887
888 /* Check length. */
889 if (pDirEntry->cbName + cchDir + 3 >= RTPATH_MAX)
890 {
891 if (!(fOutputFlags & VBOXSERVICETOOLBOXOUTPUTFLAG_PARSEABLE))
892 RTMsgError("Path too long: '%s' in '%.*s'\n", pDirEntry->szName, cchDir, pszDir);
893 rc = VERR_BUFFER_OVERFLOW;
894 break;
895 }
896
897 switch (pDirEntry->Info.Attr.fMode & RTFS_TYPE_MASK)
898 {
899 case RTFS_TYPE_SYMLINK:
900 {
901 if (!(fFlags & VBOXSERVICETOOLBOXLSFLAG_SYMLINKS))
902 break;
903 RT_FALL_THRU();
904 }
905 case RTFS_TYPE_DIRECTORY:
906 {
907 rc = vgsvcToolboxPrintFsInfo(pDirEntry->szName, pDirEntry->cbName, fOutputFlags, pszDir,
908 pIdCache, &pDirEntry->Info);
909 if (RT_FAILURE(rc))
910 break;
911
912 if (RTDirEntryExIsStdDotLink(pDirEntry))
913 continue;
914
915 if (!(fFlags & VBOXSERVICETOOLBOXLSFLAG_RECURSIVE))
916 continue;
917
918 memcpy(&pszDir[cchDir], pDirEntry->szName, pDirEntry->cbName + 1);
919 int rc2 = vgsvcToolboxLsHandleDirSub(pszDir, cchDir + pDirEntry->cbName, pDirEntry, fFlags, fOutputFlags, pIdCache);
920 if (RT_SUCCESS(rc))
921 rc = rc2;
922 break;
923 }
924
925 case RTFS_TYPE_FILE:
926 {
927 rc = vgsvcToolboxPrintFsInfo(pDirEntry->szName, pDirEntry->cbName, fOutputFlags, pszDir,
928 pIdCache, &pDirEntry->Info);
929 break;
930 }
931
932 default:
933 {
934 if (!(fOutputFlags & VBOXSERVICETOOLBOXOUTPUTFLAG_PARSEABLE))
935 RTMsgError("Entry '%.*s%s' of mode %#x not supported, skipping",
936 cchDir, pszDir, pDirEntry->szName, pDirEntry->Info.Attr.fMode & RTFS_TYPE_MASK);
937 break;
938 }
939 }
940 }
941 if (rc != VERR_NO_MORE_FILES)
942 {
943 if (!(fOutputFlags & VBOXSERVICETOOLBOXOUTPUTFLAG_PARSEABLE))
944 RTMsgError("RTDirReadEx failed: %Rrc\npszDir=%.*s", rc, cchDir, pszDir);
945 }
946
947 rc = RTDirClose(hDir);
948 if (RT_FAILURE(rc))
949 {
950 if (!(fOutputFlags & VBOXSERVICETOOLBOXOUTPUTFLAG_PARSEABLE))
951 RTMsgError("RTDirClose failed: %Rrc\npszDir=%.*s", rc, cchDir, pszDir);
952 }
953
954 return rc;
955}
956
957/**
958 * Helper routine for ls tool doing the actual parsing and output of
959 * a specified directory.
960 *
961 * @return IPRT status code.
962 * @param pszDir Absolute path to directory to ouptut.
963 * @param fFlags Flags of type VBOXSERVICETOOLBOXLSFLAG.
964 * @param fOutputFlags Flags of type VBOXSERVICETOOLBOXOUTPUTFLAG.
965 * @param pIdCache The ID cache.
966 */
967static int vgsvcToolboxLsHandleDir(const char *pszDir, uint32_t fFlags, uint32_t fOutputFlags, PVGSVCTOOLBOXIDCACHE pIdCache)
968{
969 AssertPtrReturn(pszDir, VERR_INVALID_PARAMETER);
970 AssertPtrReturn(pIdCache, VERR_INVALID_PARAMETER);
971
972 char szPath[RTPATH_MAX];
973 int rc = RTPathAbs(pszDir, szPath, sizeof(szPath));
974 if (RT_FAILURE(rc))
975 {
976 if (!(fOutputFlags & VBOXSERVICETOOLBOXOUTPUTFLAG_PARSEABLE))
977 RTMsgError("RTPathAbs failed on '%s': %Rrc\n", pszDir, rc);
978 return rc;
979 }
980
981 union
982 {
983 uint8_t abPadding[VBOXSERVICETOOLBOX_DIRENTRY_BUF_SIZE];
984 RTDIRENTRYEX DirEntry;
985 } uBuf;
986 return vgsvcToolboxLsHandleDirSub(szPath, strlen(szPath), &uBuf.DirEntry, fFlags, fOutputFlags, pIdCache);
987}
988
989
990/** @todo Document options! */
991static char g_paszLsHelp[] =
992 " VBoxService [--use-toolbox] vbox_ls [<general options>] [option]...\n"
993 " [<file>...]\n\n"
994 "List information about files (the current directory by default).\n\n"
995 "Options:\n\n"
996 " [--dereference|-L]\n"
997 " [-l][-R]\n"
998 " [--verbose|-v]\n"
999 " [<file>...]\n"
1000 "\n";
1001
1002
1003/**
1004 * Main function for tool "vbox_ls".
1005 *
1006 * @return RTEXITCODE.
1007 * @param argc Number of arguments.
1008 * @param argv Pointer to argument array.
1009 */
1010static RTEXITCODE vgsvcToolboxLs(int argc, char **argv)
1011{
1012 static const RTGETOPTDEF s_aOptions[] =
1013 {
1014 { "--machinereadable", VBOXSERVICETOOLBOXOPT_MACHINE_READABLE, RTGETOPT_REQ_NOTHING },
1015 { "--dereference", 'L', RTGETOPT_REQ_NOTHING },
1016 { NULL, 'l', RTGETOPT_REQ_NOTHING },
1017 { NULL, 'R', RTGETOPT_REQ_NOTHING },
1018 { "--verbose", VBOXSERVICETOOLBOXOPT_VERBOSE, RTGETOPT_REQ_NOTHING}
1019 };
1020
1021 int ch;
1022 RTGETOPTUNION ValueUnion;
1023 RTGETOPTSTATE GetState;
1024 int rc = RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions),
1025 1 /*iFirst*/, RTGETOPTINIT_FLAGS_OPTS_FIRST);
1026 AssertRCReturn(rc, RTEXITCODE_INIT);
1027
1028 bool fVerbose = false;
1029 uint32_t fFlags = VBOXSERVICETOOLBOXLSFLAG_NONE;
1030 uint32_t fOutputFlags = VBOXSERVICETOOLBOXOUTPUTFLAG_NONE;
1031
1032 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
1033 {
1034 /* For options that require an argument, ValueUnion has received the value. */
1035 switch (ch)
1036 {
1037 case 'h':
1038 vgsvcToolboxShowUsageHeader();
1039 RTPrintf("%s", g_paszLsHelp);
1040 return RTEXITCODE_SUCCESS;
1041
1042 case 'L': /* Dereference symlinks. */
1043 fFlags |= VBOXSERVICETOOLBOXLSFLAG_SYMLINKS;
1044 break;
1045
1046 case 'l': /* Print long format. */
1047 fOutputFlags |= VBOXSERVICETOOLBOXOUTPUTFLAG_LONG;
1048 break;
1049
1050 case VBOXSERVICETOOLBOXOPT_MACHINE_READABLE:
1051 fOutputFlags |= VBOXSERVICETOOLBOXOUTPUTFLAG_PARSEABLE;
1052 break;
1053
1054 case 'R': /* Recursive processing. */
1055 fFlags |= VBOXSERVICETOOLBOXLSFLAG_RECURSIVE;
1056 break;
1057
1058 case VBOXSERVICETOOLBOXOPT_VERBOSE:
1059 fVerbose = true;
1060 break;
1061
1062 case 'V':
1063 vgsvcToolboxShowVersion();
1064 return RTEXITCODE_SUCCESS;
1065
1066 case VINF_GETOPT_NOT_OPTION:
1067 Assert(GetState.iNext);
1068 GetState.iNext--;
1069 break;
1070
1071 default:
1072 return RTGetOptPrintError(ch, &ValueUnion);
1073 }
1074
1075 /* All flags / options processed? Bail out here.
1076 * Processing the file / directory list comes down below. */
1077 if (ch == VINF_GETOPT_NOT_OPTION)
1078 break;
1079 }
1080
1081 /* Print magic/version. */
1082 if (fOutputFlags & VBOXSERVICETOOLBOXOUTPUTFLAG_PARSEABLE)
1083 {
1084 rc = vgsvcToolboxStrmInit();
1085 if (RT_FAILURE(rc))
1086 RTMsgError("Error while initializing parseable streams, rc=%Rrc\n", rc);
1087 vgsvcToolboxPrintStrmHeader("vbt_ls", 1 /* Stream version */);
1088 }
1089
1090 VGSVCTOOLBOXIDCACHE IdCache;
1091 RT_ZERO(IdCache);
1092
1093 char szDirCur[RTPATH_MAX];
1094 rc = RTPathGetCurrent(szDirCur, sizeof(szDirCur));
1095 if (RT_FAILURE(rc))
1096 {
1097 RTMsgError("Getting current directory failed, rc=%Rrc\n", rc);
1098 return RTEXITCODE_FAILURE;
1099 }
1100
1101 ch = RTGetOpt(&GetState, &ValueUnion);
1102 do
1103 {
1104 char const *pszPath;
1105
1106 if (ch == 0) /* Use current directory if no element specified. */
1107 pszPath = szDirCur;
1108 else
1109 pszPath = ValueUnion.psz;
1110
1111 RTFSOBJINFO objInfo;
1112 int rc2 = RTPathQueryInfoEx(pszPath, &objInfo,
1113 RTFSOBJATTRADD_UNIX,
1114 fFlags & VBOXSERVICETOOLBOXLSFLAG_SYMLINKS ? RTPATH_F_FOLLOW_LINK : RTPATH_F_ON_LINK);
1115 if (RT_SUCCESS(rc2))
1116 {
1117 if ( RTFS_IS_FILE(objInfo.Attr.fMode)
1118 || ( RTFS_IS_SYMLINK(objInfo.Attr.fMode)
1119 && (fFlags & VBOXSERVICETOOLBOXLSFLAG_SYMLINKS)))
1120 {
1121 rc2 = vgsvcToolboxPrintFsInfo(pszPath, strlen(pszPath), fOutputFlags, NULL, &IdCache, &objInfo);
1122 if (RT_SUCCESS(rc)) /* Keep initial failing rc. */
1123 rc = rc2;
1124 }
1125 else if (RTFS_IS_DIRECTORY(objInfo.Attr.fMode))
1126 {
1127 rc2 = vgsvcToolboxLsHandleDir(pszPath, fFlags, fOutputFlags, &IdCache);
1128 if (RT_SUCCESS(rc)) /* Keep initial failing rc. */
1129 rc = rc2;
1130 }
1131 }
1132 else
1133 {
1134 if (!(fOutputFlags & VBOXSERVICETOOLBOXOUTPUTFLAG_PARSEABLE))
1135 RTMsgError("Cannot access '%s': No such file or directory\n", pszPath);
1136 if (RT_SUCCESS(rc))
1137 rc = VERR_FILE_NOT_FOUND;
1138 /* Do not break here -- process every element in the list
1139 * and keep failing rc. */
1140 }
1141
1142 } while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0);
1143
1144 if (fOutputFlags & VBOXSERVICETOOLBOXOUTPUTFLAG_PARSEABLE) /* Output termination. */
1145 vgsvcToolboxPrintStrmTermination();
1146
1147 return RT_SUCCESS(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
1148}
1149
1150
1151/* Try using RTPathRmCmd. */
1152static RTEXITCODE vgsvcToolboxRm(int argc, char **argv)
1153{
1154 return RTPathRmCmd(argc, argv);
1155}
1156
1157
1158static char g_paszMkTempHelp[] =
1159 " VBoxService [--use-toolbox] vbox_mktemp [<general options>] [<options>]\n"
1160 " <template>\n\n"
1161 "Create a temporary directory based on the template supplied. The first string\n"
1162 "of consecutive 'X' characters in the template will be replaced to form a unique\n"
1163 "name for the directory. The template may not contain a path. The default\n"
1164 "creation mode is 0600 for files and 0700 for directories. If no path is\n"
1165 "specified the default temporary directory will be used.\n"
1166 "Options:\n\n"
1167 " [--directory|-d] Create a directory instead of a file.\n"
1168 " [--mode|-m <mode>] Create the object with mode <mode>.\n"
1169 " [--secure|-s] Fail if the object cannot be created securely.\n"
1170 " [--tmpdir|-t <path>] Create the object with the absolute path <path>.\n"
1171 "\n";
1172
1173
1174/**
1175 * Report the result of a vbox_mktemp operation.
1176 *
1177 * Either errors to stderr (not machine-readable) or everything to stdout as
1178 * {name}\0{rc}\0 (machine- readable format). The message may optionally
1179 * contain a '%s' for the file name and an %Rrc for the result code in that
1180 * order. In future a "verbose" flag may be added, without which nothing will
1181 * be output in non-machine- readable mode. Sets prc if rc is a non-success
1182 * code.
1183 */
1184static void toolboxMkTempReport(const char *pcszMessage, const char *pcszFile,
1185 bool fActive, int rc, uint32_t fOutputFlags, int *prc)
1186{
1187 if (!fActive)
1188 return;
1189 if (!(fOutputFlags & VBOXSERVICETOOLBOXOUTPUTFLAG_PARSEABLE))
1190 if (RT_SUCCESS(rc))
1191 RTPrintf(pcszMessage, pcszFile, rc);
1192 else
1193 RTMsgError(pcszMessage, pcszFile, rc);
1194 else
1195 RTPrintf("name=%s%crc=%d%c", pcszFile, 0, rc, 0);
1196 if (prc && RT_FAILURE(rc))
1197 *prc = rc;
1198}
1199
1200
1201/**
1202 * Main function for tool "vbox_mktemp".
1203 *
1204 * @return RTEXITCODE.
1205 * @param argc Number of arguments.
1206 * @param argv Pointer to argument array.
1207 */
1208static RTEXITCODE vgsvcToolboxMkTemp(int argc, char **argv)
1209{
1210 static const RTGETOPTDEF s_aOptions[] =
1211 {
1212 { "--machinereadable", VBOXSERVICETOOLBOXOPT_MACHINE_READABLE,
1213 RTGETOPT_REQ_NOTHING },
1214 { "--directory", 'd', RTGETOPT_REQ_NOTHING },
1215 { "--mode", 'm', RTGETOPT_REQ_STRING },
1216 { "--secure", 's', RTGETOPT_REQ_NOTHING },
1217 { "--tmpdir", 't', RTGETOPT_REQ_STRING },
1218 };
1219
1220 enum
1221 {
1222 /* Isn't that a bit long? s/VBOXSERVICETOOLBOX/VSTB/ ? */
1223 /** Create a temporary directory instead of a temporary file. */
1224 VBOXSERVICETOOLBOXMKTEMPFLAG_DIRECTORY = RT_BIT_32(0),
1225 /** Only create the temporary object if the operation is expected
1226 * to be secure. Not guaranteed to be supported on a particular
1227 * set-up. */
1228 VBOXSERVICETOOLBOXMKTEMPFLAG_SECURE = RT_BIT_32(1)
1229 };
1230
1231 int ch, rc;
1232 RTGETOPTUNION ValueUnion;
1233 RTGETOPTSTATE GetState;
1234 rc = RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1 /*iFirst*/, RTGETOPTINIT_FLAGS_OPTS_FIRST);
1235 AssertRCReturn(rc, RTEXITCODE_INIT);
1236
1237 uint32_t fFlags = 0;
1238 uint32_t fOutputFlags = 0;
1239 int cNonOptions = 0;
1240 RTFMODE fMode = 0700;
1241 bool fModeSet = false;
1242 const char *pcszPath = NULL;
1243 const char *pcszTemplate;
1244 char szTemplateWithPath[RTPATH_MAX] = "";
1245
1246 while ( (ch = RTGetOpt(&GetState, &ValueUnion))
1247 && RT_SUCCESS(rc))
1248 {
1249 /* For options that require an argument, ValueUnion has received the value. */
1250 switch (ch)
1251 {
1252 case 'h':
1253 vgsvcToolboxShowUsageHeader();
1254 RTPrintf("%s", g_paszMkTempHelp);
1255 return RTEXITCODE_SUCCESS;
1256
1257 case 'V':
1258 vgsvcToolboxShowVersion();
1259 return RTEXITCODE_SUCCESS;
1260
1261 case VBOXSERVICETOOLBOXOPT_MACHINE_READABLE:
1262 fOutputFlags |= VBOXSERVICETOOLBOXOUTPUTFLAG_PARSEABLE;
1263 break;
1264
1265 case 'd':
1266 fFlags |= VBOXSERVICETOOLBOXMKTEMPFLAG_DIRECTORY;
1267 break;
1268
1269 case 'm':
1270 rc = vgsvcToolboxParseMode(ValueUnion.psz, &fMode);
1271 if (RT_FAILURE(rc))
1272 return RTEXITCODE_SYNTAX;
1273 fModeSet = true;
1274#ifndef RT_OS_WINDOWS
1275 umask(0); /* RTDirCreate workaround */
1276#endif
1277 break;
1278 case 's':
1279 fFlags |= VBOXSERVICETOOLBOXMKTEMPFLAG_SECURE;
1280 break;
1281
1282 case 't':
1283 pcszPath = ValueUnion.psz;
1284 break;
1285
1286 case VINF_GETOPT_NOT_OPTION:
1287 /* RTGetOpt will sort these to the end of the argv vector so
1288 * that we will deal with them afterwards. */
1289 ++cNonOptions;
1290 break;
1291
1292 default:
1293 return RTGetOptPrintError(ch, &ValueUnion);
1294 }
1295 }
1296
1297 /* Print magic/version. */
1298 if (fOutputFlags & VBOXSERVICETOOLBOXOUTPUTFLAG_PARSEABLE)
1299 {
1300 rc = vgsvcToolboxStrmInit();
1301 if (RT_FAILURE(rc))
1302 RTMsgError("Error while initializing parseable streams, rc=%Rrc\n", rc);
1303 vgsvcToolboxPrintStrmHeader("vbt_mktemp", 1 /* Stream version */);
1304 }
1305
1306 if (fFlags & VBOXSERVICETOOLBOXMKTEMPFLAG_SECURE && fModeSet)
1307 {
1308 toolboxMkTempReport("'-s' and '-m' parameters cannot be used together.\n", "",
1309 true, VERR_INVALID_PARAMETER, fOutputFlags, &rc);
1310 return RTEXITCODE_SYNTAX;
1311 }
1312
1313 /* We need exactly one template, containing at least one 'X'. */
1314 if (cNonOptions != 1)
1315 {
1316 toolboxMkTempReport("Please specify exactly one template.\n", "", true, VERR_INVALID_PARAMETER, fOutputFlags, &rc);
1317 return RTEXITCODE_SYNTAX;
1318 }
1319 pcszTemplate = argv[argc - 1];
1320
1321 /* Validate that the template is as IPRT requires (asserted by IPRT). */
1322 if ( RTPathHasPath(pcszTemplate)
1323 || ( !strstr(pcszTemplate, "XXX")
1324 && pcszTemplate[strlen(pcszTemplate) - 1] != 'X'))
1325 {
1326 toolboxMkTempReport("Template '%s' should contain a file name with no path and at least three consecutive 'X' characters or ending in 'X'.\n",
1327 pcszTemplate, true, VERR_INVALID_PARAMETER, fOutputFlags, &rc);
1328 return RTEXITCODE_FAILURE;
1329 }
1330 if (pcszPath && !RTPathStartsWithRoot(pcszPath))
1331 {
1332 toolboxMkTempReport("Path '%s' should be absolute.\n", pcszPath, true, VERR_INVALID_PARAMETER, fOutputFlags, &rc);
1333 return RTEXITCODE_FAILURE;
1334 }
1335 if (pcszPath)
1336 {
1337 rc = RTStrCopy(szTemplateWithPath, sizeof(szTemplateWithPath), pcszPath);
1338 if (RT_FAILURE(rc))
1339 {
1340 toolboxMkTempReport("Path '%s' too long.\n", pcszPath, true, VERR_INVALID_PARAMETER, fOutputFlags, &rc);
1341 return RTEXITCODE_FAILURE;
1342 }
1343 }
1344 else
1345 {
1346 rc = RTPathTemp(szTemplateWithPath, sizeof(szTemplateWithPath));
1347 if (RT_FAILURE(rc))
1348 {
1349 toolboxMkTempReport("Failed to get the temporary directory.\n", "", true, VERR_INVALID_PARAMETER, fOutputFlags, &rc);
1350 return RTEXITCODE_FAILURE;
1351 }
1352 }
1353 rc = RTPathAppend(szTemplateWithPath, sizeof(szTemplateWithPath), pcszTemplate);
1354 if (RT_FAILURE(rc))
1355 {
1356 toolboxMkTempReport("Template '%s' too long for path.\n", pcszTemplate, true, VERR_INVALID_PARAMETER, fOutputFlags, &rc);
1357 return RTEXITCODE_FAILURE;
1358 }
1359
1360 if (fFlags & VBOXSERVICETOOLBOXMKTEMPFLAG_DIRECTORY)
1361 {
1362 rc = fFlags & VBOXSERVICETOOLBOXMKTEMPFLAG_SECURE
1363 ? RTDirCreateTempSecure(szTemplateWithPath)
1364 : RTDirCreateTemp(szTemplateWithPath, fMode);
1365 toolboxMkTempReport("Created temporary directory '%s'.\n",
1366 szTemplateWithPath, RT_SUCCESS(rc), rc,
1367 fOutputFlags, NULL);
1368 /* RTDirCreateTemp[Secure] sets the template to "" on failure. */
1369 toolboxMkTempReport("The following error occurred while creating a temporary directory from template '%s': %Rrc.\n",
1370 pcszTemplate, RT_FAILURE(rc), rc, fOutputFlags, NULL /*prc*/);
1371 }
1372 else
1373 {
1374 rc = fFlags & VBOXSERVICETOOLBOXMKTEMPFLAG_SECURE
1375 ? RTFileCreateTempSecure(szTemplateWithPath)
1376 : RTFileCreateTemp(szTemplateWithPath, fMode);
1377 toolboxMkTempReport("Created temporary file '%s'.\n",
1378 szTemplateWithPath, RT_SUCCESS(rc), rc,
1379 fOutputFlags, NULL);
1380 /* RTFileCreateTemp[Secure] sets the template to "" on failure. */
1381 toolboxMkTempReport("The following error occurred while creating a temporary file from template '%s': %Rrc.\n",
1382 pcszTemplate, RT_FAILURE(rc), rc, fOutputFlags, NULL /*prc*/);
1383 }
1384 if (fOutputFlags & VBOXSERVICETOOLBOXOUTPUTFLAG_PARSEABLE) /* Output termination. */
1385 vgsvcToolboxPrintStrmTermination();
1386 return RT_SUCCESS(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
1387}
1388
1389
1390/** @todo Document options! */
1391static char g_paszMkDirHelp[] =
1392 " VBoxService [--use-toolbox] vbox_mkdir [<general options>] [<options>]\n"
1393 " <directory>...\n\n"
1394 "Options:\n\n"
1395 " [--mode|-m <mode>] The file mode to set (chmod) on the created\n"
1396 " directories. Default: a=rwx & umask.\n"
1397 " [--parents|-p] Create parent directories as needed, no\n"
1398 " error if the directory already exists.\n"
1399 " [--verbose|-v] Display a message for each created directory.\n"
1400 "\n";
1401
1402
1403/**
1404 * Main function for tool "vbox_mkdir".
1405 *
1406 * @return RTEXITCODE.
1407 * @param argc Number of arguments.
1408 * @param argv Pointer to argument array.
1409 */
1410static RTEXITCODE vgsvcToolboxMkDir(int argc, char **argv)
1411{
1412 static const RTGETOPTDEF s_aOptions[] =
1413 {
1414 { "--mode", 'm', RTGETOPT_REQ_STRING },
1415 { "--parents", 'p', RTGETOPT_REQ_NOTHING},
1416 { "--verbose", 'v', RTGETOPT_REQ_NOTHING}
1417 };
1418
1419 int ch;
1420 RTGETOPTUNION ValueUnion;
1421 RTGETOPTSTATE GetState;
1422 int rc = RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions),
1423 1 /*iFirst*/, RTGETOPTINIT_FLAGS_OPTS_FIRST);
1424 AssertRCReturn(rc, RTEXITCODE_INIT);
1425
1426 bool fMakeParentDirs = false;
1427 bool fVerbose = false;
1428 RTFMODE fDirMode = RTFS_UNIX_IRWXU | RTFS_UNIX_IRWXG | RTFS_UNIX_IRWXO;
1429 int cDirsCreated = 0;
1430
1431 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
1432 {
1433 /* For options that require an argument, ValueUnion has received the value. */
1434 switch (ch)
1435 {
1436 case 'p':
1437 fMakeParentDirs = true;
1438 break;
1439
1440 case 'm':
1441 rc = vgsvcToolboxParseMode(ValueUnion.psz, &fDirMode);
1442 if (RT_FAILURE(rc))
1443 return RTEXITCODE_SYNTAX;
1444#ifndef RT_OS_WINDOWS
1445 umask(0); /* RTDirCreate workaround */
1446#endif
1447 break;
1448
1449 case 'v':
1450 fVerbose = true;
1451 break;
1452
1453 case 'h':
1454 vgsvcToolboxShowUsageHeader();
1455 RTPrintf("%s", g_paszMkDirHelp);
1456 return RTEXITCODE_SUCCESS;
1457
1458 case 'V':
1459 vgsvcToolboxShowVersion();
1460 return RTEXITCODE_SUCCESS;
1461
1462 case VINF_GETOPT_NOT_OPTION:
1463 if (fMakeParentDirs)
1464 /** @todo r=bird: If fVerbose is set, we should also show
1465 * which directories that get created, parents as well as
1466 * omitting existing final dirs. Annoying, but check any
1467 * mkdir implementation (try "mkdir -pv asdf/1/2/3/4"
1468 * twice). */
1469 rc = RTDirCreateFullPath(ValueUnion.psz, fDirMode);
1470 else
1471 rc = RTDirCreate(ValueUnion.psz, fDirMode, 0);
1472 if (RT_FAILURE(rc))
1473 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Could not create directory '%s': %Rra\n",
1474 ValueUnion.psz, rc);
1475 if (fVerbose)
1476 RTMsgInfo("Created directory '%s', mode %#RTfmode\n", ValueUnion.psz, fDirMode);
1477 cDirsCreated++;
1478 break;
1479
1480 default:
1481 return RTGetOptPrintError(ch, &ValueUnion);
1482 }
1483 }
1484 AssertRC(rc);
1485
1486 if (cDirsCreated == 0)
1487 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "No directory argument.");
1488
1489 return RTEXITCODE_SUCCESS;
1490}
1491
1492
1493/** @todo Document options! */
1494static char g_paszStatHelp[] =
1495 " VBoxService [--use-toolbox] vbox_stat [<general options>] [<options>]\n"
1496 " <file>...\n\n"
1497 "Display file or file system status.\n\n"
1498 "Options:\n\n"
1499 " [--file-system|-f]\n"
1500 " [--dereference|-L]\n"
1501 " [--terse|-t]\n"
1502 " [--verbose|-v]\n"
1503 "\n";
1504
1505
1506/**
1507 * Main function for tool "vbox_stat".
1508 *
1509 * @return RTEXITCODE.
1510 * @param argc Number of arguments.
1511 * @param argv Pointer to argument array.
1512 */
1513static RTEXITCODE vgsvcToolboxStat(int argc, char **argv)
1514{
1515 static const RTGETOPTDEF s_aOptions[] =
1516 {
1517 { "--file-system", 'f', RTGETOPT_REQ_NOTHING },
1518 { "--dereference", 'L', RTGETOPT_REQ_NOTHING },
1519 { "--machinereadable", VBOXSERVICETOOLBOXOPT_MACHINE_READABLE, RTGETOPT_REQ_NOTHING },
1520 { "--terse", 't', RTGETOPT_REQ_NOTHING },
1521 { "--verbose", 'v', RTGETOPT_REQ_NOTHING }
1522 };
1523
1524 int ch;
1525 RTGETOPTUNION ValueUnion;
1526 RTGETOPTSTATE GetState;
1527 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1 /*iFirst*/, RTGETOPTINIT_FLAGS_OPTS_FIRST);
1528
1529 int rc = VINF_SUCCESS;
1530 uint32_t fOutputFlags = VBOXSERVICETOOLBOXOUTPUTFLAG_LONG; /* Use long mode by default. */
1531 uint32_t fQueryInfoFlags = RTPATH_F_ON_LINK;
1532
1533 while ( (ch = RTGetOpt(&GetState, &ValueUnion))
1534 && RT_SUCCESS(rc))
1535 {
1536 /* For options that require an argument, ValueUnion has received the value. */
1537 switch (ch)
1538 {
1539 case 'f':
1540 RTMsgError("Sorry, option '%s' is not implemented yet!\n", ValueUnion.pDef->pszLong);
1541 rc = VERR_INVALID_PARAMETER;
1542 break;
1543
1544 case 'L':
1545 fQueryInfoFlags &= ~RTPATH_F_ON_LINK;
1546 fQueryInfoFlags |= RTPATH_F_FOLLOW_LINK;
1547 break;
1548
1549 case VBOXSERVICETOOLBOXOPT_MACHINE_READABLE:
1550 fOutputFlags |= VBOXSERVICETOOLBOXOUTPUTFLAG_PARSEABLE;
1551 break;
1552
1553 case 'h':
1554 vgsvcToolboxShowUsageHeader();
1555 RTPrintf("%s", g_paszStatHelp);
1556 return RTEXITCODE_SUCCESS;
1557
1558 case 'V':
1559 vgsvcToolboxShowVersion();
1560 return RTEXITCODE_SUCCESS;
1561
1562 case VINF_GETOPT_NOT_OPTION:
1563 {
1564 Assert(GetState.iNext);
1565 GetState.iNext--;
1566 break;
1567 }
1568
1569 default:
1570 return RTGetOptPrintError(ch, &ValueUnion);
1571 }
1572
1573 /* All flags / options processed? Bail out here.
1574 * Processing the file / directory list comes down below. */
1575 if (ch == VINF_GETOPT_NOT_OPTION)
1576 break;
1577 }
1578
1579 if (RT_SUCCESS(rc))
1580 {
1581 if (fOutputFlags & VBOXSERVICETOOLBOXOUTPUTFLAG_PARSEABLE) /* Output termination. */
1582 {
1583 rc = vgsvcToolboxStrmInit();
1584 if (RT_FAILURE(rc))
1585 RTMsgError("Error while initializing parseable streams, rc=%Rrc\n", rc);
1586 vgsvcToolboxPrintStrmHeader("vbt_stat", 1 /* Stream version */);
1587 }
1588
1589 VGSVCTOOLBOXIDCACHE IdCache;
1590 RT_ZERO(IdCache);
1591
1592 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
1593 {
1594 RTFSOBJINFO objInfo;
1595 int rc2 = RTPathQueryInfoEx(ValueUnion.psz, &objInfo, RTFSOBJATTRADD_UNIX, fQueryInfoFlags);
1596 if (RT_FAILURE(rc2))
1597 {
1598 if (!(fOutputFlags & VBOXSERVICETOOLBOXOUTPUTFLAG_PARSEABLE))
1599 RTMsgError("Cannot stat for '%s': %Rrc\n", ValueUnion.psz, rc2);
1600 }
1601 else
1602 rc2 = vgsvcToolboxPrintFsInfo(ValueUnion.psz, strlen(ValueUnion.psz), fOutputFlags, NULL, &IdCache, &objInfo);
1603
1604 if (RT_SUCCESS(rc))
1605 rc = rc2;
1606 /* Do not break here -- process every element in the list
1607 * and keep (initial) failing rc. */
1608 }
1609
1610 if (fOutputFlags & VBOXSERVICETOOLBOXOUTPUTFLAG_PARSEABLE) /* Output termination. */
1611 vgsvcToolboxPrintStrmTermination();
1612
1613 /* At this point the overall result (success/failure) should be in rc. */
1614 }
1615 else
1616 RTMsgError("Failed with rc=%Rrc\n", rc);
1617
1618 if (RT_FAILURE(rc))
1619 {
1620 switch (rc)
1621 {
1622 case VERR_ACCESS_DENIED:
1623 return (RTEXITCODE)VBOXSERVICETOOLBOX_STAT_EXITCODE_ACCESS_DENIED;
1624
1625 case VERR_FILE_NOT_FOUND:
1626 return (RTEXITCODE)VBOXSERVICETOOLBOX_STAT_EXITCODE_FILE_NOT_FOUND;
1627
1628 case VERR_PATH_NOT_FOUND:
1629 return (RTEXITCODE)VBOXSERVICETOOLBOX_STAT_EXITCODE_PATH_NOT_FOUND;
1630
1631 case VERR_NET_PATH_NOT_FOUND:
1632 return (RTEXITCODE)VBOXSERVICETOOLBOX_STAT_EXITCODE_NET_PATH_NOT_FOUND;
1633
1634 case VERR_INVALID_NAME:
1635 return (RTEXITCODE)VBOXSERVICETOOLBOX_STAT_EXITCODE_INVALID_NAME;
1636
1637 default:
1638#ifdef DEBUG_andy
1639 AssertMsgFailed(("Exit code for %Rrc not implemented\n", rc));
1640#endif
1641 break;
1642 }
1643
1644 return RTEXITCODE_FAILURE;
1645 }
1646
1647 return RTEXITCODE_SUCCESS;
1648}
1649
1650
1651/**
1652 * Looks up the tool definition entry for the tool give by @a pszTool.
1653 *
1654 * @returns Pointer to the tool definition. NULL if not found.
1655 * @param pszTool The name of the tool.
1656 */
1657static PCVBOXSERVICETOOLBOXTOOL vgsvcToolboxLookUp(const char *pszTool)
1658{
1659 AssertPtrReturn(pszTool, NULL);
1660
1661 /* Do a linear search, since we don't have that much stuff in the table. */
1662 for (unsigned i = 0; i < RT_ELEMENTS(g_aTools); i++)
1663 if (!strcmp(g_aTools[i].pszName, pszTool))
1664 return &g_aTools[i];
1665
1666 return NULL;
1667}
1668
1669
1670/**
1671 * Converts a tool's exit code back to an IPRT error code.
1672 *
1673 * @return Converted IPRT status code.
1674 * @param pszTool Name of the toolbox tool to convert exit code for.
1675 * @param rcExit The tool's exit code to convert.
1676 */
1677int VGSvcToolboxExitCodeConvertToRc(const char *pszTool, RTEXITCODE rcExit)
1678{
1679 AssertPtrReturn(pszTool, VERR_INVALID_POINTER);
1680
1681 PCVBOXSERVICETOOLBOXTOOL pTool = vgsvcToolboxLookUp(pszTool);
1682 if (pTool)
1683 return pTool->pfnExitCodeConvertToRc(rcExit);
1684
1685 AssertMsgFailed(("Tool '%s' not found\n", pszTool));
1686 return VERR_GENERAL_FAILURE; /* Lookup failed, should not happen. */
1687}
1688
1689
1690/**
1691 * Entry point for internal toolbox.
1692 *
1693 * @return True if an internal tool was handled, false if not.
1694 * @param argc Number of arguments.
1695 * @param argv Pointer to argument array.
1696 * @param prcExit Where to store the exit code when an
1697 * internal toolbox command was handled.
1698 */
1699bool VGSvcToolboxMain(int argc, char **argv, RTEXITCODE *prcExit)
1700{
1701
1702 /*
1703 * Check if the file named in argv[0] is one of the toolbox programs.
1704 */
1705 AssertReturn(argc > 0, false);
1706 const char *pszTool = RTPathFilename(argv[0]);
1707 PCVBOXSERVICETOOLBOXTOOL pTool = vgsvcToolboxLookUp(pszTool);
1708 if (!pTool)
1709 {
1710 /*
1711 * For debugging and testing purposes we also allow toolbox program access
1712 * when the first VBoxService argument is --use-toolbox.
1713 */
1714 if (argc < 2 || strcmp(argv[1], "--use-toolbox"))
1715 return false;
1716
1717 /* No tool specified? Show toolbox help. */
1718 if (argc < 3)
1719 {
1720 vgsvcToolboxShowUsage();
1721 *prcExit = RTEXITCODE_SYNTAX;
1722 return true;
1723 }
1724
1725 argc -= 2;
1726 argv += 2;
1727 pszTool = argv[0];
1728 pTool = vgsvcToolboxLookUp(pszTool);
1729 if (!pTool)
1730 {
1731 *prcExit = RTEXITCODE_SUCCESS;
1732 if (!strcmp(pszTool, "-V"))
1733 {
1734 vgsvcToolboxShowVersion();
1735 return true;
1736 }
1737 if ( strcmp(pszTool, "help")
1738 && strcmp(pszTool, "--help")
1739 && strcmp(pszTool, "-h"))
1740 *prcExit = RTEXITCODE_SYNTAX;
1741 vgsvcToolboxShowUsage();
1742 return true;
1743 }
1744 }
1745
1746 /*
1747 * Invoke the handler.
1748 */
1749 RTMsgSetProgName("VBoxService/%s", pszTool);
1750 AssertPtr(pTool);
1751 *prcExit = pTool->pfnHandler(argc, argv);
1752
1753 return true;
1754}
1755
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