Luna/apps/sh.cpp
apio 724dab636c
All checks were successful
continuous-integration/drone/push Build is passing
apps: Switch to C++
2023-03-29 17:56:56 +02:00

119 lines
2.5 KiB
C++

#include <luna/Vector.h>
#include <errno.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
static Result<Vector<char*>> split_command_into_argv(const char* cmd)
{
char* str = strdup(cmd);
Vector<char*> result;
char* segment = strtok(str, " \n");
TRY(result.try_append(segment));
if (segment == NULL) return result;
for (;;)
{
char* segment = strtok(NULL, " \n");
TRY(result.try_append(segment));
if (segment == NULL) return result;
}
return result;
}
static char* join_path(const char* str1, const char* str2)
{
char* buf = (char*)malloc(strlen(str1) + strlen(str2) + 1);
strlcpy(buf, str1, strlen(str1) + 1);
strncat(buf, str2, strlen(str2));
return buf;
}
static int execute_in_path(const char* dir, char** argv)
{
char* path = join_path(dir, argv[0]);
int err = errno;
int status = execv(path, argv);
free(path);
if (errno == ENOENT)
{
errno = err;
return 0;
}
return status;
}
static int sh_execvp(char** argv)
{
if (strchr(argv[0], '/'))
{
// Relative paths do not need path resolution.
return execv(argv[0], argv);
}
if (execute_in_path("/bin/", argv) != 0) return -1;
if (execute_in_path("/sbin/", argv) != 0) return -1;
if (execute_in_path("/usr/bin/", argv) != 0) return -1;
if (execute_in_path("/usr/local/bin/", argv) != 0) return -1;
errno = ENOENT;
return -1;
}
int main()
{
while (1)
{
fputs("sh$ ", stdout);
char command[4096];
char* rc = fgets(command, sizeof(command), stdin);
if (!rc) return 0;
if (strspn(command, " \n") == strlen(command)) continue;
pid_t child = fork();
if (child < 0)
{
perror("fork");
return 1;
}
if (child == 0)
{
auto maybe_argv = split_command_into_argv(command);
if (maybe_argv.has_error())
{
errno = maybe_argv.error();
perror("failed to parse command");
return 1;
}
auto argv = maybe_argv.release_value();
if (argv[0] == NULL) return 0;
sh_execvp(argv.data());
perror(argv[0]);
return 1;
}
if (waitpid(child, NULL, 0) < 0)
{
perror("waitpid");
return 1;
}
}
}