/* -------------------------------------------------------------------- */
/* -------------------------------------------------------------------- */

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include <errno.h>
#include <unistd.h>
#include <sys/time.h>

#include "http_tread.h"


/* -------------------------------------------------------------------- */

static int timeout_flag;

/* -------------------------------------------------------------------- */
/* -------------------------------------------------------------------- */
static void timeout_func(int sig)
{	timeout_flag = 1;
}

/* -------------------------------------------------------------------- */
/* -------------------------------------------------------------------- */
int http_tread(int fd, char *buf, int len, int *timeout)
{
	int 	using_timeout,
		bytes_read,
		total_read;

	time_t	start_time,
		new_timeout;


	void (* orig_signal)(int);




	bytes_read    = 0;
	total_read    = 0;
	using_timeout = 0;
	timeout_flag  = 0;
	start_time    = 0;
	orig_signal   = NULL;

	if ((timeout != NULL) && 
	    (*timeout != 0))
	{
		using_timeout = 1;		

		start_time = time(NULL);
		orig_signal = signal(SIGALRM, timeout_func);
		alarm(*timeout);
	}


	while (len > 0)
	{
		if (timeout_flag)
		{	
			*timeout = 0;
			signal(SIGALRM, orig_signal);

			return bytes_read;
		}

		bytes_read = read(fd, &buf[total_read], len);
		if (bytes_read == -1)
		{
			if (errno != EINTR)
			{	break;
			}
		}
		else
		if (bytes_read == 0)
		{
			break;
		}
		else
		{
			total_read += bytes_read;
			len        -= bytes_read;
		}
	}

	if (using_timeout)
	{
		alarm(0);
		signal(SIGALRM, orig_signal);

		new_timeout = (*timeout - (time(NULL) - start_time));
		if (new_timeout < 0)
		{	new_timeout = 0;
		}

		*timeout = new_timeout;		
	}

	return total_read;
}



