/*-
 * This program illustrates how to access the password database.
 * For each user name given as an argument, it extracts the password
 * and shadow file information then validates passwords for users
 * which have them.
 * Normally, the file "/etc/shadow" it only readable by "root", so 
 * this program should be owned by root and set-uid to execute properly
 */

#include <libc.h>
#include <pwd.h>
#include <shadow.h>

extern char    *crypt(char *pass, char *salt);
extern char    *getpass(const char *prompt);

main(int argc, char **argv)
{
	char *user;
	if (argc == 1) {
		printf("usage: %s user-name [user-name...]\n", *argv);
		return 1;
	}
	while (user = *++argv) {
		struct passwd        *pw;
		if ((pw = getpwnam(user)) == 0) {
			printf("no user '%s'\n", user);
			continue;
		}
		if (pw->pw_passwd && *pw->pw_passwd) {
			struct spwd    *sp;
			char           *pass;
			char            pwbuf[33];

			if ((sp = getspnam(user)) == 0) {
				printf("inconsistent password database!\n");
			} else {
				printf("user %s\n", user);
				if (pass = getpass("Passwd:")) {
					strcpy(pwbuf, crypt(pass, sp->sp_pwdp));
					if (strcmp(pwbuf, sp->sp_pwdp)) {
						printf("Sorry!\n");
					} else {
						printf("Ok!\n");
					}
				} else {
					printf("no password entered\n");
				}
			}
		} else {
			printf("user %s does not have a password!\n", user);
		}
	}
	return 0;
}
