/*
 * This code is part of Screws project.
 * Copylefted by pancake@phreaker.net at 2003
 */

#include "Signal.h"
extern int forks;

/* Connection timeout Signal (USE SIGALRM) */
int S_ALRM=0;
int S_TYPE=0;

void 
my_SIGALRM(sig)
	int sig;
{
	forks--;

	switch(S_TYPE)
	{
	case ALARM_TIMEOUT:
		if (S_ALRM)
		{
		shutdown(S_ALRM,SHUT_RDWR);
		close(S_ALRM);
		exit(0); /* clean exit 4 childrens */
		}
		break;
	case ALARM_KILL:
		if (S_ALRM)
		{
		kill(S_ALRM,Svr.signal);
		exit(0); /* clean exit 4 childrens */
		}
		break;
	}
}

int
catchTimeout(s,time,type)
	int s,time; /* time enables/disables timeout */
{
	if (time) {
		S_ALRM=s;
		S_TYPE=type;
		signal(SIGALRM,(void *)my_SIGALRM);
		alarm(time);
	} else {

		S_ALRM=ALARM_NULL;
		signal(SIGALRM,SIG_IGN);
		alarm(0);
	}
	return 0;
}


/* Catch Ctrl-C signal (AKA SIGINT) */
void 
my_SIGINT(sig)
	int sig;
{

	if (sig==SIGPIPE)
	{
	printf ("SIGPIPE RECEIVED!!\n");
	exit(1);
	}
	printf("Signal catched!!\n");
	Svr.ok=false;
}

void*
process_event()
{ // IPC Using alarm? XXX
	//printf("EVENT!\n");
	alarm(1);
}

int
catchSignals(who)
	int who;
{
	int ret=0;

	switch(who)
	{
	case WHO_CHILDREN:
		//printf("CHILDREN IS GOD\n");
		signal(SIGALRM,(void*)process_event);
	alarm(1);
		break;
	case WHO_FATHER:
		//printf("FATHER ROCKS\n");
		ret|=(int)( signal(SIGINT,(void *)my_SIGINT ) );

		/* Ignore SIGPIPE for *BSD systems */
		ret|=(int)( signal(SIGPIPE,SIG_IGN) );
		//ret|=(int)( signal(SIGPIPE,my_SIGINT) );
		break;
	}

	if (ret) return ERROR_SIGNAL;
	return 0;
}

