From 98b59da9adff0580df5325a931585e9eea71d588 Mon Sep 17 00:00:00 2001 From: Mark Spencer Date: Sun, 21 Mar 2004 18:15:37 +0000 Subject: Create ast_safe_system which closes off file descriptors before spawning system() and so on. git-svn-id: https://origsvn.digium.com/svn/asterisk/trunk@2514 65c4cc65-6c06-0410-ace0-fbb531ad65f3 --- asterisk.c | 45 +++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 41 insertions(+), 4 deletions(-) (limited to 'asterisk.c') diff --git a/asterisk.c b/asterisk.c index 2811a7cad..5e1d81215 100755 --- a/asterisk.c +++ b/asterisk.c @@ -28,6 +28,7 @@ #include #include #include +#include #include #include #include @@ -153,6 +154,42 @@ static int fdprint(int fd, const char *s) return write(fd, s, strlen(s) + 1); } +int ast_safe_system(const char *s) +{ + /* XXX This function needs some optimization work XXX */ + pid_t pid; + int x; + int res; + struct rusage rusage; + int status; + pid = fork(); + if (pid == 0) { + /* Close file descriptors and launch system command */ + for (x=STDERR_FILENO + 1; x<4096;x++) { + close(x); + } + res = system(s); + exit(res); + } else if (pid > 0) { + for(;;) { + res = wait4(pid, &status, 0, &rusage); + if (res > -1) { + if (WIFEXITED(status)) + res = WEXITSTATUS(status); + else + res = -1; + } else { + if (errno != EINTR) + break; + } + } + } else { + ast_log(LOG_WARNING, "Fork failed: %s\n", strerror(errno)); + res = -1; + } + return res; +} + /* * write the string to all attached console clients */ @@ -607,9 +644,9 @@ static void consolehandler(char *s) /* The real handler for bang */ if (s[0] == '!') { if (s[1]) - system(s+1); + ast_safe_system(s+1); else - system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh"); + ast_safe_system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh"); } else ast_cli_command(STDOUT_FILENO, s); } else @@ -627,9 +664,9 @@ static int remoteconsolehandler(char *s) /* The real handler for bang */ if (s[0] == '!') { if (s[1]) - system(s+1); + ast_safe_system(s+1); else - system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh"); + ast_safe_system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh"); ret = 1; } if ((strncasecmp(s, "quit", 4) == 0 || strncasecmp(s, "exit", 4) == 0) && -- cgit v1.2.3