From 4267fdfa26ae8461f033d5a3d6ac73544229ae82 Mon Sep 17 00:00:00 2001 From: Johannes Findeisen Date: Sat, 10 Aug 2024 15:48:50 +0200 Subject: [PATCH] Added help command (-h) and fixed some things... --- checkpw.c | 29 ++++++++++++++++++++--------- 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/checkpw.c b/checkpw.c index 508ee4a..dfcbb7e 100644 --- a/checkpw.c +++ b/checkpw.c @@ -1,8 +1,15 @@ -/* +/** * checkpw is a program that checks the validity of a users password on a * Linux/PAM-based system. * - * Usage: checkpw -u $USER -p $PASSWORD + * Usage: ./checkpw [-u ] [-p ] [-i] [-v] [-h] + * + * Options: + * -u Specify username. + * -p Specify password. + * -i Enable interactive mode to prompt for missing username/password. + * -v Enable verbose mode. + * -h Show this help * * Returns 0 on success, 1 otherwise. * @@ -18,7 +25,7 @@ #include // For struct passwd and getpwnam #include // For terminal input settings -#define MAX_USERNAME_LEN 256 +#define MAX_USERNAME_LEN 32 #define MAX_PASSWORD_LEN 256 #ifndef MIN_UID @@ -154,12 +161,13 @@ void prompt_for_input(char *buffer, size_t size, const char *prompt, int hide_in } void print_usage(const char *prog_name) { - fprintf(stderr, "Usage: %s [-u ] [-p ] [-i] [-v]\n", prog_name); + fprintf(stderr, "Usage: %s [-u ] [-p ] [-i] [-v] [-h]\n", prog_name); fprintf(stderr, "Options:\n"); fprintf(stderr, " -u Specify username.\n"); fprintf(stderr, " -p Specify password.\n"); fprintf(stderr, " -i Enable interactive mode to prompt for missing username/password.\n"); fprintf(stderr, " -v Enable verbose mode.\n"); + fprintf(stderr, " -h Show this help.\n"); } int main(int argc, char *argv[]) { @@ -170,22 +178,25 @@ int main(int argc, char *argv[]) { int opt; // Parse command-line arguments - while ((opt = getopt(argc, argv, "u:p:iv")) != -1) { + while ((opt = getopt(argc, argv, "u:p:hiv")) != -1) { switch (opt) { case 'u': if (strlen(optarg) >= MAX_USERNAME_LEN) { - fprintf(stderr, "Error: Username is too long (maximum %d characters).\n", MAX_USERNAME_LEN - 1); + fprintf(stderr, "Error: Username is too long (maximum %d characters).\n", MAX_USERNAME_LEN); exit(1); } strncpy(username, optarg, MAX_USERNAME_LEN - 1); break; case 'p': if (strlen(optarg) >= MAX_PASSWORD_LEN) { - fprintf(stderr, "Error: Password is too long (maximum %d characters).\n", MAX_PASSWORD_LEN - 1); + fprintf(stderr, "Error: Password is too long (maximum %d characters).\n", MAX_PASSWORD_LEN); exit(1); } strncpy(password, optarg, MAX_PASSWORD_LEN - 1); break; + case 'h': + print_usage(argv[0]); + exit(1); case 'i': interactive = 1; // Enable interactive mode break; @@ -244,10 +255,10 @@ int main(int argc, char *argv[]) { // Authenticate the user if (authenticate(username, password, verbose) == 0) { printf("Authenticated successfully.\n"); - return 0; + exit(0); } else { printf("Authentication failed.\n"); - return 1; + exit(1); } }