#include <sys/types.h>
#include <sys/time.h>
#include <sys/wait.h>
/* >>> Chee-Wai Yeung */
#include <signal.h>
/* <<< Chee-Wai Yeung */
#include "socks.h"
#ifndef NULL
#define NULL	0L
#endif

extern pid_t socks_conn_init;
extern pid_t socks_conn_sock;
extern int socks_conn_code;
extern int socks_conn_host;
extern int socks_conn_port;
extern int socks_last_conn_host;
extern int socks_last_conn_port;



int Rselect(width, readfds, writefds, exceptfds, timeout)
int width;
fd_set *readfds, *writefds, *exceptfds;
struct timeval *timeout;
{
	int wait_ret, status;

	if(!socks_conn_init ) {
		return(select(width, readfds, writefds, exceptfds, timeout));
	}

	if (readfds != NULL)
		FD_CLR(socks_conn_sock, readfds);
	if (exceptfds != NULL)
		FD_CLR(socks_conn_sock, exceptfds);
	if ((writefds == NULL) || !FD_ISSET(socks_conn_sock, writefds))
		return(select(width, readfds, writefds, exceptfds, timeout));

#if defined(NO_WAITPID)
	wait_ret = wait3(&status, WNOHANG, (struct rusage *) NULL);
#else
	wait_ret = waitpid(socks_conn_init, &status, WNOHANG);
#endif /* #if defined(NO_WAITPID) */
	if (wait_ret == 0) {
		FD_CLR(socks_conn_sock, writefds);
		return(select(width, readfds, writefds, exceptfds, timeout));
	} else if (wait_ret == socks_conn_init) {
		if (status & 0x00ff) {
			kill(socks_conn_init, SIGKILL);
			socks_conn_init = 0;
			socks_conn_code = SOCKS_FAIL;
		} else {
			status = (status >> 8) & 0x00ff;
			if (status == SOCKS_RESULT) {
				socks_last_conn_host = socks_conn_host;
				socks_last_conn_port = socks_conn_port;
			} 
			socks_conn_init = 0;
			socks_conn_code = status;
		}
	} else {
		kill(socks_conn_init, SIGKILL);
		socks_conn_init = 0;
		socks_conn_code = SOCKS_FAIL;
	}

	return(select(width, readfds, writefds, exceptfds, timeout));
}
