/* DoConnect */

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <syslog.h>
#include "socks.h"

extern void sockd_fail(); 
#if defined(SOCKSIFIED_SOCKD)
extern int SOCKSinit();
#endif /* #if defined(SOCKSIFIED_SOCKD) */


/*
** Actually connect a socket to the outside world,
*/
#if defined(SOCKSIFIED_SOCKD)
int RDoConnect(in, dstshp, log_msg)
#else
int DoConnect(in, dstshp, log_msg)
#endif /* #if defined(SOCKSIFIED_SOCKD) */
int	in;
struct sockshost_s *dstshp;
char *log_msg;
/* returns descriptor of socket connection to destination */
{
	int			out;
	struct sockaddr_in	sin;
	Socks_t			ndst;
	int	turnon = 1;
	int	cstat;
	struct in_addr *pIP;

	bzero((char *)&sin, sizeof(sin));
#if defined(SO_OOBINLINE)
	setsockopt(in, SOL_SOCKET, SO_OOBINLINE, &turnon, sizeof(turnon));
#endif
	ndst.version = SOCKS_REPLY_VERSION;
	ndst.cmd = SOCKS_RESULT;

	sin.sin_family = AF_INET;
	sin.sin_port = dstshp->port;

	for (pIP = dstshp->shipaddr; (*pIP).s_addr != 0; pIP++) { 
		sin.sin_addr.s_addr = (*pIP).s_addr;
		if ((out = socket(AF_INET, SOCK_STREAM, 0)) < 0)
			sockd_fail("socket()", in, &ndst,log_msg);

#if defined(SOCKSIFIED_SOCKD)
		SOCKSinit("rsockd");
		cstat = Rconnect(out, (struct sockaddr *)&sin, sizeof(struct sockaddr_in));
#else
		cstat = connect(out, (struct sockaddr *)&sin, sizeof(struct sockaddr_in));
#endif /* #if defined(SOCKSIFIED_SOCKD) */
		if (cstat != -1) break;
		close(out);
	}
	if (cstat == -1) 
		sockd_fail("connect()", in, &ndst,log_msg);

	syslog(LOG_LOW, "connected -- %s", log_msg);
#if defined(SO_OOBINLINE)
	setsockopt(out, SOL_SOCKET, SO_OOBINLINE, &turnon, sizeof(turnon));
#endif
	socks_SendDst(in, &ndst);
	return out;
}
