/*
 * $Id: 430f93941094818ac44a5c7d9c46f74cbd20b57b $
 *
 * This file is part of nsmtp.
 *
 * Copyright (c) 2007, 2008 Niklas Olmes <niklas@noxa.de>
 *                          http://www.nevm.de/nsmtp/
 *                          NEVM-RIPE
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License Version 2
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 */

#include <stdio.h>
#include <string.h>

#include "legacyauth.h"
#include "log.h"
#include "config.h"

static const char rcsid[] = "$Id: 430f93941094818ac44a5c7d9c46f74cbd20b57b $";

/*
 * return codes:
 * -1 not possible to determine atm
 * 0  success
 * 1  fail
 */
int
legacyauth(const char *u, const char *p)
{
	FILE *fp;
	char buf[128];
	char *end, *cur_u, *cur_p;
	int line;

	if ((fp = fopen(nsmc_legacyauth_file, "r")) == NULL) {
		xfatal("fatal: legacyauth: unable to open file <%s>", nsmc_legacyauth_file);
		return -1;
	}

	line = 0;
	while (fgets(buf, sizeof(buf), fp) != NULL) {
		++line;

		if (*buf == '\n' || *buf == '#')
			continue;

		if ((end = strchr(buf, '\n')) == NULL) {
			xwarn("warn: legacyauth: line #(%d) of file <%s> is too long, ignoring", line, nsmc_legacyauth_file);
			continue;
		}
		*end = '\0';

		if ((cur_p = strchr(buf, ':')) == NULL) {
			xwarn("warn: legacyauth: unable to interpret line #(%d) of file <%s>: missing ':' delimiter", line, nsmc_legacyauth_file);
			continue;
		}

		cur_u = buf;
		*cur_p = '\0';
		++cur_p;

		if (*cur_p == '\0') {
			xwarn("warn: legacyauth: password for user <%s> in line #(%d) of file <%s> is empty (softfailing)", cur_u, line, nsmc_legacyauth_file);
			(void)fclose(fp);
			return -1;
		}

		if (strcasecmp(u, cur_u) != 0)
			continue;

		if (strcmp(p, cur_p) == 0) {
			/* success */
			(void)fclose(fp);
			return 0;
		} else {
			/* wrong password */
			(void)fclose(fp);
			return 1;
		}
	}

	(void)fclose(fp);

	/* not found */
	return 1;
}
