summaryrefslogtreecommitdiff
path: root/lib/shell.c
blob: 9a38b40d27c77657557ec9320e869d730048dc42 (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
#include "lslib.h"

#include <stdlib.h>
#include <string.h>
#include <unistd.h>

void setup_environment(const char *shell, bool new_env, bool clear_env, const struct passwd *pw) {
	if (!shell || !shell[0])
		shell = DEFAULT_SHELL;
    
    if (clear_env) {
        const char* term;
		term = getenv("TERM");
		clearenv();
		if (term)
			xsetenv("TERM", term);
		xsetenv("PATH", DEFAULT_PATH);
    }

    if (new_env) {
	    xsetenv("USER",    pw->pw_name);
	    xsetenv("LOGNAME", pw->pw_name);
	    xsetenv("HOME",    pw->pw_dir);
	    xsetenv("SHELL",   shell);
    }
}

void exec_shell(const char *shell, bool loginshell, const char **additional_args) {

    const char** args;

	args = additional_args;
	while (args && *args)
		args++;

	args = xzalloc(sizeof(args[0]) * (2 + (args - additional_args)));
	
    if (!shell || !shell[0])
		shell = DEFAULT_SHELL;

    args[0] = get_last_component(shell);    
    
    if (loginshell) {
        size_t len = strlen(shell) + 2;
        char* arg = xalloc(len);
        arg[0] = '-';
        memcpy(&arg[1], shell, len - 1);
        args[0] = arg;
    }

    if (additional_args) {
        int count = 0;
        while (*additional_args)
            args[++count] = *additional_args++;
    }

    execv(shell, (char**) args);
    error("cannot execute '%s'", shell);
}