/* greylisting-spp - A qmail-spp plugin implementing greylisting
 *
 *  Copyright (C) 2004,2011 Peter Conrad <conrad@tivano.de>
 *
 *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <stdlib.h>
#include <string.h>
#include "db-api.h"
#include "commonstuff.h"

#define	ENV_DEBUG	"GL_DEBUG"
#define	ENV_VERBOSE	"GL_VERBOSE"
#define	ENV_WHITELISTED	"GL_WHITELISTED"
#define	ENV_RELAYCLIENT	"RELAYCLIENT"
#define ENV_LISTDB	"GL_DATABASE"
#define	ENV_MIN_REJECT	"GL_MIN_REJECT"
#define ENV_MAX_WAIT	"GL_MAX_WAIT"
#define ENV_ACCEPT_GOOD	"GL_ACCEPT_GOOD"
#define	ENV_MAIL_FROM	"SMTPMAILFROM"
#define ENV_RCPT_TO	"SMTPRCPTTO"
#define	ENV_REMOTEIP	"TCPREMOTEIP"

#define DEFAULT_MIN_REJECT	300
#define DEFAULT_MAX_WAIT	86400
#define DEFAULT_ACCEPT_GOOD	259200

#define CMD_REJECT	"E451 GL - temporary problem. Please try again later.\n"
#define CMD_REJECT_LATE	"LD451 GL - temporary problem. Please try again later.\n"

int  min_reject, max_wait, accept_good;

#define ERR_MISSING_VARIABLE	"Missing environment variable "

/** Retrieve the environment variable with the given name. If there is no
 *  such variable, write an error message to stderr and exit with a non-zero
 *  exit code. */
static char *get_required_env(char *name) {
char *result = getenv(name);

    if (!result) {
	write_error_string(progname);
	write_error_string(": ");
	write_error_string(ERR_MISSING_VARIABLE);
	write_error_string(name);
	write_error_string("\n");
	exit(1);
    }
    return result;
}

/** Retrieve the given environment variable. If it is set, parse it as a
 *  number and return the value, otherwise return the given default value.
 */
static int get_numeric_option(char *name, int dflt) {
char *value = getenv(name);

    if (value) {
	return atoi(value);
    }
    return dflt;
}

/** Write a reject command to stdout */
static void reject(char *sender) {
    if (!*sender || !strncasecmp(sender, "postmaster@", strlen("postmaster@"))){
	/* Empty sender or postmaster sender -> delay negative answer until
	 * after DATA... */
	write(STDOUT_FILENO, CMD_REJECT_LATE, strlen(CMD_REJECT_LATE));
    } else {
	write(STDOUT_FILENO, CMD_REJECT, strlen(CMD_REJECT));
    }
}

/** main function of the greylisting plugin */
int main(int argc, char **argv) {
char *db, *remoteip, *sender, *ezmlm_sender = NULL, *recipient, *ezmlm_ret;
int found, i;

    progname = argv[0];

    debug = getenv(ENV_DEBUG);
    if (debug) {
	verbose = debug;
    } else {
	verbose = getenv(ENV_VERBOSE);
    }
    if (getenv(ENV_RELAYCLIENT)) {
	DEBUG("Accepting with RELAYCLIENT")
	exit(0);
    }
    if (getenv(ENV_WHITELISTED)) {
	DEBUG("Accepting with " ENV_WHITELISTED)
	exit(0);
    }

    db = get_required_env(ENV_LISTDB);
    remoteip = get_required_env(ENV_REMOTEIP);
    sender = get_required_env(ENV_MAIL_FROM);
    recipient = get_required_env(ENV_RCPT_TO);

    min_reject = get_numeric_option(ENV_MIN_REJECT, DEFAULT_MIN_REJECT);
    max_wait = get_numeric_option(ENV_MAX_WAIT, DEFAULT_MAX_WAIT);
    accept_good = get_numeric_option(ENV_ACCEPT_GOOD, DEFAULT_ACCEPT_GOOD);

    if ((ezmlm_ret = strstr(sender, "-return-"))) {
	/* special handling for ezmlm's VERPs:
	 * check if sender address matches '^.*-return-\d+-.*$', if yes
	 * replace message number with a single '$'
	 */
	ezmlm_ret = &ezmlm_ret[8];
	i = 0;
	while (ezmlm_ret[i] >= '0' && ezmlm_ret[i] <= '9') { i++; }
	if (i > 1 && ezmlm_ret[i] == '-') {
	    /* match found */
	    ezmlm_sender = (char *) malloc(strlen(sender) + 1);
	    if (ezmlm_sender) {
		DEBUG3("Munging EZMLM style sender address '",sender,"'")
		memcpy(ezmlm_sender, sender, ezmlm_ret - sender);
		ezmlm_sender[ezmlm_ret - sender] = '$';
		memcpy(&ezmlm_sender[ezmlm_ret - sender + 1], &ezmlm_ret[i],
		       strlen(ezmlm_ret) - i + 1);
		DEBUG3("Munged result: '",ezmlm_sender,"'")
	    } else {
		err_memory();
	    }
	}
    }

    opendb(db);
    found = find_entry(remoteip, ezmlm_sender == NULL ? sender : ezmlm_sender,
		       recipient);
    if (found < 0) {
	/* No match found -> reject and add entry */
	VERBOSETUPLE("Rejecting new triple", remoteip, sender, recipient)
	reject(sender);
	add_entry(remoteip, ezmlm_sender == NULL ? sender : ezmlm_sender,
		  recipient);
    } else if (found == 0) {
	/* Match found, but min_reject is not expired -> reject again */
	VERBOSETUPLE("Rejecting young triple", remoteip, sender, recipient)
	reject(sender);
    } else {
	/* Match found and min_reject expired and max_wait or accept_good not
	 * expired */
	DEBUGTUPLE("Accepting known triple", remoteip, sender, recipient)
	if (!*sender) {
	    /* Empty sender (bounce message) -> delete entry */
	    delete_entry();
	} else {
	    /* not a bounce -> update entry [and accept] */
	    update_entry();
	}
    }
    closedb();

    if (ezmlm_sender) { free(ezmlm_sender); }

    return 0;
}

/* Do not change the following line:
 * arch-tag: cc3f1dfa-3073-45cc-bdd4-c2e1355a9df5
 */
