/**********************************************************************
 * Copyright (c) 2006, 2009 IBM Corporation and others.
 * All rights reserved.   This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * $Id: ChkPass.c,v 1.6 2009/08/26 14:59:59 jwest Exp $
 *
 * Contributors:
 * IBM - Initial API and implementation
 **********************************************************************/

#include <stdio.h>

#if defined(__linux__) || defined(__sparc)
	#include <stdlib.h>
	#include <pwd.h>
	#include <shadow.h>
	#include <string.h>
	#include <crypt.h>
#elif defined(_AIX) || defined(__hpux)
	#include <stdlib.h>
	#include <pwd.h>
	#include <crypt.h>
	#include <unistd.h>
	#include <string.h>
#elif defined(MVS)
        #include <pwd.h>
#elif defined(__APPLE__)
	#include <stdlib.h>
	#include <pwd.h>
	#include <unistd.h>
	#include <string.h>
#endif

#define RC_SUCCESS	100 /* Authentication succeeded */
#define RC_FAILURE	101 /* Authentication failed */
#define RC_ARG		103 /* Too few arguments */

int verifyPassword(char *userid, char *password);

int main(int argc, char *argv[]) {
	char *userid;
	char *password;
	int rc;

	if(argc < 3) {
		userid = (char*)malloc(sizeof(char) * 256);
		password = (char*)malloc(sizeof(char) * 256);
		scanf("%s", userid);
		scanf("%s", password);
	}
	else {
		userid = argv[1]; /* userid (argv[1]), password (argv[2]) */
		password = argv[2];
	}

	rc = verifyPassword(userid, password);
#if _DEBUG
	if(rc == RC_SUCCESS) {
		printf("succeeded\n");
	}
	else {
		printf("failed\n");
	}
#endif
	return rc;
}

/*
 *	Linux and Solaris section
 */
#if defined(__linux__) || defined(__sparc)
int verifyPassword(char *userid, char *password) {
	struct spwd *spw; /* the shadowed password structure */

	spw = getspnam(userid);
	return (spw && !strcmp(spw->sp_pwdp, crypt(password, spw->sp_pwdp))) ? RC_SUCCESS : RC_FAILURE;
}
#endif /* __linux__, __sparc */

/*
 *	AIX and HP-UX section
 */
#if defined(_AIX) || defined(__hpux) || defined(__APPLE__)
int verifyPassword(char *userid, char *password) {
	struct passwd *pw; /* the unshadowed but encrypted password structure */

	pw = getpwnam(userid);
	return (pw && !strcmp(pw->pw_passwd, crypt(password, pw->pw_passwd))) ? RC_SUCCESS : RC_FAILURE;
}
#endif /* _AIX, __hpux */

/*
 *	MVS section
 */
#if defined(MVS)
int verifyPassword(char *userid, char *password) {
	struct passwd *pw;
	pw = getpwnam(userid);
	return (pw && __passwd(pw->pw_name, password, NULL)) ? RC_SUCCESS : RC_FAILURE;
}
#endif /* MVS */
