1 #include "communicator.h"
3 #include "streamsocket.h"
9 using namespace Msp::Net;
17 class HandshakeProtocol: public Protocol
23 HandshakeProtocol::HandshakeProtocol():
26 add<Handshake>(&Handshake::hash);
30 class HandshakeReceiver: public PacketReceiver<Handshake>
36 uint64_t get_hash() const { return hash; }
37 void receive(const Handshake &) override;
40 void HandshakeReceiver::receive(const Handshake &shake)
51 Communicator::Communicator(StreamSocket &s, const Protocol &p, ReceiverBase &r):
55 in_buf(new char[buf_size]),
58 out_buf(new char[buf_size])
60 socket.signal_data_available.connect(sigc::mem_fun(this, &Communicator::data_available));
63 Communicator::~Communicator()
69 void Communicator::initiate_handshake()
71 if(handshake_status!=0)
72 throw sequence_error("handshaking already done");
78 void Communicator::send_data(size_t size)
81 throw sequence_error("connection aborted");
82 if(handshake_status!=2)
83 throw sequence_error("handshake incomplete");
87 socket.write(out_buf, size);
89 catch(const std::exception &e)
92 if(signal_error.empty())
98 void Communicator::data_available()
105 in_end += socket.read(in_end, in_buf+buf_size-in_end);
110 if(handshake_status==2)
111 more = receive_packet(protocol, receiver);
114 HandshakeProtocol hsproto;
115 HandshakeReceiver hsrecv;
116 if((more = receive_packet(hsproto, hsrecv)))
118 if(handshake_status==0)
121 if(hsrecv.get_hash()==protocol.get_hash())
123 handshake_status = 2;
124 signal_handshake_done.emit();
127 throw incompatible_protocol("hash mismatch");
132 catch(const exception &e)
135 if(signal_error.empty())
137 signal_error.emit(e);
141 bool Communicator::receive_packet(const Protocol &proto, ReceiverBase &recv)
143 int psz = proto.get_packet_size(in_begin, in_end-in_begin);
144 if(psz && psz<=in_end-in_begin)
146 char *pkt = in_begin;
148 proto.dispatch(recv, pkt, psz);
153 if(in_end==in_buf+buf_size)
155 size_t used = in_end-in_begin;
156 memmove(in_buf, in_begin, used);
158 in_end = in_begin+used;
164 void Communicator::send_handshake()
167 shake.hash = protocol.get_hash();
169 HandshakeProtocol hsproto;
170 size_t size = hsproto.serialize(shake, out_buf, buf_size);
171 socket.write(out_buf, size);