xref: /haiku/src/tools/fs_shell/fs_shell_command.cpp (revision 17889a8c70dbb3d59c1412f6431968753c767bab)
1 /*
2  * Copyright 2005-2007, Ingo Weinhold, bonefish@cs.tu-berlin.de.
3  * Distributed under the terms of the MIT License.
4  */
5 
6 #include "fs_shell_command.h"
7 
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <string.h>
11 
12 
13 static void
14 add_char(char *&buffer, int &bufferSize, char c)
15 {
16 	if (bufferSize <= 0) {
17 		fprintf(stderr, "Error: Command line too long\n");
18 		exit(1);
19 	}
20 
21 	*buffer = c;
22 	buffer++;
23 	bufferSize--;
24 }
25 
26 
27 static void
28 prepare_command_string(const char *const *argv, int argc, char *buffer,
29 		int bufferSize)
30 {
31 	for (int argi = 0; argi < argc; argi++) {
32 		const char *arg = argv[argi];
33 
34 		if (argi > 0)
35 			add_char(buffer, bufferSize, ' ');
36 
37 		while (*arg) {
38 			if (strchr(" \"'\\", *arg))
39 				add_char(buffer, bufferSize, '\\');
40 			add_char(buffer, bufferSize, *arg);
41 			arg++;
42 		}
43 	}
44 
45 	add_char(buffer, bufferSize, '\0');
46 }
47 
48 
49 int
50 main(int argc, const char *const *argv)
51 {
52 	if (argc < 2) {
53 		fprintf(stderr, "Error: No command given.\n");
54 		exit(1);
55 	}
56 
57 	if (strcmp(argv[1], "--uses-fifos") == 0)
58 		exit(gUsesFifos ? 0 : 1);
59 
60 	// prepare the command string
61 	char command[102400];
62 	prepare_command_string(argv + 1, argc - 1, command, sizeof(command));
63 
64 	// send the command
65 	int result;
66 	if (!send_external_command(command, &result))
67 		exit(1);
68 
69 	// evaluate result
70 	if (result != 0) {
71 		fprintf(stderr, "Error: Command failed: %s\n", strerror(result));
72 		fprintf(stderr, "Error: Command was:\n  %s\n", command);
73 		exit(1);
74 	}
75 
76 	return 0;
77 }
78 
79