/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* p_redirs.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: rbousset +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/02/14 17:19:27 by rbousset #+# #+# */ /* Updated: 2020/02/14 17:19:29 by rbousset ### ########lyon.fr */ /* */ /* ************************************************************************** */ #include #include #include #include #include #include "d_define.h" #include "s_lredir.h" #include "s_struct.h" #include "s_lredir.h" #include "u_utils.h" #include "u_parse.h" static void p_append_redir(const char path[], int32_t fd, int8_t redir, t_com *com) { struct s_lredir *new; new = s_lredir_new(path, fd, redir); if (new == NULL) { return ; } s_lredir_add_back(&com->rdr, new); } static size_t p_get_path(char path[], char *ptr, const char word[], int8_t redir) { size_t pos[2]; size_t end; pos[0] = 0; pos[1] = 0; redir = (redir < 0) ? (-redir) : (redir); ptr += redir; while (*ptr != C_NUL && ft_iswhitespace(*ptr) == TRUE) ptr++; pos[0] = (ptr - word); while (*ptr != C_NUL && ft_iswhitespace(*ptr) == FALSE && u_is_not_escaped(word, ptr) == TRUE) ptr++; pos[1] = (ptr - word); end = pos[1]; while (pos[1] - pos[0] > PATH_MAX) end--; ft_strlcpy(path, word + pos[0], end); return (pos[1]); } static int32_t p_get_fd(const char word[], char *ptr) { char digit[255]; char *tmp; if (*ptr == '<' || (ptr - word) == 1) return (0); tmp = ptr; tmp -= 1; if (ft_isdigit(*tmp) == FALSE) return (0); while ((tmp - word) > 0 && ft_isdigit(*tmp) == TRUE) tmp--; if ((tmp - word) > 0 && ft_iswhitespace(*tmp) == FALSE) return (0); else { tmp += ((tmp - word) > 0) ? (1) : (0); ft_strlcpy(digit, word + (tmp - word), (ptr - tmp) + 1); } return (ft_atoi(digit)); } static int8_t p_get_redir(char word[], char *ptr, t_com *com) { char path[PATH_MAX]; size_t pos[2]; int32_t fd; int8_t redir; pos[0] = 0; pos[1] = 0; if ((fd = p_get_fd(word, ptr)) <= 0) fd = STDOUT_FILENO; redir = (*ptr == '>') ? (1) : (-1); redir = (redir == 1 && *(ptr + 1) == '>') ? (2) : (redir); redir = (redir == -1 && *(ptr + 1) == '<') ? (-2) : (redir); if (fd == STDOUT_FILENO) pos[0] = (ptr - word); else pos[0] = (ptr - word) - ft_intlen(fd); pos[1] = p_get_path(path, ptr, word, redir); (void)ft_memmove(word + pos[0], word + pos[1], (ft_strlen(word + pos[1]) + 1) * sizeof(char)); p_append_redir(path, fd, redir, com); return (0); } int8_t p_redirs(char word[], t_com **com) { char *ptr; t_quote_mode mode; mode = Q_NONE; ptr = (char *)word; while (*ptr != C_NUL) { if (*ptr == C_DQUOTE) mode = u_meet_dquote(word, ptr, mode); else if (*ptr == C_SQUOTE) mode = u_meet_squote(word, ptr, mode); else if (mode == Q_NONE && (*ptr == '<' || *ptr == '>') == 1) { if (p_get_redir(word, ptr, *com) != 0) return (1); ptr = word; } ptr++; } return (0); }