aboutsummaryrefslogtreecommitdiffstats
path: root/libexec_setenv.c
blob: 9d0dc772eeb99254a8a0b7754e23443768d7bf6b (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
/* See LICENSE file for copyright and license details. */
#include "common.h"
#ifndef TEST


int
libexec_setenv(struct libexec_command *cmd, enum libexec_insert_mode how, const char *name, const char *value)
{
	int ret;
	char *buf;
	if (!name || !value || strchr(name, '=')) {
		errno = EINVAL;
		return -1;
	}
	buf = malloc(strlen(name) + strlen(value) + 2);
	stpcpy(stpcpy(stpcpy(buf, name), "="), value);
	ret = libexec_putenv(cmd, how, buf);
	free(buf);
	return ret;
}


#else


int
main(void)
{
	 /* Correct usage is tested via
	  * libexec_setenv_append.c,
	  * libexec_setenv_noclobber.c,
	  * libexec_setenv_noreplace.c,
	  * libexec_setenv_prepend.c, and
	  * libexec_setenv_replace.c */

	struct libexec_command cmd, ref;
	int i;

	cmd = LIBEXEC_COMMAND_INIT;
	memcpy(&ref, &cmd, sizeof(cmd));

	errno = 0;
	ASSERT_EQ_INT(libexec_setenv(&cmd, (enum libexec_insert_mode)-1, "A", "B"), -1);
	ASSERT_EQ_INT(errno, EINVAL);
	ASSERT_IS_TRUE(!memcmp(&cmd, &ref, sizeof(cmd)));

	errno = 0;
	ASSERT_EQ_INT(libexec_setenv(&cmd, (enum libexec_insert_mode)LIBEXEC_INSERT_MODE__COUNT__, "A", "B"), -1);
	ASSERT_EQ_INT(errno, EINVAL);
	ASSERT_IS_TRUE(!memcmp(&cmd, &ref, sizeof(cmd)));

	for (i = 0; i < LIBEXEC_INSERT_MODE__COUNT__; i++) {
		errno = 0;
		ASSERT_EQ_INT(libexec_setenv(&cmd, (enum libexec_insert_mode)i, "A=B", "C"), -1);
		ASSERT_EQ_INT(errno, EINVAL);
		ASSERT_IS_TRUE(!memcmp(&cmd, &ref, sizeof(cmd)));

		errno = 0;
		ASSERT_EQ_INT(libexec_setenv(&cmd, (enum libexec_insert_mode)i, "A", NULL), -1);
		ASSERT_EQ_INT(errno, EINVAL);
		ASSERT_IS_TRUE(!memcmp(&cmd, &ref, sizeof(cmd)));

		errno = 0;
		ASSERT_EQ_INT(libexec_setenv(&cmd, (enum libexec_insert_mode)i, NULL, "B"), -1);
		ASSERT_EQ_INT(errno, EINVAL);
		ASSERT_IS_TRUE(!memcmp(&cmd, &ref, sizeof(cmd)));
	}

	return 0;
}


#endif