Luna/apps/sh.cpp

117 lines
2.4 KiB
C++
Raw Normal View History

2023-03-29 15:56:56 +00:00
#include <luna/Vector.h>
2023-03-23 21:19:54 +00:00
#include <errno.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
2023-03-23 21:42:24 +00:00
#include <sys/wait.h>
2023-03-23 21:19:54 +00:00
#include <unistd.h>
2023-03-29 15:56:56 +00:00
static Result<Vector<char*>> split_command_into_argv(const char* cmd)
2023-03-23 21:19:54 +00:00
{
char* str = strdup(cmd);
2023-03-29 15:56:56 +00:00
Vector<char*> result;
2023-03-23 21:19:54 +00:00
char* segment = strtok(str, " \n");
2023-03-29 15:56:56 +00:00
TRY(result.try_append(segment));
2023-03-23 21:19:54 +00:00
2023-03-29 15:56:56 +00:00
if (segment == NULL) return result;
2023-03-23 21:19:54 +00:00
for (;;)
{
char* segment = strtok(NULL, " \n");
2023-03-29 15:56:56 +00:00
TRY(result.try_append(segment));
2023-03-23 21:19:54 +00:00
2023-03-29 15:56:56 +00:00
if (segment == NULL) return result;
2023-03-23 21:19:54 +00:00
}
2023-03-29 15:56:56 +00:00
return result;
2023-03-23 21:19:54 +00:00
}
static char* join_path(const char* str1, const char* str2)
{
2023-03-29 15:56:56 +00:00
char* buf = (char*)malloc(strlen(str1) + strlen(str2) + 1);
2023-03-23 21:19:54 +00:00
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;
2023-03-23 21:19:54 +00:00
2023-03-24 19:53:53 +00:00
if (strspn(command, " \n") == strlen(command)) continue;
2023-03-23 21:19:54 +00:00
pid_t child = fork();
if (child < 0)
{
perror("fork");
return 1;
}
2023-03-23 21:19:54 +00:00
if (child == 0)
{
Vector<char*> argv;
bool ok = split_command_into_argv(command).try_set_value_or_error(argv, errno);
if (!ok)
2023-03-29 15:56:56 +00:00
{
perror("failed to parse command");
return 1;
}
if (argv[0] == NULL) return 0;
2023-03-29 15:56:56 +00:00
sh_execvp(argv.data());
2023-03-23 21:19:54 +00:00
perror(argv[0]);
return 1;
}
if (waitpid(child, NULL, 0) < 0)
{
perror("waitpid");
return 1;
}
2023-03-23 21:19:54 +00:00
}
}