This repository has been archived by the owner on Jul 23, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathwrap.c
97 lines (77 loc) · 2.22 KB
/
wrap.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
#include <json-c/json.h>
#include "wrap.h"
#include "command.h"
#include "message.h"
#define PIPE_READ 0
#define PIPE_WRITE 1
static char *json_wrap(const char *result) {
char *json;
json_object *jobj = json_object_new_object();
json_object *jstring = json_object_new_string(result);
json_object_object_add(jobj, "result", jstring);
json = strdup(json_object_to_json_string(jobj));
json_object_put(jobj);
return json;
}
/* Returns NULL if the command failed.
* args must end with a NULL pointer.
*/
char *do_command(char *script, char *args[]) {
pid_t pid;
int pipe_fd[2];
char response[MAX_MSG_LEN + 1];
memset(response, 0, MAX_MSG_LEN + 1);
if (pipe(pipe_fd) == -1) {
p_error("pipe()", "Could not create pipe.");
return NULL;
}
pid = fork();
if (pid < 0) {
return NULL;
} else if (pid == 0) { /* child */
close(pipe_fd[PIPE_READ]);
dup2(pipe_fd[PIPE_WRITE], 1);
dup2(pipe_fd[PIPE_WRITE], 2);
char **argv = build_argv(script, args);
execve(argv[0], argv, NULL);
free_argv(argv);
p_error("execve()", "Could not execute command.");
exit(-1);
} else { /* parent */
int n = 0;
waitpid(pid, NULL, WUNTRACED);
close(pipe_fd[PIPE_WRITE]);
if ((n = read(pipe_fd[PIPE_READ], response, MAX_MSG_LEN) < 0)) {
p_error("read()", "Could not read from pipe.");
return NULL;
}
response[MAX_MSG_LEN] = 0;
close(pipe_fd[PIPE_READ]);
}
return json_wrap(response);
}
/* create {"/bin/sh", "script", args[0], ..., args[n], NULL} on heap */
char **build_argv(char *script, char *args[]) {
int i, n_args = 0;
char **argv = NULL;
for (i = 0; args[i] != NULL; i++)
n_args++;
argv = malloc((n_args + 3) * sizeof(char *));
argv[0] = strdup("/bin/sh");
argv[1] = strdup(script);
for (i = 0; args[i] != NULL; i++)
argv[2+i] = strdup(args[i]);
argv[2+i] = NULL;
return argv;
}
void free_argv(char **argv) {
int i;
for (i = 0; argv[i] != NULL; i++)
free(argv[i]);
free(argv);
}