sources/network/rconsession.cpp

Wed, 20 Jul 2016 13:25:54 +0300

author
Teemu Piippo <teemu@compsta2.com>
date
Wed, 20 Jul 2016 13:25:54 +0300
branch
protocol5
changeset 135
966c09c34ae1
parent 131
4996c8684b93
child 136
8fb1c657e0b0
permissions
-rw-r--r--

Removed the disconnection change in Interface::handle_input(), not sure where that even came from

/*
	Copyright 2014 - 2016 Teemu Piippo
	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 copyright holder 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 COPYRIGHT HOLDERS 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 COPYRIGHT HOLDER
	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.
*/

#include <time.h>
#include "rconsession.h"
#include "../interface.h"
BEGIN_ZFC_NAMESPACE

// -------------------------------------------------------------------------------------------------
//
RCONSession::RCONSession() :
	m_state (RCON_DISCONNECTED),
	m_lastPing (0),
	m_numAdmins (0),
	m_interface (nullptr)
{
	if (not m_socket.set_blocking (false))
	{
		fprintf (stderr, "unable to set socket as non-blocking: %s\n",
			m_socket.error_string().chars());
		exit (EXIT_FAILURE);
	}
}

// -------------------------------------------------------------------------------------------------
//
RCONSession::~RCONSession() {}

// -------------------------------------------------------------------------------------------------
//
void RCONSession::connect (IPAddress address)
{
	m_address = address;
	m_state = RCON_CONNECTING;
	m_interface->update_statusbar();
	send_hello();
}

// -------------------------------------------------------------------------------------------------
//
void RCONSession::disconnect()
{
	if (m_state > RCON_CONNECTING)
	{
		// Say goodbye to remote
		Bytestream packet;
		packet.write_byte (CLRC_DISCONNECT);
		this->send (packet);
		m_interface->disconnected();
	}

	m_state = RCON_DISCONNECTED;
}

// -------------------------------------------------------------------------------------------------
//
void RCONSession::send (const Bytestream& packet)
{
	m_socket.send (m_address, packet);
}

// -------------------------------------------------------------------------------------------------
//
void RCONSession::tick()
{
	if (m_state == RCON_DISCONNECTED)
		return;

	time_t now;
	time (&now);

	if (m_lastPing < now)
	{
		if (m_state == RCON_CONNECTING)
		{
			send_hello();
		}
		else if (m_state == RCON_AUTHENTICATING)
		{
			send_password();
		}
		else if (m_state == RCON_CONNECTED and m_lastPing + 5 < now)
		{
			Bytestream packet;
			packet.write_byte (CLRC_PONG);
			send (packet);
			bump_last_ping();
		}
	}

	for (Datagram datagram; m_socket.read (datagram);)
		handle_packet (datagram);
}

// -------------------------------------------------------------------------------------------------
//
void RCONSession::handle_packet (Datagram& datagram)
{
	if (datagram.from != m_address)
		return;

	try
	{
		Bytestream& packet = datagram.data;
		int32_t header = packet.read_long();
		int32_t sequenceNumber = (header != 0) ? packet.read_long() : 0;
		m_interface->print("Recieved packet with header 0x%x and sequence number #%d\n", header, sequenceNumber);

		while (packet.bytes_left() > 0)
		{
			int header = packet.read_byte();

			switch (ServerResponse (header))
			{
			case SVRC_OLDPROTOCOL:
				m_interface->print_error ("Your RCON client is using outdated protocol.\n");
				m_state = RCON_DISCONNECTED;
				break;

			case SVRC_BANNED:
				m_interface->print_error ("You have been banned from the server.\n");
				m_state = RCON_DISCONNECTED;
				break;

			case SVRC_SALT:
				m_salt = packet.read_string();
				m_state = RCON_AUTHENTICATING;
				send_password();
				break;

			case SVRC_INVALIDPASSWORD:
				m_interface->print_error ("Login failed.\n");
				m_state = RCON_DISCONNECTED;
				break;

			case SVRC_MESSAGE:
				{
					String message = packet.read_string();
					message.normalize();
					m_interface->print_text ("%s\n", message.chars());
				}
				break;

			case SVRC_LOGGEDIN:
				m_interface->print ("Login successful!\n");
				m_serverProtocol = packet.read_byte();
				m_hostname = packet.read_string();
				m_interface->set_title (m_hostname);
				m_state = RCON_CONNECTED;

				for (int i = packet.read_byte(); i > 0; --i)
					process_server_updates (packet);

				m_interface->print ("Previous messages:\n");

				for (int i = packet.read_byte(); i > 0; --i)
				{
					String message = packet.read_string();
					message.normalize();
					m_interface->print_text ("--- %s\n", message.chars());
				}

				m_interface->print ("End of previous messages.\n");

				// Watch sv_hostname so that we can update the titlebar when it changes.
				request_watch("sv_hostname");
				m_interface->print ("Watch requested.\n");
				break;

			case SVRC_UPDATE:
				process_server_updates (packet);
				break;

			case SVRC_TOOMANYTABCOMPLETES:
				{
					unsigned int numCompletions = packet.read_short();
					m_interface->print ("%d completions for '%s'.\n",
						int (numCompletions), m_lastTabComplete.chars());
				}
				break;

			case SVRC_TABCOMPLETE:
				{
					StringList completes;

					for (signed int i = packet.read_byte(); i > 0; --i)
						completes << packet.read_string();

					if (completes.size() == 1)
					{
						m_interface->tab_complete (m_lastTabComplete, completes[0]);
					}
					else if (not completes.is_empty())
					{
						m_interface->print ("Completions for '%s':\n", m_lastTabComplete.chars());

						for (int i = 0; i < completes.size(); i += 8)
						{
							Range<int> spliceRange (i, min (i + 8, completes.size() - 1));
							StringList splice (completes.splice (spliceRange));
							m_interface->print ("- %s\n", splice.join (", ").chars());
						}
					}
				}
				break;

			case SVRC_WATCHINGCVAR:
				m_interface->print ("You are now watching %s\n", packet.read_string().chars());
				m_interface->print ("Its value is: %s\n", packet.read_string().chars());
				break;

			case SVRC_ALREADYWATCHINGCVAR:
				m_interface->print ("You are already watching %s\n", packet.read_string().chars());
				break;

			case SVRC_WATCHCVARNOTFOUND:
				m_interface->print ("CVar %s not found\n", packet.read_string().chars());
				break;

			case SVRC_CVARCHANGED:
				{
					String name = packet.read_string();
					String value = packet.read_string();
					m_interface->print ("The value of CVar %s", name.chars());
					m_interface->print (" is now %s\n", value.chars());

					// If sv_hostname changes, update the titlebar
					if (name == "sv_hostname")
					{
						m_hostname = value;
						m_interface->set_title(m_hostname);
					}
				}
				break;

			case SVRC_YOUREDISCONNECTED:
				m_interface->print ("You have been disconnected: %s\n", packet.read_string().chars());
				m_interface->disconnected();
				break;
			}
		}
	}
	catch (std::exception& e)
	{
		m_interface->print_warning ("Couldn't process packet: %s\n", e.what());
	}
}

void RCONSession::process_server_updates (Bytestream& packet)
{
	int header = packet.read_byte();

	switch (RCONUpdateType (header))
	{
	case SVRCU_PLAYERDATA:
		{
			StringList players;

			for (int i = packet.read_byte(); i > 0; --i)
				players.append (packet.read_string());

			m_interface->set_player_names (players);
		}
		break;

	case SVRCU_ADMINCOUNT:
		m_numAdmins = packet.read_byte();
		m_interface->update_statusbar();
		break;

	case SVRCU_MAP:
		m_level = packet.read_string();
		m_interface->update_statusbar();
		break;

	default:
		m_interface->print_warning ("Unknown server update type: %d\n", header);
		break;
	}
}

// -------------------------------------------------------------------------------------------------
//
UDPSocket* RCONSession::socket()
{
	return &m_socket;
}

// -------------------------------------------------------------------------------------------------
//
void RCONSession::send_hello()
{
	m_interface->print ("Connecting to %s...\n",
		m_address.to_string (IPAddress::WITH_PORT).chars());
	Bytestream packet;
	packet.write_byte (CLRC_BEGINCONNECTION);
	packet.write_byte (RCON_PROTOCOL_VERSION);
	send (packet);
	bump_last_ping();
}

// -------------------------------------------------------------------------------------------------
//
void RCONSession::send_password()
{
	m_interface->print ("Authenticating...\n");
	Bytestream packet;
	packet.write_byte (CLRC_PASSWORD);
	packet.write_string ((m_salt + m_password).md5());
	send (packet);
	bump_last_ping();
}

// -------------------------------------------------------------------------------------------------
//
void RCONSession::set_password (const String& password)
{
	m_password = password;
}

// -------------------------------------------------------------------------------------------------
//
void RCONSession::bump_last_ping()
{
	time_t now;
	time (&now);
	m_lastPing = now;
}

// -------------------------------------------------------------------------------------------------
//
bool RCONSession::is_active() const
{
	return state() != RCON_DISCONNECTED;
}

// -------------------------------------------------------------------------------------------------
// Returns true if the message was successfully sent.
//
bool RCONSession::send_command (const String& message)
{
	if (m_state != RCON_CONNECTED or message.is_empty())
		return false;

	Bytestream packet;

	// Let's hardcode a /watch for CVar watching testing purposes
	if (message.starts_with ("/watch "))
	{
		request_watch(message.mid(String("/watch ").length(), -1).split(','));
	}
	else
	{
		packet.write_byte (CLRC_COMMAND);
		packet.write_string (message);
	}

	send (packet);
	bump_last_ping();
	return true;
}

// -------------------------------------------------------------------------------------------------
//
RCONSessionState RCONSession::state() const
{
	return m_state;
}

// -------------------------------------------------------------------------------------------------
//
const IPAddress& RCONSession::address() const
{
	return m_address;
}

// -------------------------------------------------------------------------------------------------
//
int RCONSession::num_admins() const
{
	return m_numAdmins;
}

// -------------------------------------------------------------------------------------------------
//
const String& RCONSession::level() const
{
	return m_level;
}

// -------------------------------------------------------------------------------------------------
//
void RCONSession::request_tab_complete (const String& part)
{
	if (m_serverProtocol >= 4)
	{
		Bytestream packet;
		packet.write_byte (CLRC_TABCOMPLETE);
		packet.write_string (part);
		send (packet);
		bump_last_ping();
		m_lastTabComplete = part;
	}
	else
	{
		m_interface->print ("This server does not support tab-completion\n", m_serverProtocol);
	}
}

// -------------------------------------------------------------------------------------------------
//
void RCONSession::set_interface (Interface* iface)
{
	m_interface = iface;
}

// -------------------------------------------------------------------------------------------------
//
void RCONSession::request_watch (const String& cvar)
{
	StringList cvars;
	cvars.append(cvar);
	request_watch(cvars);
}

// -------------------------------------------------------------------------------------------------
//
void RCONSession::request_watch (const StringList& cvars)
{
	Bytestream packet;
	packet.write_byte(CLRC_WATCHCVAR);

	for (int i = 0; i < cvars.size(); ++i)
		packet.write_string(cvars[i].normalized());

	packet.write_string("");
	send(packet);
}

END_ZFC_NAMESPACE

mercurial