/*
 * server.c:  Things dealing with that wacky program we call ircd.
 *
 * Copyright 1990, 1999 Michael Sandrof and others
 * See the COPYRIGHT file for license information
 */

#define NEED_SERVER_LIST
#include "irc.h"
#include "parse.h"
#include "server.h"
#include "ircaux.h"
#include "lastlog.h"
#include "exec.h"
#include "window.h"
#include "output.h"
#include "names.h"
#include "hook.h"
#include "notify.h"
#include "screen.h"
#include "status.h"
#include "vars.h"
#include "newio.h"

/*
 * Note to future maintainers -- we do a bit of chicanery here.  The 'flags'
 * member in the server structure is assuemd to be at least N bits wide,
 * where N is the number of possible user modes.  Since the server stores
 * our user modes in a similar fashion, this shouldnt ever be "broken",
 * and if it is, we'll just change to do it however the server does.
 * The easiest way to handle that would be just to use an fd_set.
 *
 * 'umodes' here is a bogus default.  When we recieve the 004 numeric, it
 * overrides 'umodes'.
 *
 * The 'o' user mode is a special case, in that we want to know when its on.
 * This is mirrored in the "operator" member, for historical reasons.  This is
 * a kludge and should be changed.
 */
const 	char *	umodes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
static	char *	do_umode (int du_index);
	void 	reset_nickname (int);

	int	never_connected = 1;		/* true until first connection
						 * is made */
	int	connected_to_server = 0;	/* true when connection is
						 * confirmed */

static int 	connect_to_server (int new_server);
static int 	move_to_new_server (int new, int old);


/************************ SERVERLIST STUFF ***************************/

	Server	*server_list = (Server *) 0;
	int	number_of_servers = 0;

	int	primary_server = -1;
	int	from_server = -1;
	int	parsing_server_index = -1;
	int	last_server = -1;


/*
 * add_to_server_list: adds the given server to the server_list.  If the
 * server is already in the server list it is not re-added... however, if the
 * overwrite flag is true, the port and passwords are updated to the values
 * passes.  If the server is not on the list, it is added to the end. In
 * either case, the server is made the current server. 
 */
void 	add_to_server_list (const char *server, int port, const char *password, const char *nick, int overwrite)
{
	Server *s;

	if ((from_server = find_in_server_list(server, port)) == -1)
	{
		from_server = number_of_servers++;
		RESIZE(server_list, Server, number_of_servers);

		s = &server_list[from_server];
		s->name = m_strdup(server);
		s->itsname = (char *) 0;
		s->password = (char *) 0;
		s->away = (char *) 0;
		s->version_string = (char *) 0;
		s->server2_8 = 0;
		s->oper = 0;
		s->read = -1;
		s->write = -1;
		s->version = 0;
		s->flags = 0;
		s->flags2 = 0;
		s->nickname = (char *) 0;
		s->s_nickname = (char *) 0;
		s->d_nickname = (char *) 0;
		s->userhost = (char *) 0;
		s->connected = 0;
		s->eof = 0;
		s->motd = 1;
		s->port = port;
		s->who_queue = NULL;
		s->ison_queue = NULL;
		s->userhost_queue = NULL;
		s->local_addr.s_addr = 0;
		s->umodes = NULL;
		s->redirect = NULL;
		s->cookie = NULL;
		s->closing = 0;

		if (password && *password)
			malloc_strcpy(&s->password, password);
		if (nick && *nick)
			malloc_strcpy(&s->d_nickname, nick);
		else if (!s->d_nickname)
			malloc_strcpy(&s->d_nickname, nickname);
		malloc_strcpy(&s->umodes, umodes);

		make_notify_list(from_server);
		do_umode(from_server);
	}
	else
	{
		s = &server_list[from_server];

		if (overwrite)
		{
			s->port = port;
			if (password || !s->password)
			{
				if (password && *password)
					malloc_strcpy(&s->password, password);
				else
					new_free(&s->password);
			}
			if (nick || !s->d_nickname)
			{
				if (nick && *nick)
					malloc_strcpy(&s->d_nickname, nick);
				else
					new_free(&s->d_nickname);
			}
		}

		if (strlen(server) > strlen(s->name))
			malloc_strcpy(&s->name, server);
	}
}

static 	void 	remove_from_server_list (int i)
{
	Window	*tmp = NULL;
	Server  *s;

	if (i < 0 || i >= number_of_servers)
		return;

	say("Deleting server [%d]", i);
	clean_server_queues(i);

	s = &server_list[i];
	new_free(&s->name);
	new_free(&s->itsname);
	new_free(&s->password);
	new_free(&s->away);
	new_free(&s->version_string);
	new_free(&s->nickname);
	new_free(&s->s_nickname);
	new_free(&s->d_nickname);
	new_free(&s->userhost);
	new_free(&s->cookie);

	/* 
	 * this should save a coredump.  If number_of_servers drops
	 * down to zero, then trying to do a realloc ends up being
	 * a free, and accessing that is a no-no.
	 */
	if (number_of_servers == 1)
	{
		say("Sorry, the server list is empty and I just dont know what to do.");
		irc_exit(1, NULL);
	}

	memmove(&server_list[i], &server_list[i + 1], 
			(number_of_servers - i - 1) * sizeof(Server));
	number_of_servers--;
	RESIZE(server_list, Server, number_of_servers);

	/* update all he structs with server in them */
	channel_server_delete(i);
	exec_server_delete(i);
        if (i < primary_server)
                --primary_server;
        if (i < from_server)
                --from_server;
	while (traverse_all_windows(&tmp))
		if (tmp->server > i)
			tmp->server--;
}



/*
 * Given a hostname and a port number, this function returns the server_list
 * index for that server.  If the specified server is not in the server_list,
 * then -1 is returned.  This function makes an attempt to do smart name
 * completion so that if you ask for "irc", it returns the first server that
 * has the leading prefix of "irc" in it.
 */
int	find_in_server_list (const char *server, int port)
{
	int	i;

	for (i = 0; i < number_of_servers; i++)
	{
		/* Check the port first.  This is a cheap, easy check */
		if (port && server_list[i].port && 
				port != server_list[i].port && port != -1)
			continue;

#define MATCH_WITH_COMPLETION(n1, n2) 			\
{							\
	size_t l1 = strlen(n1);				\
	size_t l2 = strlen(n2);				\
	size_t l3 = l1 > l2 ? l2 : l1;			\
							\
	if (!my_strnicmp(n1, n2, l3))			\
		return i;				\
}

		MATCH_WITH_COMPLETION(server, server_list[i].name)
		if (!server_list[i].itsname)
			continue;
		MATCH_WITH_COMPLETION(server, server_list[i].itsname)
	}

	return -1;		/* Server was not found */
}

/*
 * Given a string that (in all likelihood) contains a server description
 * of the form:
 *
 *		refnum	 (where refnum is an integer for an existing server)
 * or
 *		hostname:port:password:nickname
 * or
 *		hostname port password nickname
 *
 * This extracts the salient information from the string and returns the
 * server_list index for that server.  If the information describes a server
 * that is not in the server_list, that information is *automatically added*
 * to the server_list and a new index is returned.
 *
 * This function always succeeds.
 */
int 	find_server_refnum (char *server, char **rest)
{
	int 	refnum;
	int	port = irc_port;
	char 	*cport = NULL, 
		*password = NULL,
		*nick = NULL;

	/*
	 * First of all, check for an existing server refnum
	 */
	if ((refnum = parse_server_index(server)) != -1)
		return refnum;

	/*
	 * Next check to see if its a "server:port:password:nick"
	 */
	else if (strchr(server, ':'))
		parse_server_info(server, &cport, &password, &nick);

	/*
	 * Next check to see if its "server port password nick"
	 */
	else if (rest && *rest)
	{
		cport = next_arg(*rest, rest);
		password = next_arg(*rest, rest);
		nick = next_arg(*rest, rest);
	}

	if (cport && *cport)
		port = my_atol(cport);

	/*
	 * Add to the server list (this will update the port
	 * and password fields).
	 */
	add_to_server_list(server, port, password, nick, 1);
	return from_server;
}


/*
 * parse_server_index:  given a string, this checks if it's a number, and if
 * so checks it validity as a server index.  Otherwise -1 is returned 
 */
int	parse_server_index (const char *str)
{
	int	i;

	if (is_number(str))
	{
		i = atoi(str);
		if ((i >= 0) && (i < number_of_servers))
			return (i);
	}
	return (-1);
}




/*
 * parse_server_info:  This parses a single string of the form
 * "server:portnum:password:nickname".  It the points port to the portnum
 * portion and password to the password portion.  This chews up the original
 * string, so * upon return, name will only point the the name.  If portnum
 * or password are missing or empty,  their respective returned value will
 * point to null. 
 */
void	parse_server_info (char *name, char **port, char **password, char **nick)
{
	char *ptr;

	*port = *password = *nick = NULL;
	if ((ptr = strchr(name, ':')) != NULL)
	{
		*ptr++ = 0;
		if (strlen(ptr) == 0)
			*port = (char *) 0;
		else
		{
			*port = ptr;
			if ((ptr = strchr(ptr, ':')) != NULL)
			{
				*ptr++ = 0;
				if (strlen(ptr) == 0)
					*password = '\0';
				else
				{
					*password = ptr;
					if ((ptr = strchr(ptr, ':')) != NULL)
					{
						*ptr++ = 0;
						if (!strlen(ptr))
							*nick = NULL;
						else
							*nick = ptr;
					}
				}
			}
		}
	}
}

/*
 * build_server_list: given a whitespace separated list of server names this
 * builds a list of those servers using add_to_server_list().  Since
 * add_to_server_list() is used to added each server specification, this can
 * be called many many times to add more servers to the server list.  Each
 * element in the server list case have one of the following forms: 
 *
 * servername 
 *
 * servername:port 
 *
 * servername:port:password 
 *
 * servername::password 
 *
 * Note also that this routine mucks around with the server string passed to it,
 * so make sure this is ok 
 */
void	build_server_list (char *servers)
{
	char	*host,
		*rest,
		*password = (char *) 0,
		*port = (char *) 0,
		*nick = (char *) 0;
	int	port_num;

	if (servers == (char *) 0)
		return;

	while (servers)
	{
		if ((rest = strchr(servers, '\n')) != NULL)
			*rest++ = '\0';
		while ((host = next_arg(servers, &servers)) != NULL)
		{
			parse_server_info(host, &port, &password, &nick);
                        if (port && *port)
                        {
                                port_num = my_atol(port);
                                if (!port_num)
                                        port_num = irc_port;
                        }
			else
				port_num = irc_port;

			add_to_server_list(host, port_num, password, nick, 0);
		}
		servers = rest;
	}
}

/*
 * read_server_file: reads hostname:portnum:password server information from
 * a file and adds this stuff to the server list.  See build_server_list()/ 
 */
int 	read_server_file (void)
{
	FILE 	*fp;
	char	file_path[MAXPATHLEN + 1];
	char	buffer[BIG_BUFFER_SIZE + 1];
	char	*expanded;

	if (getenv("IRC_SERVERS_FILE"))
		strmcpy(file_path, getenv("IRC_SERVERS_FILE"), MAXPATHLEN);
	else
	{
#ifdef SERVERS_FILE
		*file_path = 0;
		if (SERVERS_FILE[0] != '/')
			strmcpy(file_path, irc_lib, MAXPATHLEN);
		strmcat(file_path, SERVERS_FILE, MAXPATHLEN);
#else
		return 1;
#endif
	}

	expanded = expand_twiddle(file_path);
	if ((fp = fopen(expanded, "r")))
	{
		while (fgets(buffer, BIG_BUFFER_SIZE, fp))
		{
			chop(buffer, 1);
			build_server_list(buffer);
		}
		fclose(fp);
		new_free(&expanded);
		return (0);
	}

	new_free(&expanded);
	return 1;
}

/* display_server_list: just guess what this does */
void 	display_server_list (void)
{
	int	i;

	if (server_list)
	{
		if (from_server != -1)
			say("Current server: %s %d",
					server_list[from_server].name,
					server_list[from_server].port);
		else
			say("Current server: <None>");

		if (primary_server != -1)
			say("Primary server: %s %d",
				server_list[primary_server].name,
				server_list[primary_server].port);
		else
			say("Primary server: <None>");

		say("Server list:");
		for (i = 0; i < number_of_servers; i++)
		{
			if (!server_list[i].nickname)
			{
				if (server_list[i].read == -1)
					say("\t%d) %s %d", i,
						server_list[i].name,
						server_list[i].port);
				else
					say("\t%d) %s %d", i,
						server_list[i].name,
						server_list[i].port);
			}
			else
			{
				if (server_list[i].read == -1)
					say("\t%d) %s %d (was %s)", i,
						server_list[i].name,
						server_list[i].port,
						server_list[i].nickname);
				else
					say("\t%d) %s %d (%s)", i,
						server_list[i].name,
						server_list[i].port,
						server_list[i].nickname);
			}
		}
	}
	else
		say("The server list is empty");
}

char *	create_server_list (void)
{
	int	i;
	char 	buffer[BIG_BUFFER_SIZE + 1];

	*buffer = '\0';
	for (i = 0; i < number_of_servers; i++)
	{
		if (server_list[i].read != -1)
		{
			if (server_list[i].itsname)
			{
				strcat(buffer, server_list[i].itsname);
				strcat(buffer, space);
			}
			else
				yell("Warning: server_list[%d].itsname is null and it shouldnt be", i);
		}
	}

	return m_strdup(buffer);
}

/* server_list_size: returns the number of servers in the server list */
int 	server_list_size (void)
{
	return (number_of_servers);
}



/*************************** SERVER STUFF *************************/
/*
 * server: the /SERVER command. Read the SERVER help page about 
 */
BUILT_IN_COMMAND(servercmd)
{
	char	*server = NULL;
	int	i;

	if ((server = next_arg(args, &args)) == NULL)
	{
		display_server_list();
		return;
	}

	/*
	 * Delete an existing server
	 */
	if (strlen(server) > 1 && 
		!my_strnicmp(server, "-DELETE", strlen(server)))
	{
		if ((server = next_arg(args, &args)) == NULL)
		{
			say("Need server number for -DELETE");
			return;
		}

		if ((i = parse_server_index(server)) == -1 &&
		    (i = find_in_server_list(server, 0)) == -1)
		{
			say("No such server in list");
			return;
		}

		if (is_server_connected(i))
		{
			say("Can not delete server that is already open");
			return;
		}

		remove_from_server_list(i);
	}

	/*
	 * Add a server, but dont connect
	 */
	else if (strlen(server) > 1 && 
			!my_strnicmp(server, "-ADD", strlen(server)))
	{
		if (!(server = new_next_arg(args, &args)))
		{
			say("Need server info for -ADD");
			return;
		}

		find_server_refnum(server, &args);
	}

	/*
	 * The difference between /server +foo.bar.com  and
	 * /window server foo.bar.com is that this can support
	 * doing a server number.  That makes it a tad bit more
	 * difficult to parse, too. :P  They do the same thing,
	 * though.
	 */
	else if (*server == '+')
	{
		/* /SERVER +foo.bar.com is an alias for /window server */
		if (*++server)
		{
			i = find_server_refnum(server, &args);
			set_window_server(0, i, 0);
			if (!connect_to_new_server(i, -2))
				set_level_by_refnum(0, new_server_lastlog_level);
		}

		/* /SERVER + means go to the next server */
		else
			get_connected(from_server + 1, from_server);

		window_check_servers();
	}

	/*
	 * You can only detach a server using its refnum here.
	 */
	else if (*server == '-')
	{
		if (*++server)
		{
			i = find_server_refnum(server, &args);
			if (i == primary_server)
			{
			    say("You can't close your primary server!");
			    return;
			}
			server_list[i].reconnecting = 0;
			close_server(i, "closing server");
		}
		else
			get_connected(from_server -1, from_server);

		window_check_servers();
	}

	/*
	 * Just a naked /server with no flags
	 */
	else
	{
		int j = from_server;

		i = find_server_refnum(server, &args);
		connect_to_new_server(i, j);
		window_check_servers();
	}
}


/* SERVER INPUT STUFF */
/*
 * do_server: check the given fd_set against the currently open servers in
 * the server list.  If one have information available to be read, it is read
 * and and parsed appropriately.  If an EOF is detected from an open server,
 * one of two things occurs. 1) If the server was the primary server,
 * get_connected() is called to maintain the connection status of the user.
 * 2) If the server wasn't a primary server, connect_to_server() is called to
 * try to keep that connection alive. 
 */
void	do_server (fd_set *rd)
{
	char	buffer[IO_BUFFER_SIZE + 1];
	int	des,
		i;

	for (i = 0; i < number_of_servers; i++)
	{
		int	junk;
		char 	*bufptr = buffer;

		des = server_list[i].read;
		if (des == -1 || !FD_ISSET(des, rd))
			continue;

		last_server = from_server = i;
		switch ((junk = dgets(bufptr, des, 1)))
		{
			case 0:		/* Sit on incomplete lines */
				break;

			case -1:	/* EOF or other error */
			{
				int	sopen = is_server_connected(i);

				server_list[i].reconnecting = 1;
				close_server(i, empty_string);
				say("Connection closed from %s: %s", 
					server_list[i].name,
					(dgets_errno == -1) ? 
					     "Remote end closed connection" : 
					     strerror(dgets_errno));


				/*
				 * If we were never connected to the server,
				 * eg, they rejected us at registration time,
				 * then we will just move on to the next
				 * server in the list.
				 */
				if (sopen)
					get_connected(i, i);
				else
				{
					server_list[i].reconnecting = 0;
					get_connected(i + 1, i);
					i++;	/* mrj says this is needed */
				}
				break;
			}

			default:	/* New inbound data */
			{
				char *end;

				end = strlen(buffer) + buffer;
				if (*--end == '\n')
					*end-- = '\0';
				if (*end == '\r')
					*end-- = '\0';

				if (x_debug & DEBUG_INBOUND)
					yell("[%d] <- [%s]", 
						server_list[i].read, buffer);

				parsing_server_index = i;
				parse_server(buffer);
				parsing_server_index = -1;
				message_from(NULL, LOG_CRAP);
				break;
			}
		}
		from_server = primary_server;
	}

	/* Make sure primary_server is legit before we leave */
	if (primary_server == -1 || !is_server_connected(primary_server))
		window_check_servers();
}

/*
 * flush_server: eats all output from server, until there is at least a
 * second delay between bits of servers crap... useful to abort a /links. 
 * If you do this, you may lose JOINs/PARTs/QUITs, etc which have a severe
 * impact on the consistency of the client's internal data.
 *
 * XXXX - this is utterly useless at best, and pointless at worst.
 */
void 	flush_server (void)
{
	fd_set rd;
	struct timeval timeout;
	int	flushing = 1;
	int	des;
	char	buffer[IO_BUFFER_SIZE + 1];

	if ((des = server_list[from_server].read) == -1)
		return;
	timeout.tv_usec = 0;
	timeout.tv_sec = 1;
	while (flushing)
	{
		FD_ZERO(&rd);
		FD_SET(des, &rd);
		switch (new_select(&rd, (fd_set *) 0, &timeout))
		{
			case -1:
			case 0:
				flushing = 0;
				break;
			default:
			{
				if (FD_ISSET(des, &rd))
				{
					if (dgets(buffer, des, 0) == 0)
						flushing = 0;
				}
				break;
			}
		}
	}

	/* make sure we've read a full line from server */
	FD_ZERO(&rd);
	FD_SET(des, &rd);
	if (new_select(&rd, (fd_set *) 0, &timeout) > 0)
		dgets(buffer, des, 1);
}


/* SERVER OUTPUT STUFF */
static void 	vsend_to_server (const char *format, va_list args);

void	send_to_aserver (int refnum, const char *format, ...)
{
	int old_from_server = from_server;
	va_list args;

	from_server = refnum;
	va_start(args, format);
	vsend_to_server(format, args);
	va_end(args);
	from_server = old_from_server;
}

void	send_to_server (const char *format, ...)
{
	va_list args;
	va_start(args, format);
	vsend_to_server(format, args);
	va_end(args);
}

/* send_to_server: sends the given info the the server */
static void 	vsend_to_server (const char *format, va_list args)
{
	char	buffer[BIG_BUFFER_SIZE + 1];	/* make this buffer *much*
						 * bigger than needed */
	char	*buf = buffer;
	int	len,
		des;
	int	server;

	if ((server = from_server) == -1)
		server = primary_server;

	if (server != -1 && (des = server_list[server].write) != -1 && format)
	{
		len = vsnprintf(buf, BIG_BUFFER_SIZE, format, args);

		if (outbound_line_mangler)
			mangle_line(buf, outbound_line_mangler);

		server_list[server].sent = 1;
		if (len > (IRCD_BUFFER_SIZE - 2) || len == -1)
			buffer[IRCD_BUFFER_SIZE - 2] = (char) 0;
		if (x_debug & DEBUG_OUTBOUND)
			yell("[%d] -> [%s]", des, buffer);
		strmcat(buffer, "\r\n", IRCD_BUFFER_SIZE);
		if (do_hook(SEND_TO_SERVER_LIST, "%d %d %s", server, des, buffer))
		{
			if (write(des, buffer, strlen(buffer)) == -1 && (!get_int_var(NO_FAIL_DISCONNECT_VAR)))
			{
				say("Write to server failed.  Closing connection.");
				close_server(server, strerror(errno));
			}
		}
	}
	else if (from_server == -1)
        {
                if (do_hook(DISCONNECT_LIST,"No Connection to %d", server))
			say("You are not connected to a server, use /SERVER to connect.");
        }
}

void	clear_sent_to_server (int servnum)
{
	server_list[servnum].sent = 0;
}

int	sent_to_server (int servnum)
{
	return server_list[servnum].sent;
}


/* CONNECTION/RECONNECTION STRATEGIES */
/*
 * This establishes a new connection to 'new_server'.  This function does
 * not worry about why or where it is doing this.  It is only concerned
 * with getting a connection up and running.
 */
static int 	connect_to_server (int new_server)
{
	int 			des;
	struct sockaddr_in *	localaddr;
	int			len;
	unsigned short		this_sucks;
	Server 			*s;

	/*
	 * Can't connect to refnum -1, this is definitely an error.
	 */
	if (new_server == -1)
	{
		say ("Connecting to refnum -1.  That makes no sense.");
		return -1;		/* XXXX */
	}

	s = &server_list[new_server];

	/*
	 * If we are already connected to the new server, go with that.
	 */
	if (s->read != -1)
	{
		say("Connected to port %d of server %s", s->port, s->name);
		from_server = new_server;
		return 0;
	}

	/*
	 * Make an attempt to connect to the new server.
	 */
	say("Connecting to server port %d of server %s [refnum %d]", 
			s->port, s->name, new_server);

	s->closing = 0;
	oper_command = 0;
	errno = 0;
	localaddr = &s->local_sockname;
	memset(localaddr, 0, sizeof(*localaddr));

	this_sucks = (unsigned short)s->port;
	des = connect_by_number(s->name, &this_sucks,
					SERVICE_CLIENT, PROTOCOL_TCP);
	s->port = this_sucks;

	if (des < 0)
	{
		if (x_debug & DEBUG_SERVER_CONNECT)
			say("new_des is %d", des);

		say("Unable to connect to port %d of server %s: %s", 
				s->port, s->name, 
				errno ? strerror(errno) : "unknown host");
		return -1;
	}

	from_server = new_server;	/* XXX sigh */
	new_open(des);

	if (*s->name != '/')
	{
		len = sizeof(*localaddr);
		getsockname(des, (struct sockaddr *)localaddr, &len);
		s->local_addr.s_addr = localaddr->sin_addr.s_addr;
	}


	/*
	 * Initialize all of the server_list data items
	 * XXX - Calling add_to_server_list is a hack.
	 */
	add_to_server_list(s->name, s->port, NULL, NULL, 1);
	s->read = s->write = des;
	s->oper = 0;
	if (!s->d_nickname)
		malloc_strcpy(&s->d_nickname, nickname);

	/*
	 * Reset everything and go on our way.
	 */
	message_from((char *) 0, LOG_CRAP);
	update_all_status();
	return 0;
}


/*
 * This attempts to substitute a new connection to server 'new_server'
 * for the server connection 'old_server'.  
 * If 'old_server' is -1, then this is the first connection for the entire
 * 	client.  We have to handle this differently because no windows exist
 *	at this point and we have to be careful not to call 
 *	window_check_servers.
 * If 'old_server' is -2, then this is a new server connection on an existing
 * 	window.  This is used when a window "splits off" from an existing
 *	server connection to a new server.
 */
int 	connect_to_new_server (int new_server, int old_server)
{
	if (connect_to_server(new_server) == -1)
	{
		if (old_server >= 0 && server_list[old_server].read != -1)
			say("Connection to server %s resumed...", 
				server_list[old_server].name);

		return -1;
	}

	from_server = new_server;	/* XXX sigh */

	/*
	 * If it succeeds, and we're switching servers, then close the 
	 * old server off.
	 */
	if (old_server >= 0 && old_server != new_server)
	{
		/*
		 * We really are reconnecting here!  The reason why we
		 * set this is so that close_server marks all of the channels
		 * as being re-joinable.  Then when we call move_to_new_server 
		 * down below, all of the channels will move (or not move) to
		 * the new server, and be rejoined.
		 */
		server_list[old_server].reconnecting = 1;
		close_server(old_server, "changing servers");
	}

	/*
	 * And do a protocol registration
	 */
	if (!is_server_connected(new_server))
		register_server(new_server, server_list[new_server].d_nickname);
	if (old_server != -2)
		move_to_new_server(new_server, old_server);
	return 0;
}


/* This moves protocol information from 'old' server to 'new' server */
static int 	move_to_new_server (int new, int old)
{
	if (new == old)
		return 0;

	change_server_channels(old, new);
	change_window_server(old, new);
	if (!get_server_away(new) && get_server_away(old))
		set_server_away(new, get_server_away(old));

	return 0;
}

/*
 * This asks the client to make any attempt possible to connect to a new
 * server.  The 'old' server is presumably a server we are already connected
 * to.  The 'new' server is the server that we would prefer to connect to,
 * but of course any server will suffice if that doesn't work.
 */
int 	get_connected (int new, int old)
{
	int	i;
	int	j;

	if (!server_list)
	{
                if (do_hook(DISCONNECT_LIST, "No Server List"))
		    say("No server list. Use /SERVER to connect to a server");
		return -1;
	}

	for (i = 0; i < number_of_servers; i++)
	{
		j = (i + new) % number_of_servers;
		if (new != old && j == old)
			continue;
		if (connect_to_new_server(j, old) == 0)
			return 0;
	}

	if (do_hook(DISCONNECT_LIST, "Unable to connect to a server"))
		say("Sorry, cannot connect.  Use /SERVER to connect to a server");
	return -1;
}


int 	close_all_servers (const char *message)
{
	int i;

	for (i = 0; i < number_of_servers; i++)
	{
		server_list[i].reconnecting = 0;
		close_server(i, message);
	}

	return 0;
}

/*
 * close_server: Given an index into the server list, this closes the
 * connection to the corresponding server.  If 'message' is anything other
 * than the NULL or the empty_string, it will send a protocol QUIT message
 * to the server before closing the connection.
 */
void	close_server (int old, const char *message)
{
	/* Make sure server refnum is valid */
	if (old < 0 || old >= number_of_servers)
	{
		yell("Closing server [%d] makes no sense!", old);
		return;
	}

	if (server_list[old].read == -1)
		return;			/* Can't close server that isn't open */

	clean_server_queues(old);
	if (waiting_out > waiting_in)		/* XXX - hack! */
		waiting_out = waiting_in = 0;

	if (server_list[old].reconnecting)
		set_waiting_channel(old);
	else
		destroy_server_channels(old);

	server_list[old].reconnecting = 0;
	server_list[old].oper = 0;
	server_list[old].connected = 0;
	new_free(&server_list[old].nickname);
	new_free(&server_list[old].s_nickname);

	if (server_list[old].write != -1)
	{
		if (message && *message && !server_list[old].closing)
		{
		    server_list[old].closing = 1;
		    if (x_debug & DEBUG_OUTBOUND)
			yell("Closing server %d because [%s]", 
			   old, message ? message : empty_string);

		    send_to_aserver(old, "QUIT :%s\n", message);
		    do_hook(SERVER_LOST_LIST, "%d %s %s", 
				old, server_list[old].name, message);
		}

		server_list[old].write = new_close(server_list[old].write);
	}

	if (server_list[old].read != -1)
		server_list[old].read = new_close(server_list[old].read);

	return;
}

void 	save_server_channels (int servnum)
{
	server_list[servnum].reconnecting = 1;
}




/********************* OTHER STUFF ************************************/

/* AWAY STATUS */
/*
 * Encapsulates everything we need to change our AWAY status.
 * This improves greatly on having everyone peek into that member.
 * Also, we can deal centrally with someone changing their AWAY
 * message for a server when we're not connected to that server
 * (when we do connect, then we send out the AWAY command.)
 * All this saves a lot of headaches and crashes.
 */
void	set_server_away (int servnum, const char *message)
{
	if (servnum == -1)
		say("You are not connected to a server.");

	else if (message && *message)
	{
		if (server_list[servnum].away != message)
			malloc_strcpy(&server_list[servnum].away, message);
		if (server_list[servnum].connected)
			send_to_aserver(servnum, "AWAY :%s", message);
	}
	else
	{
		new_free(&server_list[servnum].away);
		if (server_list[servnum].connected)
			send_to_aserver(servnum, "AWAY :");
	}
}

const char *	get_server_away (int gsa_index)
{
	if (gsa_index == -2)
	{
		int	i;
		for (i = 0; i < number_of_servers; i++)
		{
			if (server_list[i].connected && server_list[i].away)
				return server_list[i].away;
		}
		return 0;
	}
	if (gsa_index < 0 || gsa_index >= number_of_servers)
		return NULL;
	
	return server_list[gsa_index].away;
}


/* USER MODES */
static char *do_umode (int du_index)
{
	char *c = server_list[du_index].umode;
	long flags = server_list[du_index].flags;
	long flags2 = server_list[du_index].flags2;
	int i;

	for (i = 0; server_list[du_index].umodes[i]; i++)
	{
		if (i > 31)
		{
			if (flags2 & (0x1 << (i - 32)))
				*c++ = server_list[du_index].umodes[i];
		}
		else
		{
			if (flags & (0x1 << i))
				*c++ = server_list[du_index].umodes[i];
		}
	}

	*c = '\0';
	return server_list[du_index].umode;
}

const char *	get_possible_umodes (int gu_index)
{
	if (gu_index == -1)
		gu_index = primary_server;
	else if (gu_index >= number_of_servers)
		return empty_string;

	return server_list[gu_index].umodes;
}

const char *	get_umode (int gu_index)
{
	if (gu_index == -1)
		gu_index = primary_server;
	else if (gu_index >= number_of_servers)
		return empty_string;

	return server_list[gu_index].umode;
}

void 	clear_user_modes (int gindex)
{
	if (gindex == -1)
		gindex = primary_server;
	else if (gindex >= number_of_servers)
		return;

	server_list[gindex].flags = 0;
	server_list[gindex].flags2 = 0;
	do_umode(gindex);
}

void	set_server_flag (int ssf_index, int flag, int value)
{
	if (ssf_index == -1)
		ssf_index = primary_server;
	else if (ssf_index >= number_of_servers)
		return;

	if (flag > 31)
	{
		if (value)
			server_list[ssf_index].flags2 |= 0x1 << (flag - 32);
		else
			server_list[ssf_index].flags2 &= ~(0x1 << (flag - 32));
	}
	else
	{
		if (value)
			server_list[ssf_index].flags |= 0x1 << flag;
		else
			server_list[ssf_index].flags &= ~(0x1 << flag);
	}

	do_umode(ssf_index);
}

int	get_server_flag (int gsf_index, int value)
{
	if (gsf_index == -1)
		gsf_index = primary_server;
	else if (gsf_index >= number_of_servers)
		return 0;

	if (value > 31)
		return server_list[gsf_index].flags2 & (0x1 << (value - 32));
	else
		return server_list[gsf_index].flags & (0x1 << value);
}

/* SERVER VERSIONS */
/*
 * set_server_version: Sets the server version for the given server type.  A
 * zero version means pre 2.6, a one version means 2.6 aso. (look server.h
 * for typedef)
 */
void	set_server_version (int ssv_index, int version)
{
	if (ssv_index == -1)
		ssv_index = primary_server;
	else if (ssv_index >= number_of_servers)
		return;
	server_list[ssv_index].version = version;
}

/*
 * get_server_version: returns the server version value for the given server
 * index 
 */
int	get_server_version (int gsv_index)
{
	if (gsv_index == -1)
		gsv_index = primary_server;
	else if (gsv_index >= number_of_servers)
		return 0;

	return (server_list[gsv_index].version);
}

/* SERVER NAMES */
/* get_server_name: returns the name for the given server index */
const char	*get_server_name (int gsn_index)
{
	if (gsn_index == -1)
		gsn_index = primary_server;
	else if (gsn_index == -1 || gsn_index >= number_of_servers)
		return empty_string;

	return (server_list[gsn_index].name);
}

/* get_server_itsname: returns the server's idea of its name */
const char	*get_server_itsname (int gsi_index)
{
	if (gsi_index==-1)
		gsi_index=primary_server;
	else if (gsi_index >= number_of_servers)
		return empty_string;

	/* better check gsi_index for -1 here CDE */
	if (gsi_index == -1)
		return empty_string;

	if (server_list[gsi_index].itsname)
		return server_list[gsi_index].itsname;
	else
		return server_list[gsi_index].name;
}

void	set_server_itsname (int ssi_index, const char *name)
{
	if (ssi_index==-1)
		ssi_index=primary_server;
	else if (ssi_index >= number_of_servers)
		return;

	malloc_strcpy(&server_list[ssi_index].itsname, name);
}

void	set_server_version_string (int servnum, const char *ver)
{
	malloc_strcpy(&server_list[servnum].version_string, ver);
}

const char *	get_server_version_string (int servnum)
{
	 return server_list[servnum].version_string;
}


/* CONNECTION/REGISTRATION STATUS */
void	register_server (int ssn_index, const char *nickname)
{
	if (server_list[ssn_index].password)
		send_to_aserver(ssn_index, "PASS %s", 
			server_list[ssn_index].password);

	send_to_aserver(ssn_index, "USER %s %s %s :%s", username, 
			(send_umode && *send_umode) ? send_umode : 
			(LocalHostName ? LocalHostName : hostname), 
			username, (*realname ? realname : space));
	change_server_nickname(ssn_index, nickname);
}

/*
 * password_sendline: called by send_line() in get_password() to handle
 * hitting of the return key, etc 
 * -- Callback function
 */
void 	password_sendline (char *data, char *line)
{
	int	new_server;

	if (line && *line)
	{
		new_server = atoi(next_arg(line, &line));
		set_server_password(new_server, line);
		connect_to_new_server(new_server, -2);
	}
}

/*
 * set_server_password: this sets the password for the server with the given
 * index.  If password is null, the password for the given server is returned 
 */
char	*set_server_password (int ssp_index, const char *password)
{
	if (server_list)
	{
		if (password)
		   malloc_strcpy(&(server_list[ssp_index].password), password);
		return (server_list[ssp_index].password);
	}
	else
		return ((char *) 0);
}


/*
 * is_server_open: Returns true if the given server index represents a server
 * with a live connection, returns false otherwise 
 */
int	is_server_open (int iso_index)
{
	if (iso_index < 0 || iso_index >= number_of_servers) 
		return (0);
	return (server_list[iso_index].read != -1);
}

/*
 * is_server_connected: returns true if the given server is connected.  This
 * means that both the tcp connection is open and the user is properly
 * registered 
 */
int	is_server_connected (int isc_index)
{
	if (isc_index >= 0 && isc_index < number_of_servers)
		return (server_list[isc_index].connected);
	return 0;
}

/*
 * Informs the client that the user is now officially registered or not
 * registered on the specified server.
 */
void 	server_is_connected (int sic_index, int value)
{
	if (sic_index < 0 || sic_index >= number_of_servers)
		return;

	server_list[sic_index].connected = value;
	if (value)
		server_list[sic_index].eof = 0;
}

BUILT_IN_COMMAND(disconnectcmd)
{
	char	*server;
	char	*message;
	int	i;

	if (!(server = next_arg(args, &args)))
		i = get_window_server(0);
	else
	{
		if ((i = parse_server_index(server)) == -1)
		{
			say("No such server!");
			return;
		}
	}

	if (i >= 0 && i < number_of_servers)
	{
		if (!args || !*args)
			message = "Disconnecting";
		else
			message = args;

		say("Disconnecting from server %s", get_server_itsname(i));
		close_server(i, message);
		window_check_servers();
	}

	if (!connected_to_server)
                if (do_hook(DISCONNECT_LIST, "Disconnected by user request"))
			say("You are not connected to a server, use /SERVER to connect.");
} 

int 	auto_reconnect_callback (void *d)
{
	char *stuff = (char *)d;
	servercmd(NULL, stuff, empty_string);
	new_free((char **)&d);
	return 0;
}



/* PORTS */
/* get_server_port: Returns the connection port for the given server index */
int	get_server_port (int gsp_index)
{
	if (gsp_index == -1)
		gsp_index = primary_server;
	else if (gsp_index >= number_of_servers)
		return 0;

	return (server_list[gsp_index].port);
}

int	get_server_local_port (int gsp_index)
{
	if (gsp_index == -1)
		gsp_index = primary_server;
	else if (gsp_index >= number_of_servers)
		return 0;

	return ntohs(server_list[gsp_index].local_sockname.sin_port);
}

struct in_addr	get_server_local_addr (int servnum)
{
	return server_list[servnum].local_addr;
}


/* USERHOST */
/*
 * get_server_userhost: return the userhost for this connection to server
 */
const char	*get_server_userhost (int gsu_index)
{
	if (gsu_index >= number_of_servers)
		return empty_string;
	else if (gsu_index != -1 && server_list[gsu_index].userhost)
		return (server_list[gsu_index].userhost);
	else
		return get_userhost();
}

/*
 * got_my_userhost -- callback function, XXXX doesnt belong here
 */
void 	got_my_userhost (UserhostItem *item, char *nick, char *stuff)
{
	new_free(&server_list[from_server].userhost);
	server_list[from_server].userhost = m_3dup(item->user, "@", item->host);
}



/* SERVER OPERATOR */
/*
 * get_server_operator: returns true if the user has op privs on the server,
 * false otherwise 
 */
int	get_server_operator (int gso_index)
{
	if ((gso_index < 0) || (gso_index >= number_of_servers))
		return 0;
	return (server_list[gso_index].oper);
}

/*
 * set_server_operator: If flag is non-zero, marks the user as having op
 * privs on the given server.  
 */
void	set_server_operator (int sso_index, int flag)
{
	if (sso_index < 0 || sso_index >= number_of_servers)
		return;

	server_list[sso_index].oper = flag;
	oper_command = 0;		/* No longer doing oper */
	do_umode(sso_index);
}



/* COOKIES */
void	set_server_cookie (int ssc_index, const char *cookie)
{
	if (server_list[ssc_index].cookie)
		send_to_aserver(ssc_index, "COOKIE %s", 
				server_list[ssc_index].cookie);
	malloc_strcpy(&server_list[ssc_index].cookie, cookie);
}

/* MOTD */
void 	set_server_motd (int ssm_index, int flag)
{
	if (ssm_index != -1 && ssm_index < number_of_servers)
		server_list[ssm_index].motd = flag;
}

int 	get_server_motd (int gsm_index)
{
	if (gsm_index != -1 && gsm_index < number_of_servers)
		return(server_list[gsm_index].motd);
	return (0);
}



/* NICKNAMES */
/*
 * get_server_nickname: returns the current nickname for the given server
 * index 
 */
const char	*get_server_nickname (int gsn_index)
{
	if (gsn_index >= number_of_servers)
		return empty_string;
	else if (gsn_index != -1 && server_list[gsn_index].nickname)
		return (server_list[gsn_index].nickname);
	else
		return "<not registered yet>";
}

int	is_me (int refnum, const char *nick)
{
	if (refnum == -1 && primary_server != -1)
		refnum = from_server;

	if (refnum >= number_of_servers || refnum < 0)
		return 0;

	if (server_list[refnum].nickname && nick)
		return !my_stricmp(nick, server_list[refnum].nickname);

	return 0;
}



/*
 * This is the function to attempt to make a nickname change.  You
 * cannot send the NICK command directly to the server: you must call
 * this function.  This function makes sure that the neccesary variables
 * are set so that if the NICK command fails, a sane action can be taken.
 *
 * If ``nick'' is NULL, then this function just tells the server what
 * we're trying to change our nickname to.  If we're not trying to change
 * our nickname, then this function does nothing.
 */
void	change_server_nickname (int ssn_index, const char *nick)
{
	Server *s = &server_list[ssn_index];
	char	*n;

	if (nick)
	{
		n = LOCAL_COPY(nick);
		if ((n = check_nickname(n)) != NULL)
		{
		    malloc_strcpy(&s->d_nickname, n);
		    malloc_strcpy(&s->s_nickname, n);
		}
		else
			reset_nickname(ssn_index);
	}

	if (s->s_nickname)
		send_to_aserver(ssn_index, "NICK %s", s->s_nickname);
}

const char *	get_pending_nickname (int servnum)
{
	return server_list[servnum].s_nickname;
}


void	accept_server_nickname (int ssn_index, const char *nick)
{
	malloc_strcpy(&server_list[ssn_index].nickname, nick);
	malloc_strcpy(&server_list[ssn_index].d_nickname, nick);
	new_free(&server_list[ssn_index].s_nickname);
	server_list[ssn_index].fudge_factor = 0;

	if (ssn_index == primary_server)
		strmcpy(nickname, nick, NICKNAME_LEN);

	update_all_status();
}

void	nick_command_is_pending (int servnum, int value)
{
	server_list[servnum].nickname_pending = value;
}

/* 
 * This will generate up to 18 nicknames plus the 9-length(nickname)
 * that are unique but still have some semblance of the original.
 * This is intended to allow the user to get signed back on to
 * irc after a nick collision without their having to manually
 * type a new nick every time..
 * 
 * The func will try to make an intelligent guess as to when it is
 * out of guesses, and if it ever gets to that point, it will do the
 * manually-ask-you-for-a-new-nickname thing.
 */
void 	fudge_nickname (int servnum)
{
	char 	l_nickname[NICKNAME_LEN + 1];
	Server *s = &server_list[servnum];

	/*
	 * If we got here because the user did a /NICK command, and
	 * the nick they chose doesnt exist, then we just dont do anything,
	 * we just cancel the pending action and give up.
	 */
	if (s->nickname_pending)
	{
		new_free(&s->s_nickname);
		return;
	}

	/*
	 * Ok.  So we're not doing a /NICK command, so we need to see
	 * if maybe we're doing some other type of NICK change.
	 */
	if (s->s_nickname)
		strcpy(l_nickname, s->s_nickname);
	else if (s->nickname)
		strcpy(l_nickname, s->nickname);
	else
		strcpy(l_nickname, nickname);


	if (s->fudge_factor < strlen(l_nickname))
		s->fudge_factor = strlen(l_nickname);
	else
	{
		if (++s->fudge_factor == 17)
		{
			/* give up... */
			reset_nickname(servnum);
			s->fudge_factor = 0;
			return;
		}
	}

	/* 
	 * Process of fudging a nickname:
	 * If the nickname length is less then 9, add an underscore.
	 */
	if (strlen(l_nickname) < 9)
		strcat(l_nickname, "_");

	/* 
	 * The nickname is 9 characters long. roll the nickname
	 */
	else
	{
		char tmp = l_nickname[8];
		l_nickname[8] = l_nickname[7]; l_nickname[7] = l_nickname[6];
		l_nickname[6] = l_nickname[5]; l_nickname[5] = l_nickname[4];
		l_nickname[4] = l_nickname[3]; l_nickname[3] = l_nickname[2];
		l_nickname[2] = l_nickname[1]; l_nickname[1] = l_nickname[0];
		l_nickname[0] = tmp;
	}

	/*
	 * This is the degenerate case
	 */
	if (!strcmp(l_nickname, "_________"))
	{
		reset_nickname(servnum);
		return;
	}

	change_server_nickname(servnum, l_nickname);
}


/*
 * -- Callback function
 */
void 	nickname_sendline (char *data, char *nick)
{
	int	new_server;

	new_server = atoi(data);
	change_server_nickname(new_server, nick);
}

/*
 * reset_nickname: when the server reports that the selected nickname is not
 * a good one, it gets reset here. 
 * -- Called by more than one place
 */
void 	reset_nickname (int servnum)
{
	char	server_num[10];

	kill(getpid(), SIGINT);		/* ??? Trap to gdb? ??? */
	say("You have specified an invalid nickname");
	if (!dumb_mode)
	{
		say("Please enter your nickname");
		strcpy(server_num, ltoa(servnum));
		add_wait_prompt("Nickname: ", nickname_sendline, server_num,
			WAIT_PROMPT_LINE, 1);
	}
	update_all_status();
}


/* REDIRECT STUFF */
void 	set_server_redirect (int s, const char *who)
{
	malloc_strcpy(&server_list[s].redirect, who);
}

const char *get_server_redirect (int s)
{
	return server_list[s].redirect;
}

int	check_server_redirect (const char *who)
{
	if (!who || !server_list[from_server].redirect)
		return 0;

	if (!strncmp(who, "***", 3) && 
	    !strcmp(who + 3, server_list[from_server].redirect))
	{
		set_server_redirect(from_server, NULL);
		return 1;
	}

	return 0;
}

