-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinput_validation.c
114 lines (105 loc) · 2.57 KB
/
input_validation.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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* input_validation.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: emansoor <emansoor@student.hive.fi> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/04/23 10:30:06 by emansoor #+# #+# */
/* Updated: 2024/05/05 13:56:54 by emansoor ### ########.fr */
/* */
/* ************************************************************************** */
#include "pipex.h"
/*
constructs a full path
*/
char *full_path(char *path, char *command)
{
char *temp;
char *full_path;
temp = ft_strjoin(path, "/");
if (!temp)
return (NULL);
full_path = ft_strjoin(temp, command);
if (!path)
{
free(temp);
return (NULL);
}
free(temp);
return (full_path);
}
/*
checks whether the calling process can access path for a given command;
returns index for accessible path in paths, -1 if path not found,
-2 if given command is an absolute path
*/
static int validate_command(char *command, char **paths)
{
char *path;
int index;
if (access(command, F_OK) == 0)
return (-2);
index = 0;
while (paths[index])
{
path = full_path(paths[index], command);
if (!path)
break ;
if (access(path, F_OK) == 0)
{
free(path);
return (index);
}
free(path);
index++;
}
return (-1);
}
/*
initializes and adds a new node to the command list
*/
static int build_command_list(t_cmds **cmds, char **cmd,
char **paths, int pindex)
{
t_cmds *new;
t_cmds *last;
int index;
new = ft_lstnew_pipex(cmd, paths, pindex);
if (!new)
return (1);
ft_lstadd_back_pipex(cmds, new);
last = ft_lstlast_pipex(*cmds);
index = ft_lstsize_pipex(*cmds);
last->id = index - 1;
return (0);
}
/*
builds a linked list of valid commands
*/
int collect_commands(int argc, char **argv, t_cmds **cmds, char **paths)
{
int index;
int path;
char **cmd;
index = 2;
while (index < argc - 1)
{
cmd = ft_split(argv[index], ' ');
if (substrlen(cmd) == 0)
{
perror(NULL);
free(cmd);
return (1);
}
path = validate_command(cmd[0], paths);
if (build_command_list(cmds, cmd, paths, path) == 0)
index++;
else
{
free_array(cmd);
return (1);
}
}
return (0);
}