/* This file is part of Mailfromd.             -*- c -*-
   Copyright (C) 2007-2020 Sergey Poznyakoff

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3, or (at your option)
   any later version.

   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, see <http://www.gnu.org/licenses/>. */

MF_BUILTIN_MODULE

#include "spf.h"

MF_VAR(spf_explanation, STRING);
MF_VAR(spf_mechanism, STRING);
MF_VAR(spf_explanation_prefix, STRING);
       
MF_DSEXP_SUPPRESS([<update_spf_vars>],[<
static void
update_spf_vars(eval_environ_t env, spf_answer_t *ans)
{
	size_t i;
	
	MF_VAR_SET_STRING(spf_explanation, ans->exp_text);
	MF_OBSTACK_BEGIN();
	if (ans->mechn) {
		MF_OBSTACK_GROW(ans->mechv[0]);
		for (i = 1; i < ans->mechn; i++) {
			MF_OBSTACK_1GROW(' ');
			MF_OBSTACK_GROW(ans->mechv[i]);
		}
	}
	MF_OBSTACK_1GROW(0);
	MF_VAR_REF(spf_mechanism, size, mf_c_val(MF_OBSTACK_FINISH, size));
}
>])

MF_DSEXP
MF_DEFUN(spf_check_host, NUMBER, STRING ip, STRING domain, STRING sender,
	 STRING helo_domain, STRING my_domain)
{
	spf_result res;
	spf_query_t q;
	spf_answer_t ans;

	q.ipstr = ip;
	q.domain = domain;
	q.sender = sender;
	q.helo_domain = helo_domain;
	q.my_domain = my_domain;
	q.exp_prefix = MF_VAR_STRING(spf_explanation_prefix);
	res = spf_check_host(&q, &ans);
	update_spf_vars(env, &ans);
	spf_answer_free(&ans);
	MF_RETURN(res);
}
END

MF_DSEXP
MF_DEFUN(spf_test_record, NUMBER, STRING record,
	 STRING ip, STRING domain, STRING sender,
	 STRING helo_domain, STRING my_domain)
{
	spf_result res;
	spf_query_t q;
	spf_answer_t ans;

	q.ipstr = ip;
	q.domain = domain;
	q.sender = sender;
	q.helo_domain = helo_domain;
	q.my_domain = my_domain;
	q.exp_prefix = MF_VAR_STRING(spf_explanation_prefix);
	res = spf_test_record(record, &q, &ans);
	update_spf_vars(env, &ans);
	spf_answer_free(&ans);
	MF_RETURN(res);
}
END