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


int
libexec_unsetenv_last(struct libexec_command *cmd, const char *name)
{
	char **env;
	size_t i, n, len;

	if (!cmd || !name) {
		errno = EINVAL;
		return -1;
	}

	if (strchr(name, '='))
		return 0;

	env = cmd->environ ? cmd->environ : environ;
	len = strlen(name);

	n = 0;
	while (env[n])
		n++;

	for (i = n; i--;)
		if (!strncmp(env[i], name, len) && env[i][len] == '=')
			goto found;

	return 0;

found:
	if (!cmd->environ)
		if (libexec_copy_environ(cmd, NULL))
			return -1;
	free(cmd->environ[i]);
	memmove(&cmd->environ[i], &cmd->environ[i + 1], (n - i - 1) * sizeof(*cmd->environ));

	return 0;
}


#else
LIBEXEC_CONST__ int main(void) {return 0;} /* TODO test */
#endif