Repository navigation
Expand file tree
/
Copy pathpath_utils.c
More file actions
104 lines (85 loc) · 1.89 KB
/
Copy pathpath_utils.c
File metadata and controls
104 lines (85 loc) · 1.89 KB
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
#include "shell.h"
/**
* resolve_slash_cmd - resolves a command containing '/'.
* @cmd: command path to check
*
* Return: malloc'd copy of cmd if executable, or NULL on failure.
* If cmd exists but is not executable, sets errno to EACCES.
*/
char *resolve_slash_cmd(char *cmd)
{
struct stat st;
if (cmd == NULL || cmd[0] == '\0')
{
errno = ENOENT;
return (NULL);
}
if (stat(cmd, &st) == -1)
return (NULL);
if (S_ISDIR(st.st_mode))
{
errno = EACCES;
return (NULL);
}
if (access(cmd, X_OK) == 0)
return (strdup(cmd));
if (access(cmd, F_OK) == 0)
errno = EACCES;
return (NULL);
}
/**
* build_full_path - build "dir/cmd"
* @dir: directory
* @cmd: command
*
* Return: malloc'd full path, or NULL
*/
char *build_full_path(char *dir, char *cmd)
{
size_t len;
char *full_path;
if (dir == NULL || cmd == NULL)
return (NULL);
len = strlen(dir) + 1 + strlen(cmd) + 1;
full_path = malloc(len);
if (full_path == NULL)
return (NULL);
sprintf(full_path, "%s/%s", dir, cmd);
return (full_path);
}
/**
* search_in_path - searches PATH directories for an executable command.
* @cmd: command name to find
* @path_value: PATH value (colon-separated directories)
*
* Return: malloc'd full path if found and executable, or NULL.
* If at least one match exists but is not executable, sets errno to EACCES.
*/
char *search_in_path(char *cmd, char *path_value)
{
char *path_copy, *dir, *full_path;
int perm_denied = 0;
path_copy = strdup(path_value);
if (path_copy == NULL)
return (NULL);
dir = strtok(path_copy, ":");
while (dir != NULL)
{
full_path = build_full_path(dir, cmd);
if (full_path == NULL)
break;
if (access(full_path, X_OK) == 0)
{
free(path_copy);
return (full_path);
}
if (access(full_path, F_OK) == 0)
perm_denied = 1;
free(full_path);
dir = strtok(NULL, ":");
}
free(path_copy);
if (perm_denied)
errno = EACCES;
return (NULL);
}