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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
|
#include "pathexec.h"
#include <unistd.h>
#include "alloc.h"
#include "byte.h"
#include "env.h"
#include "error.h"
#include "str.h"
#include "stralloc.h"
/**
@file pathexec.c
@author djb
@source ucspi-tcp, ucspi-ssl
@brief populate environment after fork
*/
static stralloc plus;
static stralloc tmp;
int pathexec_env(const char *s, const char *t)
{
if (!s) return 1;
if (!stralloc_copys(&tmp, s)) return 0;
if (t) {
if (!stralloc_cats(&tmp, "=")) return 0;
if (!stralloc_cats(&tmp, t)) return 0;
}
if (!stralloc_0(&tmp)) return 0;
return stralloc_cat(&plus, &tmp);
}
int pathexec_multienv(stralloc *sa)
{
if (!sa) return 1;
return stralloc_cat(&plus, sa);
}
void pathexec(char *const *argv)
{
char **e;
unsigned int elen;
unsigned int i;
unsigned int j;
unsigned int split;
unsigned int t;
if (!stralloc_cats(&plus, "")) return;
elen = 0;
for (i = 0; environ[i]; ++i) ++elen;
for (i = 0; i < plus.len; ++i)
if (!plus.s[i]) ++elen;
e = (char **)alloc((elen + 1) * sizeof(char *));
if (!e) return;
elen = 0;
for (i = 0; environ[i]; ++i) e[elen++] = environ[i];
j = 0;
for (i = 0; i < plus.len; ++i)
if (!plus.s[i]) {
split = str_chr(plus.s + j, '=');
for (t = 0; t < elen; ++t)
if (byte_equal(plus.s + j, split, e[t]))
if (e[t][split] == '=') {
--elen;
e[t] = e[elen];
break;
}
if (plus.s[j + split]) e[elen++] = plus.s + j;
j = i + 1;
}
e[elen] = 0;
pathexec_run(*argv, argv, e);
alloc_free(e);
}
void pathexec_run(const char *file, char *const *argv, char *const *envp)
{
char *path;
unsigned int split;
int savederrno;
if (file[str_chr(file, '/')]) {
execve(file, argv, envp);
return;
}
path = env_get("PATH");
if (!path) path = "/bin:/usr/bin";
savederrno = 0;
for (;;) {
split = str_chr(path, ':');
if (!stralloc_copyb(&tmp, path, split)) return;
if (!split)
if (!stralloc_cats(&tmp, ".")) return;
if (!stralloc_cats(&tmp, "/")) return;
if (!stralloc_cats(&tmp, file)) return;
if (!stralloc_0(&tmp)) return;
execve(tmp.s, argv, envp);
if (errno != ENOENT) {
savederrno = errno;
if ((errno != EACCES) && (errno != EPERM) && (errno != EISDIR)) return;
}
if (!path[split]) {
if (savederrno) errno = savederrno;
return;
}
path += split;
path += 1;
}
}
|