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

#include "Accept.h"
#include "Error.h"
#include "Logs.h"
#include "IO.h"

bool IO_select(s,in,out,err)
	int s,in,out,err;
{
	fd_set set;
	int nb;
	int buf[65556];
	struct timeval tim;
	int dead=0;
	bool wrk=false;

	FD_ZERO(&set);
	FD_SET(out,&set); /* execve input */
	FD_SET(s,&set); /* socket input */

	tim.tv_sec=0;
	tim.tv_usec=10;
	
	while(1)
	{
		wrk=false;
		if (dead==0)
		dead=waitpid(-1,0,WNOHANG);

		//if (select (0,&set,&set,&set,&tim)<0)
		if (select (FD_SETSIZE,&set,0,&set,&tim)<0)
		{
			perror("select");
			return 1;
		}
/*
		if (FD_ISSET(s,&set))
		{
			nb=recv(s,buf,tcpwin,0);
		//	fprintf(stderr,"EADIN %d\n",nb);
			if (nb==0) goto SELECT_END;
			if (nb>0) {
		//	if (nb<0&&dead) goto SELECT_END;
			//	write(2,buf,nb);
			//	write(in,buf,nb);
				//send(s,buf,nb,0);
			}
		}*/
		if (FD_ISSET(out,&set))
		{
			fcntl(out,F_SETFL,O_NONBLOCK,1);
			nb=read(out,buf,tcpwin);
			fcntl(out,F_SETFL,O_NONBLOCK,0);
			if (nb<0) { printf("GOme\n"); goto SELECT_END;}
		   if (nb>0)
			{
				setHTTPCode(buf,nb);
				screws_send(in,buf,nb);
			}
			wrk=true;
		}

		if (nb==0&&dead) { goto SELECT_END; }
		nb=0;
	}
SELECT_END:
return true;
}

