#include <stdio.h>
#include <syslog.h>
#include <errno.h>

#ifndef lint
static char RCSid[] = "$Id: copy.c,v 1.6 1996/07/22 14:08:21 sjg Exp $";
#endif

static int _timeout = 0;

int
copy_timeout(secs)
	int secs;
{
	_timeout = secs;
}

int
copy_net(s1, s2)
	int s1, s2;
{
	char buf[BUFSIZ];
	int n, w, x, t;

	n = w = x = t = 0;

	for (;;) {
		if (_timeout)
			alarm(_timeout);

		n = read_net(s1, buf, sizeof(buf));

		if (_timeout)
			alarm(0);
	
		if (n < 0) {
#ifdef DEBUG
			syslog(LOG_DEBUG, "copy(%d,%d) n=%d, errno=%d: %m",
			       s1, s2, n , errno);
#endif
			if (errno == EINTR)
				continue;
			break;
		}
		
		if (n == 0)
			break;
		for (x = 0; x < n; ) {
			w = write_net(s2, &buf[x], n - x);
			if (w <= 0)
				return -1;
			x += w;
			t += w;
		}
	}
#ifdef DEBUG
	syslog(LOG_DEBUG, "copy(%d,%d) n=%d, w=%d: %m",
	       s1, s2, n , w);
#endif
	return t;
}
