2023-06-11 21:01:02 +03:00
|
|
|
#include <BAN/String.h>
|
|
|
|
#include <BAN/Optional.h>
|
|
|
|
#include <BAN/Vector.h>
|
|
|
|
|
|
|
|
#include <ctype.h>
|
|
|
|
#include <fcntl.h>
|
2023-07-13 12:01:41 +03:00
|
|
|
#include <pwd.h>
|
2023-06-11 21:01:02 +03:00
|
|
|
#include <stdio.h>
|
|
|
|
#include <stdlib.h>
|
|
|
|
#include <string.h>
|
|
|
|
|
|
|
|
void initialize_stdio()
|
|
|
|
{
|
|
|
|
char tty[L_ctermid];
|
|
|
|
ctermid(tty);
|
|
|
|
if (open(tty, O_RDONLY) != 0) _exit(1);
|
|
|
|
if (open(tty, O_WRONLY) != 1) _exit(1);
|
|
|
|
if (open(tty, O_WRONLY) != 2) _exit(1);
|
|
|
|
}
|
|
|
|
|
|
|
|
int main()
|
|
|
|
{
|
|
|
|
initialize_stdio();
|
|
|
|
|
2023-06-12 00:46:07 +03:00
|
|
|
bool first = true;
|
|
|
|
|
2023-06-11 21:01:02 +03:00
|
|
|
while (true)
|
|
|
|
{
|
|
|
|
char name_buffer[128];
|
2023-06-12 00:46:07 +03:00
|
|
|
|
2023-07-13 12:01:41 +03:00
|
|
|
while (!first)
|
2023-06-11 21:01:02 +03:00
|
|
|
{
|
|
|
|
printf("username: ");
|
|
|
|
fflush(stdout);
|
|
|
|
|
|
|
|
size_t nread = fread(name_buffer, 1, sizeof(name_buffer) - 1, stdin);
|
|
|
|
if (nread == 0)
|
|
|
|
{
|
|
|
|
if (ferror(stdin))
|
|
|
|
{
|
|
|
|
fprintf(stderr, "Could not read from stdin\n");
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
continue;
|
|
|
|
}
|
2023-07-13 12:01:41 +03:00
|
|
|
if (nread <= 1 || name_buffer[nread - 1] != '\n')
|
|
|
|
continue;
|
|
|
|
name_buffer[nread - 1] = '\0';
|
2023-06-11 21:01:02 +03:00
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
2023-07-13 12:01:41 +03:00
|
|
|
if (first)
|
2023-06-11 21:01:02 +03:00
|
|
|
{
|
2023-07-13 12:01:41 +03:00
|
|
|
strcpy(name_buffer, "user");
|
|
|
|
first = false;
|
|
|
|
}
|
2023-06-11 21:01:02 +03:00
|
|
|
|
2023-07-13 12:01:41 +03:00
|
|
|
auto* pwd = getpwnam(name_buffer);
|
|
|
|
if (pwd == nullptr)
|
|
|
|
continue;
|
2023-06-11 22:32:51 +03:00
|
|
|
|
2023-07-13 12:01:41 +03:00
|
|
|
pid_t pid = fork();
|
|
|
|
if (pid == 0)
|
|
|
|
{
|
|
|
|
printf("Welcome back %s!\n", pwd->pw_name);
|
2023-06-12 01:26:10 +03:00
|
|
|
|
2023-07-13 12:01:41 +03:00
|
|
|
if (setgid(pwd->pw_gid) == -1)
|
|
|
|
perror("setgid");
|
|
|
|
if (setuid(pwd->pw_uid) == -1)
|
|
|
|
perror("setuid");
|
2023-06-11 21:01:02 +03:00
|
|
|
|
2023-07-13 12:01:41 +03:00
|
|
|
setenv("HOME", pwd->pw_dir, 1);
|
|
|
|
chdir(pwd->pw_dir);
|
|
|
|
|
|
|
|
execl(pwd->pw_shell, pwd->pw_shell, nullptr);
|
|
|
|
perror("execl");
|
|
|
|
|
|
|
|
exit(1);
|
|
|
|
}
|
|
|
|
|
|
|
|
endpwent();
|
|
|
|
|
|
|
|
if (pid == -1)
|
|
|
|
{
|
|
|
|
perror("fork");
|
|
|
|
break;
|
2023-06-11 21:01:02 +03:00
|
|
|
}
|
2023-07-13 12:01:41 +03:00
|
|
|
|
|
|
|
int status;
|
|
|
|
waitpid(pid, &status, 0);
|
2023-06-11 21:01:02 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
}
|