summaryrefslogtreecommitdiff
path: root/src/util/exec.c
blob: 687cfbd13c4f18dd60c3b2c375f7995c9aa8d8c6 (plain)
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 "exec.h"

#if HAVE_STDBOOL_H
#include <stdbool.h>
#endif

#include "fs.h"

#include "../log.h"

#include <errno.h>

#include <limits.h>
#if HAVE_LINUX_LIMITS_H
#include <linux/limits.h>
#endif

#include <unistd.h>

static int max_fd() {
	int fd_max = 0;

#ifdef NR_OPEN  /* from <linux/limits.h> */
	fd_max = NR_OPEN;
	if (0 < fd_max) return fd_max;
#endif
#ifdef _SC_OPEN_MAX  /* from <unistd.h> */
	fd_max = sysconf(_SC_OPEN_MAX);
	if (0 < fd_max) return fd_max;
#endif
#ifdef _POSIX_OPEN_MAX  /* from <limits.h> */
	fd_max = _POSIX_OPEN_MAX;
	if (0 < fd_max) return fd_max;
#endif

	return 256;  /* random guess falllback value */
}

pid_t exec_subcmd(
		char *const argv[], int stdin, int stdout, int stderr,
		bool close_fds, const char *cwd, envp_t *const envp) {
	pid_t pid = fork();
	if (0 != pid) {
		/* parent */
		return pid;
	}

	/* child */

	/* replace "standard" FDs */
	if (-1 == dup2(stdin, 0)) {
		sk_error("failed to replace stdin for subcmd: %s", strerror(errno));
		return -1;
	}
	if (-1 == dup2(stdout, 1)) {
		sk_error("failed to replace stdout for subcmd: %s", strerror(errno));
		return -1;
	}
	if (-1 == dup2(stderr, 2)) {
		sk_error("failed to replace stderr for subcmd: %s", strerror(errno));
		return -1;
	}

	if (close_fds) {
		/* close all "non-standard" FDs */
		for (int i = 3, m = max_fd(); i < m; ++i) {
			(void)close(i);
		}
	}

	/* chdir */
	if (NULL != cwd) {
		if (-1 == chdir(cwd)) {
			sk_error(
				"error in subcommand execution: chdir(%s) failed: %s",
				cwd, strerror(errno));
			exit(-1);
		}
	}

	char executable[PATH_MAX+1];
	which(argv[0], executable, envp_get(envp, "PATH"));

	if (is_empty_string(executable)) {
		/* no such command found */
		/* TODO: handle error */
		exit(-1);
	}

	if (NULL != envp) {
		execve(executable, argv, *envp);
	} else {
		execv(executable, argv);
	}

	exit(-1);
}