summaryrefslogtreecommitdiff
path: root/src/util.c
blob: 5001e0181fc0082407007c0f34f81ae821c4bdd8 (plain) (blame)
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>

#include <cjson/cJSON.h>

#include "evanix.h"
#include "util.h"

int json_streaming_read(FILE *stream, cJSON **json)
{
	size_t n;
	int ret;
	char *line = NULL;

	errno = 0;
	ret = getline(&line, &n, stream);
	if (ret < 0) {
		if (errno != 0) {
			print_err("%s", strerror(errno));
			ret = -errno;
		}
		ret = -EOF;

		goto out_free_line;
	}

	*json = cJSON_Parse(line);
	if (cJSON_IsInvalid(*json)) {
		print_err("%s", "Invalid JSON");
		ret = -EPERM;
		goto out_free_line;
	}

out_free_line:
	free(line);
	return ret;
}

int vpopen(FILE **stream, const char *file, char *const argv[])
{
	int fd[2], ret;
	int nullfd = -1;

	ret = pipe(fd);
	if (ret < 0) {
		print_err("%s", strerror(errno));
		return -errno;
	}

	ret = fork();
	if (ret < 0) {
		print_err("%s", strerror(errno));

		close(fd[0]);
		close(fd[1]);
		return -errno;
	} else if (ret > 0) {
		close(fd[1]);
		*stream = fdopen(fd[0], "r");
		if (*stream == NULL) {
			print_err("%s", strerror(errno));
			return -errno;
		}

		return 0;
	}

	close(fd[0]);
	ret = dup2(fd[1], STDOUT_FILENO);
	if (ret < 0) {
		print_err("%s", strerror(errno));
		goto out_close_fd_1;
	}

	if (evanix_opts.close_stderr_exec) {
		nullfd = open("/dev/null", O_WRONLY);
		if (nullfd < 0) {
			print_err("%s", strerror(errno));
			goto out_close_fd_1;
		}
		ret = dup2(nullfd, STDERR_FILENO);
		if (ret < 0) {
			print_err("%s", strerror(errno));
			goto out_close_nullfd;
		}
	}

	execvp(file, argv);
	print_err("%s", strerror(errno));

out_close_nullfd:
	if (nullfd >= 0)
		close(nullfd);
out_close_fd_1:
	close(fd[1]);
	exit(EXIT_FAILURE);
}

int atob(const char *s)
{
	if (!strcmp(s, "true") || !strcmp(s, "yes") || !strcmp(s, "y"))
		return true;
	else if (!strcmp(s, "false") || !strcmp(s, "no") || !strcmp(s, "n"))
		return false;

	return -1;
}

int run(const char *file, char *argv[])
{
	int ret, wstatus;

	ret = fork();
	switch (ret) {
	case -1:
		print_err("%s", strerror(errno));
		return -errno;
	case 0:
		execvp(file, argv);
		print_err("%s", strerror(errno));
		exit(EXIT_FAILURE);
	default:
		ret = waitpid(ret, &wstatus, 0);
		if (!WIFEXITED(wstatus))
			return -EPERM;
		return WEXITSTATUS(wstatus) == 0 ? 0 : -EPERM;
	}
}