/*
 * $Id: a000e3541c2f20ba139c719216245b2b748b129c $
 *
 * 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 <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>

#include "signals.h"
#include "config.h"

#define RETSIGTYPE void

static RETSIGTYPE sigchld(int);
static RETSIGTYPE sigterm(int);

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

extern int smtpd_childcount;
extern pid_t *smtpd_childdeath;
extern int smtpd_want_down;

static RETSIGTYPE
sigchld(int ignore)
{
	pid_t child;
	int status;
	int i;

	(void)ignore;

#ifdef S_SPLINT_S
	status = 0;
#endif
	while ((child = waitpid(-1, &status, WNOHANG)) > 0) {
		smtpd_childcount--;

		/*
		 * Record child deaths to be examined by handle() loop
		 */
		if (smtpd_childdeath == NULL)
			continue;
		i = 0;
		while (i < nsmc_smtpd_maxchilds && smtpd_childdeath[i] != 0)
			i++;
		if (i < nsmc_smtpd_maxchilds)
			smtpd_childdeath[i] = child;
	}
}

static RETSIGTYPE
sigterm(int ignore)
{

	(void)ignore;
	smtpd_want_down = 1;
}

void
init_sighandlers(void)
{

	(void)signal(SIGCHLD, sigchld);
	(void)signal(SIGTERM, sigterm);
}
