#include "tcpdispatcher"

void TcpDispatcher::handle() {
    
    debugmsg("TCP dispatcher: About to shuttle between client fd " <<
	     clientfd().fd() << " and backend fd " << backendfd().fd() <<
	     '\n');
    
    Fdset readset(maxtimeout(config.client_read_timeout(),
			     config.backend_read_timeout()));
    readset.add(clientfd());
    readset.add(backendfd());
    while (1) {
	Socket sock, othersock;
	int timeout;

	readset.wait_r();	
	if (readset.readable(clientfd())) {
	    sock = clientfd();
	    othersock = backendfd();
	    timeout = config.backend_write_timeout();
	} else if (readset.readable(backendfd())) {
	    sock = backendfd();
	    othersock = clientfd();
	    timeout = config.client_write_timeout();
	} else
	    break;

	if (!netbuffer.netread(sock))
	    break;
	debugmsg("Had data on " << sock.fd() <<
		 ", sending to " << othersock.fd() << '\n');
	netbuffer.netwrite (othersock, timeout);
	if (sock == backendfd())
	    balancer.backend(targetbackend()).addbytes(netbuffer.bufsz());
	else
	    IPStore::activity(clientfd().clientaddr().sin_addr,
			      targetbackend());

	netbuffer.reset();
    }
}
