/*
 * Copyright (C) 2001 USAGI/WIDE Project.
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the project nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */
/*
 * Copyright (c) 1983 Regents of the University of California.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

/*
 * From: @(#)ctl_transact.c	5.8 (Berkeley) 3/1/91
 */
char ctlt_rcsid[] = 
  "$Id: ctl_transact.c,v 1.12 1999/09/28 22:04:14 netbug Exp $";

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <netinet/in.h>
/* #include <netinet/ip.h> looks like this is not needed (no functions used) */
#ifdef INET6
#include <netdb.h>
#endif
#include <string.h>
#include <errno.h>
#include "talk.h"

#define CTL_WAIT 2	/* time to wait for a response, in seconds */

/* We now make two UDP sockets, one for the local talkd, one for the remote. */
static int to_local_talkd;
static int to_remote_talkd;
#ifdef INET6
static struct sockaddr_storage local_addr_for_remote;
#else
static struct sockaddr local_addr_for_remote;
#endif
socklen_t local_addrsize_for_remote;


/* open the ctl sockets */
void
open_ctl(void) 
{
#ifdef INET6
	struct addrinfo hints, *lres0, *lres, *rres, *rres0;
	int gai;
#else
	struct sockaddr_in loc;
	struct sockaddr_in rem;
#endif
	int on=1;

#ifdef INET6
	memset(&hints, 0, sizeof(hints));
	hints.ai_family = default_family;
	hints.ai_socktype = SOCK_DGRAM;
	hints.ai_protocol = IPPROTO_UDP;
	hints.ai_flags = AI_PASSIVE;

	gai = getaddrinfo(NULL, "0", &hints, &lres0);
	if (gai) {
		p_error(gai_strerror(gai));
	}

	to_local_talkd = -1;
	for (lres=lres0; lres; lres=lres->ai_next) {
		to_local_talkd = socket(lres->ai_family, lres->ai_socktype, lres->ai_protocol);
		if (to_local_talkd < 0)
			continue;
		/*
		 * Linux does some async error return stuff that 
		 * really disagrees with us. So we disable it.
		 */
		setsockopt(to_local_talkd, SOL_SOCKET, SO_BSDCOMPAT, &on ,sizeof(on));
		/* Explicitly talk to the local daemon over loopback. */
		if (bind(to_local_talkd, lres->ai_addr, lres->ai_addrlen) < 0) {
			close(to_local_talkd);
			to_local_talkd = -1;
			continue;
		}
		lres->ai_flags = 0;
		gai = getaddrinfo(NULL, SERV_NTALK, lres, &rres0);
		if (gai) {
			continue;
		}
		if (connect(to_local_talkd, rres0->ai_addr, rres0->ai_addrlen) < 0) {
			freeaddrinfo(rres0);
			continue;
		}
		freeaddrinfo(rres0);
		break;
	}
	freeaddrinfo(lres0);
	if (to_local_talkd < 0) {
		p_error("Couldn't socket/bind/connect local socket");
	}
#else	/* INET6 / !INET6 */
	to_local_talkd = socket(AF_INET, SOCK_DGRAM, 0);

	if (to_local_talkd < 0) {
		p_error("Bad socket");
	}

#ifdef SO_BSDCOMPAT
	/* 
	 * Linux does some async error return stuff that
	 * really disagrees with us. So we disable it.
	 */
	setsockopt(to_local_talkd, SOL_SOCKET, SO_BSDCOMPAT, &on, sizeof(on));
#endif

	/*
	 * Explicitly talk to the local daemon over loopback.
	 */
	memset(&loc, 0, sizeof(loc));
	loc.sin_family = AF_INET;
	loc.sin_port = htons(0);
	loc.sin_addr.s_addr = htonl(INADDR_LOOPBACK);

	if (bind(to_local_talkd, (struct sockaddr *)&loc, sizeof(loc))<0) {
		p_error("Couldn't bind local control socket");
	}

	memset(&loc, 0, sizeof(loc));
	loc.sin_family = AF_INET;
	loc.sin_port = daemon_port;
	loc.sin_addr.s_addr = htonl(INADDR_LOOPBACK);

	if (connect(to_local_talkd, (struct sockaddr *)&loc, sizeof(loc))<0) {
		p_error("Couldn't connect local control socket");
	}
#endif	/* !INET6 */

#ifdef INET6
	to_remote_talkd = -1;
	for (rres=his_machine_addrs; rres; rres=rres->ai_next) {
		if (!rres->ai_addr)
			continue;
		if (rres->ai_addr->sa_family != AF_INET &&
		    rres->ai_addr->sa_family != AF_INET6)
			continue;
		to_remote_talkd = socket(rres->ai_family, rres->ai_socktype, rres->ai_protocol);
		if (to_remote_talkd < 0)
			continue;
		if (connect(to_remote_talkd, rres->ai_addr, rres->ai_addrlen) < 0) {
			/* printf("%d, %s\n", rres->ai_family, strerror(errno)); */
			close(to_remote_talkd);
			to_remote_talkd = -1;
			continue;
		}
		remote_family = rres->ai_family;
		break;
	}
	freeaddrinfo(his_machine_addrs);
	his_machine_addrs = NULL;
	if (to_remote_talkd < 0) {
		p_error("Couldn't socket/bind/connect remote socket");
	}
#else	/* INET6 / !INET6 */
	to_remote_talkd = socket(((struct sockaddr *)&his_machine_addr)->sa_family, SOCK_DGRAM, 0);
	if (to_remote_talkd < 0) {
		p_error("Bad socket for remote talkd");
	}

#ifdef SO_BSDCOMPAT
	setsockopt(to_remote_talkd, SOL_SOCKET, SO_BSDCOMPAT, &on, sizeof(on));
#endif

	/*
	 * Now the trick - don't bind the remote socket. Instead
	 * just do a UDP connect on it to force it to talk to the 
	 * remote talkd. The neat side effect of this is that
	 * we can then get the correct local IP back from it
	 * with getsockname.
	 */
	memcpy(&rem, &his_machine_addr, sizeof(rem));
	rem.sin_port = daemon_port;
	if (connect(to_remote_talkd, (struct sockaddr *)&rem, sizeof(rem))<0) {
		p_error("Couldn't connect remote control socket");
	}
#endif	/* !INET6 */

	local_addrsize_for_remote = sizeof(local_addr_for_remote);
	if (getsockname(to_remote_talkd, (struct sockaddr *)&local_addr_for_remote, &local_addrsize_for_remote)<0) {
		p_error("getsockname");
	}
	switch(((struct sockaddr *)&local_addr_for_remote)->sa_family) {
	case AF_INET:
		((struct sockaddr_in *)&local_addr_for_remote)->sin_port = 0;
		break;
#ifdef INET6
	case AF_INET6:
		((struct sockaddr_in6 *)&local_addr_for_remote)->sin6_port = 0;
		break;
#endif
	default:
		p_error("getsockname (family)");
	}
}

static void
send_packet(char *msg, int len, int sock)
{
	int cc;
	cc = send(sock, msg, len, 0);
	if (cc<0 && errno == EINTR) {
		return;
	}
	else if (cc<0) {
	    p_error("Error on write to talk daemon");
	}
	else if (cc != len) {
	    p_error("Short write to talk daemon");
	}
}

static int
clean_up_packet(int sock, struct CtlMessage *msg, int type, char *buf, socklen_t buflen)
{
	socklen_t len;

	msg->vers = TALK_VERSION;
	msg->type = type;
	msg->answer = 0;
	msg->pad = 0;

	len = sizeof(msg->ctl_addr);
	if (getsockname(sock, (struct sockaddr *)&msg->ctl_addr, &len)<0) {
	    p_error("getsockname");
	}

	memcpy(&msg->addr, &local_addr_for_remote, local_addrsize_for_remote);
	switch(((struct sockaddr *)&msg->addr)->sa_family) {
	case AF_INET:
		((struct sockaddr_in *)&msg->addr)->sin_port = invitation_port;
		break;
#ifdef INET6
	case AF_INET6:
		((struct sockaddr_in6 *)&msg->addr)->sin6_port = invitation_port;
		break;
#endif
	}

	return (cm_export(msg, buf, buflen));
}

void
send_one_delete(int ismydaemon, int id)
{
	struct CtlMessage tmp = msg;
	char buf[CTL_MSG_SIZE];
	int len;
	int sock = ismydaemon ? to_local_talkd : to_remote_talkd;

	tmp.id_num = id;
	len = clean_up_packet(sock, &tmp, DELETE, buf, sizeof(buf));
	if (len <= 0) {
		p_error("sned_one_delete");
	}
	send_packet(buf, len, sock);
}

/*
 * SOCKDGRAM is unreliable, so we must repeat messages if we have
 * not received an acknowledgement within a reasonable amount
 * of time
 */
static void
do_transact(int sock, char *mesg, int len, int type, struct CtlResponse *rp)
{
	fd_set read_mask, ctl_mask;
	int nready=0, cc;
	struct timeval wait;
	int isok = 0;
	char rpbuf[CTL_RESPONSE_SIZE];

	FD_ZERO(&ctl_mask);
	FD_SET(sock, &ctl_mask);

	/*
	 * Keep sending the message until a response of
	 * the proper type is obtained.
	 */
	do {
		/* resend message until a response is obtained */
		do {
			send_packet(mesg, len, sock);
			read_mask = ctl_mask;
			wait.tv_sec = CTL_WAIT;
			wait.tv_usec = 0;
			nready = select(sock+1, &read_mask, 0, 0, &wait);
			if (nready < 0) {
				if (errno == EINTR)
					continue;
				p_error("Error waiting for daemon response");
			}
		} while (nready == 0);
		/*
		 * Keep reading while there are queued messages 
		 * (this is not necessary, it just saves extra
		 * request/acknowledgements being sent)
		 */
		do {
			cc = recv(sock, rpbuf, sizeof(rpbuf), 0);
			if (cc < 0) {
				if (errno == EINTR)
					continue;
				p_error("Error on read from talk daemon");
			}
			isok = cr_import(rpbuf, cc, rp);
			read_mask = ctl_mask;
			/* an immediate poll */
			timerclear(&wait);
			nready = select(sock+1, &read_mask, 0, 0, &wait);
		} while (isok < 0 && nready > 0 && (rp->vers != TALK_VERSION ||
		    rp->type != type));
	} while (isok < 0 && 
		 (rp->vers != TALK_VERSION || rp->type != type));
}

void
ctl_transact(int ismydaemon, struct CtlMessage mesg, int type, struct CtlResponse *rp)
{
	char buf[CTL_MSG_SIZE];
	int sock;
	int len;

	sock = ismydaemon ? to_local_talkd : to_remote_talkd;

	len = clean_up_packet(sock, &mesg, type, buf, sizeof(buf));
	if (len <= 0) {
		p_error("ctl_transact");
	}

	do_transact(sock, buf, len, type, rp);
}

