Removed popen, using execvp for shell like functions

This commit is contained in:
Chris Dorman 2022-05-18 11:44:42 -07:00
parent 5ffbec0ce0
commit c091373610
4 changed files with 65 additions and 28 deletions

View File

@ -23,6 +23,7 @@
#include "config.h"
#include "sbyteswap.h"
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/select.h>
// Networking
#include <sys/socket.h>

View File

@ -42,4 +42,5 @@ char *ss_time();
void gen_random_string(char *s, const int len);
char *remove_extension(char *string);
int check_for_var(char *string);
int ss_exec(char **argv);
char **line_to_args(char *line);
int ss_exec(char **args);

View File

@ -27,11 +27,13 @@ char *process_line (char *line)
//printf("%s", &line[strlen(line)-2]);
static char pathbuf[MAXPATHLENGTH+1];
// Needed for strncpy
static char line_save[MAXPATHLENGTH+1];
static char line_backup[MAXPATHLENGTH+1];
// save full line if popen is used, and no function is found
bzero(line_save, sizeof(line_save));
strcpy(line_save, line);
bzero(line_backup, sizeof(line_backup));
strcpy(line_backup, line);
char **func_args = line_to_args(line_backup);
// Check to see if we're dealing with a
// variable (for the end if the lexer)
@ -1484,24 +1486,13 @@ char *process_line (char *line)
}
else
{
FILE* p = popen(line_save, "r");
if(!p)
{
printf("ss:warn:command not found: %s\n", line_save);
}
else
{
char buff[1024];
while (fgets(buff, sizeof(buff), p)) {
printf("%s", buff);
}
}
// Make SS a shell as well :)
ss_exec(func_args);
pclose(p);
free(func_args);
}
}
return NULL;
}

View File

@ -160,18 +160,62 @@ int check_for_var(char *string)
}
}
// Execute - Run programs found within the *nix system
int ss_exec(char **argv)
char **line_to_args(char *line)
{
int exec_ret = execve(argv[0], (char **)argv, NULL);
int bufsize = MAXPATHLENGTH+1, position = 0;
char **tokens = calloc(bufsize, sizeof(char*));
char *token, **tokens_backup;
if ((exec_ret) == -1)
{
printf("ss:warn:failed to execute program [%d]", exec_ret);
return exec_ret;
if (!tokens) {
fprintf(stderr, "cdsh: allocation error\n");
exit(EXIT_FAILURE);
}
else
{
return exec_ret;
token = strtok(line, " ");
while (token != NULL) {
tokens[position] = strip_nl(token);
position++;
if (position >= bufsize) {
bufsize += MAXPATHLENGTH;
tokens_backup = tokens;
tokens = realloc(tokens, bufsize * sizeof(char*));
if (!tokens) {
free(tokens_backup);
fprintf(stderr, "cdsh: allocation error\n");
exit(EXIT_FAILURE);
}
}
token = strtok(NULL, " ");
}
tokens[position] = NULL;
return tokens;
}
int ss_exec(char **args)
{
pid_t pid;
int status;
pid = fork();
if (pid == 0) {
// Child process
if (execvp(args[0], args) == -1) {
printf("ss:warn:failed to create child process\n");
}
return 1;
} else if (pid < 0) {
// Error forking
perror("cdsh");
} else {
// Parent process
do {
waitpid(pid, &status, WUNTRACED);
} while (!WIFEXITED(status) && !WIFSIGNALED(status));
}
return 0;
}