micro-utils/src/loginutils/login/login.c

93 lines
1.9 KiB
C
Raw Normal View History

2024-01-13 22:18:21 +00:00
#include <pwd.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <unistd.h>
#include <signal.h>
#include "get_string.h"
#include "pw_check.h"
void login(const struct passwd *pw) {
char *shell = pw->pw_shell[0] == '\0' ? "/bin/sh" : pw->pw_shell;
setenv("HOME", pw->pw_dir, 1);
setenv("SHELL", shell, 1);
setenv("USER", pw->pw_name, 1);
setenv("LOGNAME", pw->pw_name, 1);
if (chdir(pw->pw_dir) < 0) {
fprintf(stderr, "login: %s\n", strerror(errno));
return;
}
execlp(shell, shell, "-l", NULL);
}
struct passwd *proccess_input(char *hostname) {
static char user[512];
static char psswd[512];
/* Username */
printf("Login on %s:\n", hostname);
2024-01-14 08:38:55 +00:00
if (!mu_get_string("login", user, sizeof(user)))
2024-01-13 22:18:21 +00:00
return NULL;
struct passwd *pw = getpwnam(user);
if (!pw) {
fprintf(stderr, "login: Incorrent username\n");
return NULL;
}
/* Password */
printf("\nPassword:\n");
2024-01-14 08:38:55 +00:00
if (!mu_get_string("login", psswd, sizeof(psswd)))
2024-01-13 22:18:21 +00:00
return NULL;
if (pw_check("login", pw, psswd)) {
memset(psswd, '\0', sizeof(psswd));
2024-01-14 08:38:55 +00:00
fprintf(stderr, "login: Incorrect password\n");
2024-01-13 22:18:21 +00:00
return NULL;
}
memset(psswd, '\0', sizeof(psswd));
return pw;
}
int main(void) {
if ((!isatty(STDIN_FILENO) || !isatty(STDOUT_FILENO))) {
fprintf(stderr, "login: no tty\n");
return 1;
}
/* For prompt */
char hostname[HOST_NAME_MAX + 1];
if (gethostname(hostname, sizeof(hostname)) < 0) {
fprintf(stderr, "login: %s\n", strerror(errno));
return 1;
}
signal(SIGQUIT, SIG_IGN);
signal(SIGINT, SIG_IGN);
signal(SIGHUP, SIG_IGN);
struct passwd *pw = proccess_input(hostname);
if (!pw)
return 1;
/* Start */
if (setgid(pw->pw_gid) < 0) {
fprintf(stderr, "login: %s\n", strerror(errno));
return 1;
}
if (setuid(pw->pw_uid) < 0) {
fprintf(stderr, "login: %s\n", strerror(errno));
return 1;
}
login(pw);
return 0;
}