Browse Source

[fix] redirections: prenvent segfault by checking there is char before and after chevrons. Add corresponding unit tests.

Moul 4 years ago
parent
commit
d08c535926
3 changed files with 48 additions and 6 deletions
  1. 28 6
      src/redirect.c
  2. 1 0
      src/sh.h
  3. 19 0
      tests.sh

+ 28 - 6
src/redirect.c

@@ -1,12 +1,14 @@
 #include "sh.h"
 
 /*
-** Parse redirections: split in three parts:
-** Get position of the first chevron
-** Before chevron, chevron, after chevron
-** Check if fd is specified
-** Check if there is two chevrons
-** Split with strsub then trim
+** If a chevron is present:
+**  Prevent segfault by checking there is something before and after chevron
+**  Parse redirections: split in three parts:
+**  Get position of the first chevron
+**  Before chevron, chevron, after chevron
+**  Check if fd is specified
+**  Check if there is two chevrons
+**  Split with strsub then trim
 ** Else: launch pipe without redirections
 */
 
@@ -21,6 +23,11 @@ void	parse_redirection(char *str)
 	if ((chev = ft_strchr(str, '<')) != NULL || \
 			(chev = ft_strchr(str, '>')) != NULL)
 	{
+		if (check_before_after_chevron(chev) == 1)
+		{
+			error_message("", "", "nothing specified before or after chevron");
+			return ;
+		}
 		fd = chev[-1] == '1' || chev[-1] == '2' ? 1 : 0;
 		len = chev[0] == chev[1] ? 2 : 1;
 		pos = ft_strlen(str) - ft_strlen(chev);
@@ -33,6 +40,21 @@ void	parse_redirection(char *str)
 		launch_pipe(str);
 }
 
+/*
+** Check if there is visible char before and after chevrons
+*/
+
+int		check_before_after_chevron(char *chev)
+{
+	if ((chev[-1] == ' ' && ft_isvisible(chev[-2]) == 0) || \
+		(chev[1] == ' ' && ft_isvisible(chev[2]) == 0) || \
+		ft_isprint(chev[-1]) == 0 || \
+		(ft_isprint(chev[1]) == 0 && chev[1] != '>' && chev[1] != '<') || \
+		((chev[1] == '>' || chev[1] == '<') && ft_isprint(chev[2]) == 0))
+		return (1);
+	return (0);
+}
+
 /*
 ** if <: open file and dup it in STDIN, save stdfd
 ** elif <<: run bottow function

+ 1 - 0
src/sh.h

@@ -29,6 +29,7 @@ void		comma_split(char *cmd);
 ** redirect.c
 */
 void		parse_redirection(char *str);
+int			check_before_after_chevron(char *chev);
 void		redirections(char *cmd, char *operator, char *file);
 void		right_redirections(int *fd, char *operator, char *file);
 void		prompt_redirection(char *cmd, char *file);

+ 19 - 0
tests.sh

@@ -75,6 +75,25 @@ tests=(
 #"cat << fin\nnrstai\nfin\n" # double gauche
 #"cat << toto\nnrstai\nrsnati\nairnst\ntoto" # double gauche avec autre string de fin
 
+## Segfault on redirections
+">"
+"ls>"
+"ls >"
+#"> toto", ">toto", ">> toto", ">>toto" # are not working
+">>"
+"ls>>"
+"ls >>"
+"<"
+"cat<"
+"cat <"
+"< toto"
+"<toto"
+"<<"
+"cat<<"
+"cat <<"
+"<<end"
+"<< end"
+
 ## Mix
 "rm $tmpf ; ls ; pwd; ls -a | cat -e | wc > $tmpf ; cat $tmpf ; rm $tmpf" # point-virgules, pipes et redirection
 "ls -a | cat -e | wc >> $tmpf ; cat $tmpf ; rm $tmpf" # pipes et double redirection