/*
 * mailing backend for dovecot antispam plugin
 *
 * Copyright (C) 2007, 2025       Johannes Berg <johannes@sipsolutions.net>
 *
 * 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.
 */

#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <fcntl.h>

#include "lib.h"
#include "dict.h"
#include "mail-storage-private.h"
#include "ostream.h"
#include "istream.h"

#include "antispam-plugin.h"


static int run_pipe(const struct antispam_settings *cfg,
		    int mailfd, enum classification wanted)
{
	char **dest;
	int dest_num;
	pid_t pid;
	int status;

	switch (wanted) {
	case CLASS_SPAM:
		dest = cfg->pipe_program_spam_args;
		dest_num = cfg->pipe_program_spam_args_num;
		break;
	case CLASS_NOTSPAM:
		dest = cfg->pipe_program_notspam_args;
		dest_num = cfg->pipe_program_notspam_args_num;
		break;
	}

	if (!dest)
		return -1;

	pid = fork();

	if (pid == -1)
		return -1;

	debug(cfg, "running mailtrain backend program %s", cfg->pipe_program);

	if (pid) {
		if (waitpid(pid, &status, 0) == -1)
			return -1;
		if (!WIFEXITED(status))
			return -1;
		return WEXITSTATUS(status);
	} else {
		char **argv;
		int sz = sizeof(char *) * (2 + cfg->pipe_program_args_num + dest_num + 1);
		int i, j, fd;

		argv = i_malloc(sz);
		memset(argv, 0, sz);

		argv[0] = (char *) cfg->pipe_program;

		for (i = 0; i < cfg->pipe_program_args_num; i++) {
			argv[i + 1] = (char *) cfg->pipe_program_args[i];
			debug(cfg, "running mailtrain backend program parameter %d %s", i + 1, argv[i + 1]);
		}

		for (j = 0; j < dest_num; j++) {
			argv[i + 1 + j] = (char *) dest[j];
			debug(cfg, "running mailtrain backend program parameter %d %s", i + 1 + j, argv[i + 1 + j]);
		}

		dup2(mailfd, 0);
		fd = open("/dev/null", O_WRONLY);
		dup2(fd, 1);
		dup2(fd, 2);
		close(fd);
		execv(cfg->pipe_program, argv);
		_exit(1);
		/* not reached */
		return -1;
	}
}

struct antispam_transaction_context {
	char *tmpdir;
	int count;
	int tmplen;
};

static struct antispam_transaction_context *
backend_start(const struct antispam_settings *cfg ATTR_UNUSED,
	      struct mailbox *box ATTR_UNUSED)
{
	struct antispam_transaction_context *ast;
	char *tmp;

	ast = i_new(struct antispam_transaction_context, 1);

	ast->count = 0;

	tmp = i_strconcat(cfg->pipe_tmpdir, "/antispam-mail-XXXXXX", NULL);

	ast->tmpdir = mkdtemp(tmp);
	if (!ast->tmpdir)
		i_free(tmp);
	else
		ast->tmplen = strlen(ast->tmpdir);

	return ast;
}

static int process_tmpdir(const struct antispam_settings *cfg,
			  struct mailbox_transaction_context *ctx,
			  struct antispam_transaction_context *ast)
{
	int cnt = ast->count;
	int fd;
	char *buf;
	enum classification wanted;
	int rc = 0;

	T_BEGIN {

	buf = t_malloc0(20 + ast->tmplen);

	while (rc == 0 && cnt > 0) {
		cnt--;
		i_snprintf(buf, 20 + ast->tmplen - 1, "%s/%d",
			   ast->tmpdir, cnt);

		fd = open(buf, O_RDONLY);
		read(fd, &wanted, sizeof(wanted));

		if ((rc = run_pipe(cfg, fd, wanted))) {
			mail_storage_set_error(ctx->box->storage,
					       MAIL_ERROR_TEMP,
					       "failed to send mail");
			debug(cfg, "run program failed with exit code %d\n", rc);
			rc = -1;
		}

		close(fd);
	}

	} T_END;

	return rc;
}

static void clear_tmpdir(struct antispam_transaction_context *ast)
{
	char *buf;

	T_BEGIN {

	buf = t_malloc0(20 + ast->tmplen);

	while (ast->count > 0) {
		ast->count--;
		i_snprintf(buf, 20 + ast->tmplen - 1, "%s/%d",
			   ast->tmpdir, ast->count);
		unlink(buf);
	}
	rmdir(ast->tmpdir);

	} T_END;
}

static void backend_rollback(const struct antispam_settings *cfg ATTR_UNUSED,
			     struct antispam_transaction_context *ast)
{
	if (ast->tmpdir) {
		/* clear it! */
		clear_tmpdir(ast);
		i_free(ast->tmpdir);
	}

	i_free(ast);
}

static int backend_commit(const struct antispam_settings *cfg,
			  struct mailbox_transaction_context *ctx,
			  struct antispam_transaction_context *ast)
{
	int ret;

	if (!ast->tmpdir) {
		i_free(ast);
		return 0;
	}

	ret = process_tmpdir(cfg, ctx, ast);

	clear_tmpdir(ast);

	i_free(ast->tmpdir);
	i_free(ast);

	return ret;
}

static int backend_handle_mail(const struct antispam_settings *cfg ATTR_UNUSED,
			       struct mailbox_transaction_context *t,
			       struct antispam_transaction_context *ast,
			       struct mail *mail, enum classification wanted)
{
	struct istream *mailstream;
	struct ostream *outstream;
	int ret;
	char *buf;
	const unsigned char *beginning;
	size_t size;
	int fd;

	if (!ast->tmpdir) {
		mail_storage_set_error(t->box->storage,
				       MAIL_ERROR_NOTPOSSIBLE,
				       "Failed to initialise temporary dir");
		return -1;
	}

	if (mail_get_stream(mail, NULL, NULL, &mailstream) < 0) {
		mail_storage_set_error(t->box->storage,
				       MAIL_ERROR_EXPUNGED,
				       "Failed to get mail contents");
		return -1;
	}

	T_BEGIN {

	buf = t_malloc0(20 + ast->tmplen);
	i_snprintf(buf, 20 + ast->tmplen - 1, "%s/%d", ast->tmpdir, ast->count);

	fd = creat(buf, 0600);
	if (fd < 0) {
		mail_storage_set_error(t->box->storage,
				       MAIL_ERROR_NOTPOSSIBLE,
				       "Failed to create temporary file");
		ret = -1;
		goto out;
	}

	ast->count++;

	outstream = o_stream_create_fd_autoclose(&fd, 0);
	if (!outstream) {
		ret = -1;
		mail_storage_set_error(t->box->storage,
				       MAIL_ERROR_NOTPOSSIBLE,
				       "Failed to stream temporary file");
		goto out_close;
	}

	if (o_stream_send(outstream, &wanted, sizeof(wanted))
			!= sizeof(wanted)) {
		ret = -1;
		mail_storage_set_error(t->box->storage,
				       MAIL_ERROR_NOTPOSSIBLE,
				       "Failed to write marker to temp file");
		goto failed_to_copy;
	}

	if (i_stream_read_data(mailstream, &beginning, &size, 5) < 0 ||
	    size < 5) {
		ret = -1;
		mail_storage_set_error(t->box->storage,
				       MAIL_ERROR_NOTPOSSIBLE,
				       "Failed to read mail beginning");
		goto failed_to_copy;
	}

	/* "From "? skip line */
	if (memcmp("From ", beginning, 5) == 0)
		i_stream_read_next_line(mailstream);

	if (o_stream_send_istream(outstream, mailstream) < 0) {
		ret = -1;
		mail_storage_set_error(t->box->storage,
				       MAIL_ERROR_NOTPOSSIBLE,
				       "Failed to copy to temporary file");
		goto failed_to_copy;
	}

	ret = 0;

 failed_to_copy:
	o_stream_destroy(&outstream);
 out_close:
	close(fd);
 out:	;
	} T_END;

	return ret;
}

static bool backend_settings(struct antispam_settings *cfg,
			     pool_t pool ATTR_UNUSED, const char **error_r)
{
	if (cfg->_pipe_program_args[0]) {
		cfg->pipe_program_args = p_strsplit(cfg->pool, cfg->_pipe_program_args, ";");
		cfg->pipe_program_args_num = str_array_length(
					(const char *const *)cfg->pipe_program_args);
		for (int i = 0; i < cfg->pipe_program_args_num; i++)
			debug(cfg, "pipe backend arg[%d] = %s\n",
			      i, cfg->pipe_program_args[i]);
	}

	if (cfg->_pipe_program_spam_args[0]) {
		cfg->pipe_program_spam_args = p_strsplit(cfg->pool, cfg->_pipe_program_spam_args, ";");
		cfg->pipe_program_spam_args_num = str_array_length(
					(const char *const *)cfg->pipe_program_spam_args);
		for (int i = 0; i < cfg->pipe_program_spam_args_num; i++)
			debug(cfg, "pipe backend arg[%d] = %s\n",
			      i, cfg->pipe_program_spam_args[i]);
	} else {
		*error_r = t_strdup("no pipe spam arguments configured");
		return false;
	}

	if (cfg->_pipe_program_notspam_args[0]) {
		cfg->pipe_program_notspam_args = p_strsplit(cfg->pool, cfg->_pipe_program_notspam_args, ";");
		cfg->pipe_program_notspam_args_num = str_array_length(
					(const char *const *)cfg->pipe_program_notspam_args);
		for (int i = 0; i < cfg->pipe_program_notspam_args_num; i++)
			debug(cfg, "pipe backend arg[%d] = %s\n",
			      i, cfg->pipe_program_notspam_args[i]);
	} else {
		*error_r = t_strdup("no pipe not-spam arguments configured");
		return false;
	}

	debug(cfg, "pipe backend program = %s\n", cfg->pipe_program);
	debug(cfg, "pipe backend tmpdir %s\n", cfg->pipe_tmpdir);

	return true;
}

struct backend pipe_backend = {
	.settings = backend_settings,
	.handle_mail = backend_handle_mail,
	.start = backend_start,
	.rollback = backend_rollback,
	.commit = backend_commit,
};
