Luna/apps/sh.cpp

120 lines
2.5 KiB
C++

#include <luna/StringBuilder.h>
#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 (;;)
{
segment = strtok(NULL, " \n");
TRY(result.try_append(segment));
if (segment == NULL) return result;
}
return result;
}
static Result<String> join_path(const char* str1, const char* str2)
{
StringBuilder sb;
TRY(sb.add(StringView { str1 }));
TRY(sb.add(StringView { str2 }));
return sb.string();
}
static int execute_in_path(const char* dir, char** argv)
{
String path;
bool ok = join_path(dir, argv[0]).try_move_value_or_error(path, errno);
if (!ok) return -1;
int err = errno;
int status = execv(path.chars(), argv);
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)
{
Vector<char*> argv;
bool ok = split_command_into_argv(command).try_move_value_or_error(argv, errno);
if (!ok)
{
perror("failed to parse command");
return 1;
}
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;
}
}
}