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
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* e_externs_next.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rbousset <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/02/14 17:19:27 by rbousset #+# #+# */
/* Updated: 2020/02/14 17:19:29 by rbousset ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include <libft.h>
#include <dirent.h>
#include <stdlib.h>
#include <stddef.h>
#include "f_fail.h"
#include "s_destroy.h"
#include "s_line.h"
#include "s_struct.h"
#include "u_utils.h"
static char
*get_fullpath(const char p_path[],
const char d_name[],
t_msh *msh)
{
char *fullpath;
const size_t path_len = ft_strlen(p_path);
const size_t name_len = ft_strlen(d_name);
if (!(fullpath = (char*)malloc((path_len + name_len + 2) * sizeof(char))))
{
f_alloc_and_destroy_msh(msh);
}
(void)ft_memcpy(fullpath, p_path, path_len);
*(fullpath + (path_len)) = '/';
(void)ft_memcpy(fullpath + path_len + 1, d_name, name_len);
*(fullpath + (path_len + name_len + 1)) = '\0';
return (fullpath);
}
char
*search_in_path(const char com[],
char *envpath[],
t_msh *msh)
{
struct dirent *ent;
char **p_path;
char *fullpath;
DIR *dir;
p_path = envpath;
while (*p_path)
{
if ((dir = opendir(*p_path)) != NULL)
{
while ((ent = readdir(dir)) != NULL)
{
/* TODO: check for not bins (dirs, etc) */
if (ft_strncmp(com, ent->d_name, ft_strlen(com) + 1) == 0)
{
fullpath = get_fullpath(*p_path, ent->d_name, msh);
closedir(dir);
return (fullpath);
}
}
closedir(dir);
}
p_path++;
}
return (NULL);
}
char
**get_env_path(t_msh *msh)
{
size_t i;
char **env_dup;
char **envpath;
char *envline;
env_dup = u_get_env_var_names(msh);
i = 0;
while (env_dup[i] && ft_strncmp("PATH", env_dup[i], 5) != 0)
i++;
if (env_dup[i] == NULL)
return (NULL);
ft_delwords(env_dup);
envline = ft_strchr(msh->envp[i], '=');
envline += 1;
if (*envline != '\0')
{
if ((envpath = ft_split(envline, ':')) == NULL)
{
f_alloc_and_destroy_msh(msh);
}
return (envpath);
}
return (NULL);
}
|