-
Notifications
You must be signed in to change notification settings - Fork 0
/
path.c
121 lines (103 loc) · 2.83 KB
/
path.c
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
120
121
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "root.h"
#include "path.h"
#include "logging.h"
/*
* Return the full path to command found by searching for it in pathenv,
* and returning the first match.
*
* If command is found via a non-absolute path in PATH, return NULL.
* This is to prevent security issues arising from "" or "." in PATH.
*
* If the string returned is not NULL, it must be freed by the caller.
*/
char *get_command_path(const char *command, const char *pathenv)
{
size_t commandlen = strlen(command);
char *pathenvcopy = strdup(pathenv);
if (pathenvcopy == NULL) {
error("Cannot allocate memory to hold pathenv\n");
return NULL;
}
for (char *dir = strtok(pathenvcopy, PATHENVSEP);
dir != NULL;
dir = strtok(NULL, PATHENVSEP)) {
int dirlen = strlen(dir);
char *path = malloc(dirlen+1+commandlen+1);
if (path == NULL) {
error("Cannot allocate memory to hold path");
return NULL;
}
strcpy(path, dir);
/*debug("Looking in %s", path);*/
if (strcmp(path, "") != 0 && path[dirlen-1] != DIRSEP) {
char dirsepstr[2];
sprintf(dirsepstr, "%c", DIRSEP);
strcat(path, dirsepstr);
dirlen++;
}
strcat(path, command);
if (access(path, F_OK) == 0) {
/*debug("%s is %s", command, path);*/
free(pathenvcopy);
return path;
}
else {
free(path);
path = NULL;
}
}
debug("%s not found in PATH", command);
if (pathenvcopy != NULL) {
free(pathenvcopy);
}
return NULL;
}
/**
* Returns 0 (true) if path does not contain a slash.
*
* This is typically used to determine whether a command
* should be looked up in PATH or executed as-is.
*/
int is_unqualified_path(const char *path)
{
return !is_qualified_path(path);
}
/**
* Returns 0 (true) if path contains a slash.
*
* This is typically used to determine whether a command
* should be looked up in PATH or executed as-is.
*/
int is_qualified_path(const char *path)
{
return path && strchr(path, DIRSEP) != NULL;
}
/**
* Returns 0 (true) if path is an unambigious path starting at the root.
*/
int is_absolute_path(const char *path)
{
return path && path[0] == DIRSEP;
}
/**
* Perform an action on each element of PATH.
*/
void pathenv_each(const char *pathenv, void (*func)(const char *pathentry))
{
if (pathenv == NULL) {
error("pathenv_each: pathenv is NULL\n");
return;
}
char *pathenvcopy = strdup(pathenv);
for (char *dir = strtok(pathenvcopy, PATHENVSEP);
dir != NULL;
dir = strtok(NULL, PATHENVSEP)) {
(*func)(dir);
}
}
/* vim: set ts=4 sw=4 tw=0 et:*/