summaryrefslogtreecommitdiff
path: root/src/rexec.c
blob: 56b0b4e33049ee269a757131f3943cba45c7a963 (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
#include "rexec.h"

#include "log.h"

#include "util/exec.h"

#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/wait.h>

int sk_rexec_command(
		const char *restrict target_host, char *restrict cmd,
		int stdin, int stdout, int stderr, envp_t *const extra_envp) {
	envp_t *envp = envp_dup();

	/* FIXME: set actual values */
	envp_set(envp, "__target_host", target_host, true);
	envp_set(envp, "__target_fqdn", target_host, true);
	envp_set(envp, "__target_hostname", target_host, true);

	if (NULL != envp) {
		envp_merge(envp, extra_envp);
	}

	/* TODO: use remote_exec instead of ssh */
	/* FIXME: Remove echo */
	pid_t pid = exec_subcmd(
		(char *const[]){"echo", "ssh", (char *)target_host, cmd},
		stdin, stdout, stderr, true, NULL, envp);

	int rv = -1;
	if (0 > pid) {
		/* command could not be launched */
		sk_error("failed to execute command (%s) on target: %s",
		         cmd, strerror(errno));
		goto ret;
	}

	int cmd_status = 0;
	while (0 >= waitpid(pid, &cmd_status, 0));
	if (WIFEXITED(cmd_status)) { rv = WEXITSTATUS(cmd_status); }

  ret:
	envp_free(envp);

	return rv;
}