-/* $Id$
-
-This file is part of libmspnet
-Copyright © 2009 Mikkosoft Productions, Mikko Rasa
-Distributed under the LGPL
-*/
-
#include <cstring>
#include "communicator.h"
void HandshakeReceiver::receive(const Handshake &shake)
{
- hash=shake.hash;
+ hash = shake.hash;
}
}
in_buf(new char[buf_size]),
in_begin(in_buf),
in_end(in_buf),
- out_buf(new char[buf_size])
+ out_buf(new char[buf_size]),
+ good(true)
{
socket.signal_data_available.connect(sigc::mem_fun(this, &Communicator::data_available));
}
void Communicator::initiate_handshake()
{
if(handshake_status!=0)
- throw InvalidState("Handshaking is already underway or done");
+ throw sequence_error("handshaking already done");
send_handshake();
- handshake_status=1;
+ handshake_status = 1;
}
void Communicator::data_available()
{
- in_end+=socket.read(in_end, in_buf+buf_size-in_end);
+ if(!good)
+ return;
+
+ in_end += socket.read(in_end, in_buf+buf_size-in_end);
try
{
- bool more=true;
+ bool more = true;
while(more)
{
if(handshake_status==2)
{
- more=receive_packet(protocol, receiver);
+ more = receive_packet(protocol, receiver);
}
else
{
HandshakeProtocol hsproto;
HandshakeReceiver hsrecv;
- if((more=receive_packet(hsproto, hsrecv)))
+ if((more = receive_packet(hsproto, hsrecv)))
{
if(hsrecv.get_hash()==protocol.get_hash())
{
if(handshake_status==0)
send_handshake();
- handshake_status=2;
+ handshake_status = 2;
signal_handshake_done.emit();
}
else
- socket.close();
+ good = false;
}
}
}
}
catch(...)
{
- socket.close();
+ good = false;
throw;
}
}
bool Communicator::receive_packet(const Protocol &proto, ReceiverBase &recv)
{
- int psz=proto.get_packet_size(in_begin, in_end-in_begin);
+ int psz = proto.get_packet_size(in_begin, in_end-in_begin);
if(psz && psz<=in_end-in_begin)
{
- char *pkt=in_begin;
- in_begin+=psz;
+ char *pkt = in_begin;
+ in_begin += psz;
proto.disassemble(recv, pkt, psz);
return true;
}
{
if(in_end==in_buf+buf_size)
{
- unsigned used=in_end-in_begin;
+ unsigned used = in_end-in_begin;
memmove(in_buf, in_begin, used);
- in_begin=in_buf;
- in_end=in_begin+used;
+ in_begin = in_buf;
+ in_end = in_begin+used;
}
return false;
}
void Communicator::send_handshake()
{
Handshake shake;
- shake.hash=protocol.get_hash();
+ shake.hash = protocol.get_hash();
HandshakeProtocol hsproto;
- unsigned size=hsproto.assemble(shake, out_buf, buf_size);
+ unsigned size = hsproto.assemble(shake, out_buf, buf_size);
socket.write(out_buf, size);
}