/*
 * $Id: 41a4921bf02f70a439ab2044a7c6fb9e70a534f3 $
 *
 * 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.
 *
 */

/*
 * RfC3462
 * RfC3464
 */

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <unistd.h>

#include "alloc.h"
#include "smtp.h"
#include "spool.h"
#include "log.h"
#include "ndn.h"
#include "config.h"

static const char rcsid[] = "$Id: 41a4921bf02f70a439ab2044a7c6fb9e70a534f3 $";

int
ndn_tooold(const SMTP_CTX *ctx, const char **rcpts, time_t last)
{
	char buf[256];

	(void)snprintf(buf, sizeof(buf),
		"I'm sorry to inform you that your message could not be delivered\n"
		"to one or more recipients.\n"
		"Es tut mir Leid Ihnen mitteilen zu muessen, dass Ihre Nachricht\n"
		"an einen oder mehrere Empfaenger nicht zugestellt werden konnte.\n"
		"\n"
		"The message has been in the queue for too long,\n"
		"I'm not going to try again.\n"
		"Die Nachricht ist schon zu lange in der Warteschlange,\n"
		"ich werde nicht weiter versuchen die Nachricht zuzustellen.\n");

	return ndn_generic(ctx, buf, rcpts, NULL, NULL, NULL, last);
}

int
ndn_bounce(const SMTP_CTX *ctx, const char **rcpts, const char *mx, const char *reason, const char *state, time_t last)
{
	char buf[256];

	(void)snprintf(buf, sizeof(buf),
		"I'm sorry to inform you that your message could not be delivered\n"
		"to one or more recipients.\n"
		"Es tut mir Leid Ihnen mitteilen zu muessen, dass Ihre Nachricht\n"
		"an einen oder mehrere Empfaenger nicht zugestellt werden konnte.\n");

	return ndn_generic(ctx, buf, rcpts, mx, reason, state, last);
}

int
ndn_generic(const SMTP_CTX *ctx, const char *descr, const char **rcpts, const char *mx, const char *reason, const char *state, time_t last)
{
	SMTP_CTX *ndn;
	char buf[2048], boundary[64];
	char *t822;
	int i;

	if (*(ctx->from) == '\0') {
		xinfo("{%s}|%s| info: DOUBLE BOUNCE, discarding", ctx->conn_id, ctx->lmid);
		return 0;
	}

	ndn = init_smtp_ctx();

	ndn->conn_id = nsm_strdup(ctx->conn_id);
	ndn->lmid = make_mid(ndn);
	ndn->from = nsm_strdup("");
	ndn->helo = nsm_strdup(nsmc_name);

	ndn->rcpts = nsm_calloc(2, sizeof(char *));
	ndn->rcpts[0] = nsm_strdup(ctx->from);
	ndn->rcpts[1] = NULL;

	nsm_asprintf(&(ndn->recvdinfo), "(nsmtp/ndn %d for sender %s)", getpid(), ctx->from);

	t822 = make_822time(time(NULL));
	(void)snprintf(boundary, sizeof(boundary), "%lu.%ld/%s", (unsigned long)time(NULL), random() % 1000000 + 1, nsmc_name);

	ndn->data = nsm_calloc(1, 1);
	ndn->size = 0;

	#define APPEND()	ndn->data = nsm_realloc(ndn->data, ndn->size + strlen(buf)); \
				(void)memcpy(ndn->data + ndn->size, buf, strlen(buf)); \
				ndn->size += strlen(buf);

	/*
	 * Outer MIME-Header
	 */
	(void)snprintf(buf, sizeof(buf),
		"Date: %s\n"
		"From: MAILER-DAEMON@%s (Mail Delivery System)\n"
		"Subject: Undelivered Mail Returned to Sender\n"
		"To: %s\n"
		"Message-Id: <%s>\n"
		"MIME-Version: 1.0\n"
		"Content-Type: multipart/report; report-type=delivery-status;\n"
		"\tboundary=\"%s\"\n"
		"\n"
		"This is a MIME-encapsulated message.\n",
		t822, nsmc_name, ctx->from, ndn->lmid, boundary);
	APPEND();
	nsm_free(t822);

	/*
	 * Notification
	 */
	(void)snprintf(buf, sizeof(buf),
		"\n--%s\n"
		"Content-Description: Notification\n"
		"Content-Type: text/plain; charset=us-ascii\n"
		"\n"
		"This is the nsmtp MTA program at %s.\n"
		"Dies ist das nsmtp MTA Programm auf %s.\n"
		"\n"
		"%s"
		"\n"
		"The original message is attached.\n"
		"Die Originalnachricht ist angehaengt.\n"
		"\n", boundary, nsmc_name, nsmc_name, descr);
	APPEND();

	(void)snprintf(buf, sizeof(buf), "    ----- The following addresses had delivery problems -----\n");
	APPEND();

	for (i = 0; rcpts[i] != NULL; i++) {
		if (mx != NULL && reason != NULL && state != NULL)
			(void)snprintf(buf, sizeof(buf), "<%s> MX %s said: \"%s\" at state %s\n", rcpts[i], mx, reason, state);
		else if (reason != NULL)
			(void)snprintf(buf, sizeof(buf), "<%s> (%s)\n", rcpts[i], reason);
		else
			(void)snprintf(buf, sizeof(buf), "<%s>\n", rcpts[i]);
		APPEND();
	}

	/*
	 * Delivery Report
	 */
	(void)snprintf(buf, sizeof(buf),
		"\n--%s\n"
		"Content-Description: Delivery Report\n"
		"Content-Type: message/delivery-status\n"
		"\n"
		"Reporting-MTA: dns; %s\n"
		"X-nsmtp-CID: %s\n"
		"X-nsmtp-LMID: %s\n"
		"X-nsmtp-Failed-State: %s\n"
		"X-nsmtp-Sender: rfc822; %s\n",
		boundary, nsmc_name, ctx->conn_id, ctx->lmid, state, ctx->from);
	APPEND();

	for (i = 0; rcpts[i] != NULL; i++) {
		(void)snprintf(buf, sizeof(buf),
			"\n"
			"Final-Recipient: rfc822; %s\n"
			"Action: failed\n"
			"Status: 5.0.0\n", rcpts[i]);
		APPEND();

		if (mx != NULL) {
			(void)snprintf(buf, sizeof(buf), "Remote-MTA: dns; %s\n", mx);
			APPEND();
		}
		if (reason != NULL) {
			(void)snprintf(buf, sizeof(buf), "Diagnostic-Code: %s; %s\n", mx != NULL ? "smtp" : "local", reason);
			APPEND();
		}
		if (last != 0) {
			t822 = make_822time(last);
			(void)snprintf(buf, sizeof(buf), "Last-Attempt-Date: %s\n", t822);
			nsm_free(t822);
			APPEND();
		}
	}

	/*
	 * Original Message
	 */
	(void)snprintf(buf, sizeof(buf),
		"\n--%s\n"
		"Content-Description: Undelivered Message\n"
		"Content-Type: message/rfc822\n"
		"\n", boundary);
	APPEND();

	/* Message Data */
	ndn->data = nsm_realloc(ndn->data, ndn->size + ctx->size);
	(void)memcpy(ndn->data + ndn->size, ctx->data, ctx->size);
	ndn->size += ctx->size;

	(void)snprintf(buf, sizeof(buf), "\n--%s\n", boundary);
	APPEND();

	/*
	 * Spool NDN
	 */
	if (spool("incoming", ndn) != 0) {
		xwarn("{%s}|%s| warn: ndn_generic: creating ndn spool file failed", ctx->conn_id, ctx->lmid);
		destroy_smtp_ctx(ndn);
		return 1;
	}

	for (i = 0; rcpts[i] != NULL; i++)
		xinfo("{%s}|%s| info: NDN for rcpt <%s> (#%d), LMID=<%s>", ctx->conn_id, ctx->lmid, rcpts[i], i, ndn->lmid);

	destroy_smtp_ctx(ndn);

	return 0;
}
