3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22 #include "connection.h"
23 #include "serialization.h"
26 #include "network/networkpacket.h"
27 #include "util/serialize.h"
28 #include "util/numeric.h"
29 #include "util/string.h"
36 /******************************************************************************/
37 /* defines used for debugging and profiling */
38 /******************************************************************************/
42 #undef DEBUG_CONNECTION_KBPS
44 /* this mutex is used to achieve log message consistency */
45 std::mutex log_message_mutex;
48 MutexAutoLock loglock(log_message_mutex); \
52 //#define DEBUG_CONNECTION_KBPS
53 #undef DEBUG_CONNECTION_KBPS
57 static inline float CALC_DTIME(u64 lasttime, u64 curtime)
59 float value = ( curtime - lasttime) / 1000.0;
60 return MYMAX(MYMIN(value,0.1),0.0);
63 #define MAX_UDP_PEERS 65535
65 #define PING_TIMEOUT 5.0
67 /* maximum number of retries for reliable packets */
68 #define MAX_RELIABLE_RETRY 5
70 static u16 readPeerId(u8 *packetdata)
72 return readU16(&packetdata[4]);
74 static u8 readChannel(u8 *packetdata)
76 return readU8(&packetdata[6]);
79 BufferedPacket makePacket(Address &address, u8 *data, u32 datasize,
80 u32 protocol_id, u16 sender_peer_id, u8 channel)
82 u32 packet_size = datasize + BASE_HEADER_SIZE;
83 BufferedPacket p(packet_size);
86 writeU32(&p.data[0], protocol_id);
87 writeU16(&p.data[4], sender_peer_id);
88 writeU8(&p.data[6], channel);
90 memcpy(&p.data[BASE_HEADER_SIZE], data, datasize);
95 BufferedPacket makePacket(Address &address, SharedBuffer<u8> &data,
96 u32 protocol_id, u16 sender_peer_id, u8 channel)
98 return makePacket(address, *data, data.getSize(),
99 protocol_id, sender_peer_id, channel);
102 SharedBuffer<u8> makeOriginalPacket(
103 SharedBuffer<u8> data)
106 u32 packet_size = data.getSize() + header_size;
107 SharedBuffer<u8> b(packet_size);
109 writeU8(&(b[0]), TYPE_ORIGINAL);
110 if (data.getSize() > 0) {
111 memcpy(&(b[header_size]), *data, data.getSize());
116 std::list<SharedBuffer<u8> > makeSplitPacket(
117 SharedBuffer<u8> data,
121 // Chunk packets, containing the TYPE_SPLIT header
122 std::list<SharedBuffer<u8> > chunks;
124 u32 chunk_header_size = 7;
125 u32 maximum_data_size = chunksize_max - chunk_header_size;
131 end = start + maximum_data_size - 1;
132 if (end > data.getSize() - 1)
133 end = data.getSize() - 1;
135 u32 payload_size = end - start + 1;
136 u32 packet_size = chunk_header_size + payload_size;
138 SharedBuffer<u8> chunk(packet_size);
140 writeU8(&chunk[0], TYPE_SPLIT);
141 writeU16(&chunk[1], seqnum);
142 // [3] u16 chunk_count is written at next stage
143 writeU16(&chunk[5], chunk_num);
144 memcpy(&chunk[chunk_header_size], &data[start], payload_size);
146 chunks.push_back(chunk);
152 while(end != data.getSize() - 1);
154 for(std::list<SharedBuffer<u8> >::iterator i = chunks.begin();
155 i != chunks.end(); ++i)
158 writeU16(&((*i)[3]), chunk_count);
164 std::list<SharedBuffer<u8> > makeAutoSplitPacket(
165 SharedBuffer<u8> data,
169 u32 original_header_size = 1;
170 std::list<SharedBuffer<u8> > list;
171 if (data.getSize() + original_header_size > chunksize_max)
173 list = makeSplitPacket(data, chunksize_max, split_seqnum);
179 list.push_back(makeOriginalPacket(data));
184 SharedBuffer<u8> makeReliablePacket(
185 SharedBuffer<u8> data,
189 u32 packet_size = data.getSize() + header_size;
190 SharedBuffer<u8> b(packet_size);
192 writeU8(&b[0], TYPE_RELIABLE);
193 writeU16(&b[1], seqnum);
195 memcpy(&b[header_size], *data, data.getSize());
204 void ReliablePacketBuffer::print()
206 MutexAutoLock listlock(m_list_mutex);
207 LOG(dout_con<<"Dump of ReliablePacketBuffer:" << std::endl);
208 unsigned int index = 0;
209 for(std::list<BufferedPacket>::iterator i = m_list.begin();
213 u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
214 LOG(dout_con<<index<< ":" << s << std::endl);
218 bool ReliablePacketBuffer::empty()
220 MutexAutoLock listlock(m_list_mutex);
221 return m_list.empty();
224 u32 ReliablePacketBuffer::size()
229 bool ReliablePacketBuffer::containsPacket(u16 seqnum)
231 return !(findPacket(seqnum) == m_list.end());
234 RPBSearchResult ReliablePacketBuffer::findPacket(u16 seqnum)
236 std::list<BufferedPacket>::iterator i = m_list.begin();
237 for(; i != m_list.end(); ++i)
239 u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
240 /*dout_con<<"findPacket(): finding seqnum="<<seqnum
241 <<", comparing to s="<<s<<std::endl;*/
247 RPBSearchResult ReliablePacketBuffer::notFound()
251 bool ReliablePacketBuffer::getFirstSeqnum(u16& result)
253 MutexAutoLock listlock(m_list_mutex);
256 BufferedPacket p = *m_list.begin();
257 result = readU16(&p.data[BASE_HEADER_SIZE+1]);
261 BufferedPacket ReliablePacketBuffer::popFirst()
263 MutexAutoLock listlock(m_list_mutex);
265 throw NotFoundException("Buffer is empty");
266 BufferedPacket p = *m_list.begin();
267 m_list.erase(m_list.begin());
270 if (m_list_size == 0) {
271 m_oldest_non_answered_ack = 0;
273 m_oldest_non_answered_ack =
274 readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]);
278 BufferedPacket ReliablePacketBuffer::popSeqnum(u16 seqnum)
280 MutexAutoLock listlock(m_list_mutex);
281 RPBSearchResult r = findPacket(seqnum);
282 if (r == notFound()) {
283 LOG(dout_con<<"Sequence number: " << seqnum
284 << " not found in reliable buffer"<<std::endl);
285 throw NotFoundException("seqnum not found in buffer");
287 BufferedPacket p = *r;
290 RPBSearchResult next = r;
292 if (next != notFound()) {
293 u16 s = readU16(&(next->data[BASE_HEADER_SIZE+1]));
294 m_oldest_non_answered_ack = s;
300 if (m_list_size == 0)
301 { m_oldest_non_answered_ack = 0; }
303 { m_oldest_non_answered_ack = readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]); }
306 void ReliablePacketBuffer::insert(BufferedPacket &p,u16 next_expected)
308 MutexAutoLock listlock(m_list_mutex);
309 if (p.data.getSize() < BASE_HEADER_SIZE + 3) {
310 errorstream << "ReliablePacketBuffer::insert(): Invalid data size for "
311 "reliable packet" << std::endl;
314 u8 type = readU8(&p.data[BASE_HEADER_SIZE + 0]);
315 if (type != TYPE_RELIABLE) {
316 errorstream << "ReliablePacketBuffer::insert(): type is not reliable"
320 u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE + 1]);
322 if (!seqnum_in_window(seqnum, next_expected, MAX_RELIABLE_WINDOW_SIZE)) {
323 errorstream << "ReliablePacketBuffer::insert(): seqnum is outside of "
324 "expected window " << std::endl;
327 if (seqnum == next_expected) {
328 errorstream << "ReliablePacketBuffer::insert(): seqnum is next expected"
334 sanity_check(m_list_size <= SEQNUM_MAX+1); // FIXME: Handle the error?
336 // Find the right place for the packet and insert it there
337 // If list is empty, just add it
341 m_oldest_non_answered_ack = seqnum;
346 // Otherwise find the right place
347 std::list<BufferedPacket>::iterator i = m_list.begin();
348 // Find the first packet in the list which has a higher seqnum
349 u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
351 /* case seqnum is smaller then next_expected seqnum */
352 /* this is true e.g. on wrap around */
353 if (seqnum < next_expected) {
354 while(((s < seqnum) || (s >= next_expected)) && (i != m_list.end())) {
356 if (i != m_list.end())
357 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
360 /* non wrap around case (at least for incoming and next_expected */
363 while(((s < seqnum) && (s >= next_expected)) && (i != m_list.end())) {
365 if (i != m_list.end())
366 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
372 (readU16(&(i->data[BASE_HEADER_SIZE+1])) != seqnum) ||
373 (i->data.getSize() != p.data.getSize()) ||
374 (i->address != p.address)
377 /* if this happens your maximum transfer window may be to big */
379 "Duplicated seqnum %d non matching packet detected:\n",
381 fprintf(stderr, "Old: seqnum: %05d size: %04d, address: %s\n",
382 readU16(&(i->data[BASE_HEADER_SIZE+1])),i->data.getSize(),
383 i->address.serializeString().c_str());
384 fprintf(stderr, "New: seqnum: %05d size: %04u, address: %s\n",
385 readU16(&(p.data[BASE_HEADER_SIZE+1])),p.data.getSize(),
386 p.address.serializeString().c_str());
387 throw IncomingDataCorruption("duplicated packet isn't same as original one");
390 /* nothing to do this seems to be a resent packet */
391 /* for paranoia reason data should be compared */
394 /* insert or push back */
395 else if (i != m_list.end()) {
402 /* update last packet number */
403 m_oldest_non_answered_ack = readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]);
406 void ReliablePacketBuffer::incrementTimeouts(float dtime)
408 MutexAutoLock listlock(m_list_mutex);
409 for(std::list<BufferedPacket>::iterator i = m_list.begin();
410 i != m_list.end(); ++i)
413 i->totaltime += dtime;
417 std::list<BufferedPacket> ReliablePacketBuffer::getTimedOuts(float timeout,
418 unsigned int max_packets)
420 MutexAutoLock listlock(m_list_mutex);
421 std::list<BufferedPacket> timed_outs;
422 for(std::list<BufferedPacket>::iterator i = m_list.begin();
423 i != m_list.end(); ++i)
425 if (i->time >= timeout) {
426 timed_outs.push_back(*i);
428 //this packet will be sent right afterwards reset timeout here
430 if (timed_outs.size() >= max_packets)
441 IncomingSplitBuffer::~IncomingSplitBuffer()
443 MutexAutoLock listlock(m_map_mutex);
444 for(std::map<u16, IncomingSplitPacket*>::iterator i = m_buf.begin();
445 i != m_buf.end(); ++i)
451 This will throw a GotSplitPacketException when a full
452 split packet is constructed.
454 SharedBuffer<u8> IncomingSplitBuffer::insert(BufferedPacket &p, bool reliable)
456 MutexAutoLock listlock(m_map_mutex);
457 u32 headersize = BASE_HEADER_SIZE + 7;
458 if (p.data.getSize() < headersize) {
459 errorstream << "Invalid data size for split packet" << std::endl;
460 return SharedBuffer<u8>();
462 u8 type = readU8(&p.data[BASE_HEADER_SIZE+0]);
463 u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]);
464 u16 chunk_count = readU16(&p.data[BASE_HEADER_SIZE+3]);
465 u16 chunk_num = readU16(&p.data[BASE_HEADER_SIZE+5]);
467 if (type != TYPE_SPLIT) {
468 errorstream << "IncomingSplitBuffer::insert(): type is not split"
470 return SharedBuffer<u8>();
473 // Add if doesn't exist
474 if (m_buf.find(seqnum) == m_buf.end())
476 IncomingSplitPacket *sp = new IncomingSplitPacket();
477 sp->chunk_count = chunk_count;
478 sp->reliable = reliable;
482 IncomingSplitPacket *sp = m_buf[seqnum];
484 // TODO: These errors should be thrown or something? Dunno.
485 if (chunk_count != sp->chunk_count)
486 LOG(derr_con<<"Connection: WARNING: chunk_count="<<chunk_count
487 <<" != sp->chunk_count="<<sp->chunk_count
489 if (reliable != sp->reliable)
490 LOG(derr_con<<"Connection: WARNING: reliable="<<reliable
491 <<" != sp->reliable="<<sp->reliable
494 // If chunk already exists, ignore it.
495 // Sometimes two identical packets may arrive when there is network
496 // lag and the server re-sends stuff.
497 if (sp->chunks.find(chunk_num) != sp->chunks.end())
498 return SharedBuffer<u8>();
500 // Cut chunk data out of packet
501 u32 chunkdatasize = p.data.getSize() - headersize;
502 SharedBuffer<u8> chunkdata(chunkdatasize);
503 memcpy(*chunkdata, &(p.data[headersize]), chunkdatasize);
505 // Set chunk data in buffer
506 sp->chunks[chunk_num] = chunkdata;
508 // If not all chunks are received, return empty buffer
509 if (sp->allReceived() == false)
510 return SharedBuffer<u8>();
512 // Calculate total size
514 for(std::map<u16, SharedBuffer<u8> >::iterator i = sp->chunks.begin();
515 i != sp->chunks.end(); ++i)
517 totalsize += i->second.getSize();
520 SharedBuffer<u8> fulldata(totalsize);
522 // Copy chunks to data buffer
524 for(u32 chunk_i=0; chunk_i<sp->chunk_count;
527 SharedBuffer<u8> buf = sp->chunks[chunk_i];
528 u16 chunkdatasize = buf.getSize();
529 memcpy(&fulldata[start], *buf, chunkdatasize);
530 start += chunkdatasize;;
533 // Remove sp from buffer
539 void IncomingSplitBuffer::removeUnreliableTimedOuts(float dtime, float timeout)
541 std::list<u16> remove_queue;
543 MutexAutoLock listlock(m_map_mutex);
544 for(std::map<u16, IncomingSplitPacket*>::iterator i = m_buf.begin();
545 i != m_buf.end(); ++i)
547 IncomingSplitPacket *p = i->second;
548 // Reliable ones are not removed by timeout
549 if (p->reliable == true)
552 if (p->time >= timeout)
553 remove_queue.push_back(i->first);
556 for(std::list<u16>::iterator j = remove_queue.begin();
557 j != remove_queue.end(); ++j)
559 MutexAutoLock listlock(m_map_mutex);
560 LOG(dout_con<<"NOTE: Removing timed out unreliable split packet"<<std::endl);
570 void ConnectionCommand::send(u16 peer_id_, u8 channelnum_, NetworkPacket *pkt,
575 channelnum = channelnum_;
576 data = pkt->oldForgePacket();
577 reliable = reliable_;
584 u16 Channel::readNextIncomingSeqNum()
586 MutexAutoLock internal(m_internal_mutex);
587 return next_incoming_seqnum;
590 u16 Channel::incNextIncomingSeqNum()
592 MutexAutoLock internal(m_internal_mutex);
593 u16 retval = next_incoming_seqnum;
594 next_incoming_seqnum++;
598 u16 Channel::readNextSplitSeqNum()
600 MutexAutoLock internal(m_internal_mutex);
601 return next_outgoing_split_seqnum;
603 void Channel::setNextSplitSeqNum(u16 seqnum)
605 MutexAutoLock internal(m_internal_mutex);
606 next_outgoing_split_seqnum = seqnum;
609 u16 Channel::getOutgoingSequenceNumber(bool& successful)
611 MutexAutoLock internal(m_internal_mutex);
612 u16 retval = next_outgoing_seqnum;
613 u16 lowest_unacked_seqnumber;
615 /* shortcut if there ain't any packet in outgoing list */
616 if (outgoing_reliables_sent.empty())
618 next_outgoing_seqnum++;
622 if (outgoing_reliables_sent.getFirstSeqnum(lowest_unacked_seqnumber))
624 if (lowest_unacked_seqnumber < next_outgoing_seqnum) {
625 // ugly cast but this one is required in order to tell compiler we
626 // know about difference of two unsigned may be negative in general
627 // but we already made sure it won't happen in this case
628 if (((u16)(next_outgoing_seqnum - lowest_unacked_seqnumber)) > window_size) {
634 // ugly cast but this one is required in order to tell compiler we
635 // know about difference of two unsigned may be negative in general
636 // but we already made sure it won't happen in this case
637 if ((next_outgoing_seqnum + (u16)(SEQNUM_MAX - lowest_unacked_seqnumber)) >
645 next_outgoing_seqnum++;
649 u16 Channel::readOutgoingSequenceNumber()
651 MutexAutoLock internal(m_internal_mutex);
652 return next_outgoing_seqnum;
655 bool Channel::putBackSequenceNumber(u16 seqnum)
657 if (((seqnum + 1) % (SEQNUM_MAX+1)) == next_outgoing_seqnum) {
659 next_outgoing_seqnum = seqnum;
665 void Channel::UpdateBytesSent(unsigned int bytes, unsigned int packets)
667 MutexAutoLock internal(m_internal_mutex);
668 current_bytes_transfered += bytes;
669 current_packet_successfull += packets;
672 void Channel::UpdateBytesReceived(unsigned int bytes) {
673 MutexAutoLock internal(m_internal_mutex);
674 current_bytes_received += bytes;
677 void Channel::UpdateBytesLost(unsigned int bytes)
679 MutexAutoLock internal(m_internal_mutex);
680 current_bytes_lost += bytes;
684 void Channel::UpdatePacketLossCounter(unsigned int count)
686 MutexAutoLock internal(m_internal_mutex);
687 current_packet_loss += count;
690 void Channel::UpdatePacketTooLateCounter()
692 MutexAutoLock internal(m_internal_mutex);
693 current_packet_too_late++;
696 void Channel::UpdateTimers(float dtime,bool legacy_peer)
698 bpm_counter += dtime;
699 packet_loss_counter += dtime;
701 if (packet_loss_counter > 1.0)
703 packet_loss_counter -= 1.0;
705 unsigned int packet_loss = 11; /* use a neutral value for initialization */
706 unsigned int packets_successfull = 0;
707 //unsigned int packet_too_late = 0;
709 bool reasonable_amount_of_data_transmitted = false;
712 MutexAutoLock internal(m_internal_mutex);
713 packet_loss = current_packet_loss;
714 //packet_too_late = current_packet_too_late;
715 packets_successfull = current_packet_successfull;
717 if (current_bytes_transfered > (unsigned int) (window_size*512/2))
719 reasonable_amount_of_data_transmitted = true;
721 current_packet_loss = 0;
722 current_packet_too_late = 0;
723 current_packet_successfull = 0;
726 /* dynamic window size is only available for non legacy peers */
728 float successfull_to_lost_ratio = 0.0;
731 if (packets_successfull > 0) {
732 successfull_to_lost_ratio = packet_loss/packets_successfull;
734 else if (packet_loss > 0)
738 MIN_RELIABLE_WINDOW_SIZE);
744 if ((successfull_to_lost_ratio < 0.01) &&
745 (window_size < MAX_RELIABLE_WINDOW_SIZE))
747 /* don't even think about increasing if we didn't even
748 * use major parts of our window */
749 if (reasonable_amount_of_data_transmitted)
752 MAX_RELIABLE_WINDOW_SIZE);
754 else if ((successfull_to_lost_ratio < 0.05) &&
755 (window_size < MAX_RELIABLE_WINDOW_SIZE))
757 /* don't even think about increasing if we didn't even
758 * use major parts of our window */
759 if (reasonable_amount_of_data_transmitted)
762 MAX_RELIABLE_WINDOW_SIZE);
764 else if (successfull_to_lost_ratio > 0.15)
768 MIN_RELIABLE_WINDOW_SIZE);
770 else if (successfull_to_lost_ratio > 0.1)
774 MIN_RELIABLE_WINDOW_SIZE);
780 if (bpm_counter > 10.0)
783 MutexAutoLock internal(m_internal_mutex);
785 (((float) current_bytes_transfered)/bpm_counter)/1024.0;
786 current_bytes_transfered = 0;
788 (((float) current_bytes_lost)/bpm_counter)/1024.0;
789 current_bytes_lost = 0;
791 (((float) current_bytes_received)/bpm_counter)/1024.0;
792 current_bytes_received = 0;
796 if (cur_kbps > max_kbps)
801 if (cur_kbps_lost > max_kbps_lost)
803 max_kbps_lost = cur_kbps_lost;
806 if (cur_incoming_kbps > max_incoming_kbps) {
807 max_incoming_kbps = cur_incoming_kbps;
810 rate_samples = MYMIN(rate_samples+1,10);
811 float old_fraction = ((float) (rate_samples-1) )/( (float) rate_samples);
812 avg_kbps = avg_kbps * old_fraction +
813 cur_kbps * (1.0 - old_fraction);
814 avg_kbps_lost = avg_kbps_lost * old_fraction +
815 cur_kbps_lost * (1.0 - old_fraction);
816 avg_incoming_kbps = avg_incoming_kbps * old_fraction +
817 cur_incoming_kbps * (1.0 - old_fraction);
826 PeerHelper::PeerHelper(Peer* peer) :
829 if (peer && !peer->IncUseCount())
833 PeerHelper::~PeerHelper()
836 m_peer->DecUseCount();
841 PeerHelper& PeerHelper::operator=(Peer* peer)
844 if (peer && !peer->IncUseCount())
849 Peer* PeerHelper::operator->() const
854 Peer* PeerHelper::operator&() const
859 bool PeerHelper::operator!() {
863 bool PeerHelper::operator!=(void* ptr)
865 return ((void*) m_peer != ptr);
868 bool Peer::IncUseCount()
870 MutexAutoLock lock(m_exclusive_access_mutex);
872 if (!m_pending_deletion) {
880 void Peer::DecUseCount()
883 MutexAutoLock lock(m_exclusive_access_mutex);
884 sanity_check(m_usage > 0);
887 if (!((m_pending_deletion) && (m_usage == 0)))
893 void Peer::RTTStatistics(float rtt, const std::string &profiler_id,
894 unsigned int num_samples) {
896 if (m_last_rtt > 0) {
897 /* set min max values */
898 if (rtt < m_rtt.min_rtt)
900 if (rtt >= m_rtt.max_rtt)
903 /* do average calculation */
904 if (m_rtt.avg_rtt < 0.0)
907 m_rtt.avg_rtt = m_rtt.avg_rtt * (num_samples/(num_samples-1)) +
908 rtt * (1/num_samples);
910 /* do jitter calculation */
912 //just use some neutral value at beginning
913 float jitter = m_rtt.jitter_min;
915 if (rtt > m_last_rtt)
916 jitter = rtt-m_last_rtt;
918 if (rtt <= m_last_rtt)
919 jitter = m_last_rtt - rtt;
921 if (jitter < m_rtt.jitter_min)
922 m_rtt.jitter_min = jitter;
923 if (jitter >= m_rtt.jitter_max)
924 m_rtt.jitter_max = jitter;
926 if (m_rtt.jitter_avg < 0.0)
927 m_rtt.jitter_avg = jitter;
929 m_rtt.jitter_avg = m_rtt.jitter_avg * (num_samples/(num_samples-1)) +
930 jitter * (1/num_samples);
932 if (profiler_id != "") {
933 g_profiler->graphAdd(profiler_id + "_rtt", rtt);
934 g_profiler->graphAdd(profiler_id + "_jitter", jitter);
937 /* save values required for next loop */
941 bool Peer::isTimedOut(float timeout)
943 MutexAutoLock lock(m_exclusive_access_mutex);
944 u64 current_time = porting::getTimeMs();
946 float dtime = CALC_DTIME(m_last_timeout_check,current_time);
947 m_last_timeout_check = current_time;
949 m_timeout_counter += dtime;
951 return m_timeout_counter > timeout;
957 MutexAutoLock usage_lock(m_exclusive_access_mutex);
958 m_pending_deletion = true;
963 PROFILE(std::stringstream peerIdentifier1);
964 PROFILE(peerIdentifier1 << "runTimeouts[" << m_connection->getDesc()
965 << ";" << id << ";RELIABLE]");
966 PROFILE(g_profiler->remove(peerIdentifier1.str()));
967 PROFILE(std::stringstream peerIdentifier2);
968 PROFILE(peerIdentifier2 << "sendPackets[" << m_connection->getDesc()
969 << ";" << id << ";RELIABLE]");
970 PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier2.str(), SPT_AVG));
975 UDPPeer::UDPPeer(u16 a_id, Address a_address, Connection* connection) :
976 Peer(a_address,a_id,connection)
980 bool UDPPeer::getAddress(MTProtocols type,Address& toset)
982 if ((type == MTP_UDP) || (type == MTP_MINETEST_RELIABLE_UDP) || (type == MTP_PRIMARY))
991 void UDPPeer::setNonLegacyPeer()
993 m_legacy_peer = false;
994 for(unsigned int i=0; i< CHANNEL_COUNT; i++)
996 channels->setWindowSize(g_settings->getU16("max_packets_per_iteration"));
1000 void UDPPeer::reportRTT(float rtt)
1005 RTTStatistics(rtt,"rudp",MAX_RELIABLE_WINDOW_SIZE*10);
1007 float timeout = getStat(AVG_RTT) * RESEND_TIMEOUT_FACTOR;
1008 if (timeout < RESEND_TIMEOUT_MIN)
1009 timeout = RESEND_TIMEOUT_MIN;
1010 if (timeout > RESEND_TIMEOUT_MAX)
1011 timeout = RESEND_TIMEOUT_MAX;
1013 MutexAutoLock usage_lock(m_exclusive_access_mutex);
1014 resend_timeout = timeout;
1017 bool UDPPeer::Ping(float dtime,SharedBuffer<u8>& data)
1019 m_ping_timer += dtime;
1020 if (m_ping_timer >= PING_TIMEOUT)
1022 // Create and send PING packet
1023 writeU8(&data[0], TYPE_CONTROL);
1024 writeU8(&data[1], CONTROLTYPE_PING);
1031 void UDPPeer::PutReliableSendCommand(ConnectionCommand &c,
1032 unsigned int max_packet_size)
1034 if (m_pending_disconnect)
1037 if ( channels[c.channelnum].queued_commands.empty() &&
1038 /* don't queue more packets then window size */
1039 (channels[c.channelnum].queued_reliables.size()
1040 < (channels[c.channelnum].getWindowSize()/2))) {
1041 LOG(dout_con<<m_connection->getDesc()
1042 <<" processing reliable command for peer id: " << c.peer_id
1043 <<" data size: " << c.data.getSize() << std::endl);
1044 if (!processReliableSendCommand(c,max_packet_size)) {
1045 channels[c.channelnum].queued_commands.push_back(c);
1049 LOG(dout_con<<m_connection->getDesc()
1050 <<" Queueing reliable command for peer id: " << c.peer_id
1051 <<" data size: " << c.data.getSize() <<std::endl);
1052 channels[c.channelnum].queued_commands.push_back(c);
1056 bool UDPPeer::processReliableSendCommand(
1057 ConnectionCommand &c,
1058 unsigned int max_packet_size)
1060 if (m_pending_disconnect)
1063 u32 chunksize_max = max_packet_size
1065 - RELIABLE_HEADER_SIZE;
1067 sanity_check(c.data.getSize() < MAX_RELIABLE_WINDOW_SIZE*512);
1069 std::list<SharedBuffer<u8> > originals;
1070 u16 split_sequence_number = channels[c.channelnum].readNextSplitSeqNum();
1074 originals.push_back(c.data);
1077 originals = makeAutoSplitPacket(c.data, chunksize_max,split_sequence_number);
1078 channels[c.channelnum].setNextSplitSeqNum(split_sequence_number);
1081 bool have_sequence_number = true;
1082 bool have_initial_sequence_number = false;
1083 std::queue<BufferedPacket> toadd;
1084 volatile u16 initial_sequence_number = 0;
1086 for(std::list<SharedBuffer<u8> >::iterator i = originals.begin();
1087 i != originals.end(); ++i)
1089 u16 seqnum = channels[c.channelnum].getOutgoingSequenceNumber(have_sequence_number);
1091 /* oops, we don't have enough sequence numbers to send this packet */
1092 if (!have_sequence_number)
1095 if (!have_initial_sequence_number)
1097 initial_sequence_number = seqnum;
1098 have_initial_sequence_number = true;
1101 SharedBuffer<u8> reliable = makeReliablePacket(*i, seqnum);
1103 // Add base headers and make a packet
1104 BufferedPacket p = con::makePacket(address, reliable,
1105 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1111 if (have_sequence_number) {
1112 volatile u16 pcount = 0;
1113 while(toadd.size() > 0) {
1114 BufferedPacket p = toadd.front();
1116 // LOG(dout_con<<connection->getDesc()
1117 // << " queuing reliable packet for peer_id: " << c.peer_id
1118 // << " channel: " << (c.channelnum&0xFF)
1119 // << " seqnum: " << readU16(&p.data[BASE_HEADER_SIZE+1])
1121 channels[c.channelnum].queued_reliables.push(p);
1124 sanity_check(channels[c.channelnum].queued_reliables.size() < 0xFFFF);
1128 volatile u16 packets_available = toadd.size();
1129 /* we didn't get a single sequence number no need to fill queue */
1130 if (!have_initial_sequence_number)
1134 while(toadd.size() > 0) {
1138 bool successfully_put_back_sequence_number
1139 = channels[c.channelnum].putBackSequenceNumber(
1140 (initial_sequence_number+toadd.size() % (SEQNUM_MAX+1)));
1142 FATAL_ERROR_IF(!successfully_put_back_sequence_number, "error");
1144 LOG(dout_con<<m_connection->getDesc()
1145 << " Windowsize exceeded on reliable sending "
1146 << c.data.getSize() << " bytes"
1147 << std::endl << "\t\tinitial_sequence_number: "
1148 << initial_sequence_number
1149 << std::endl << "\t\tgot at most : "
1150 << packets_available << " packets"
1151 << std::endl << "\t\tpackets queued : "
1152 << channels[c.channelnum].outgoing_reliables_sent.size()
1158 void UDPPeer::RunCommandQueues(
1159 unsigned int max_packet_size,
1160 unsigned int maxcommands,
1161 unsigned int maxtransfer)
1164 for (unsigned int i = 0; i < CHANNEL_COUNT; i++) {
1165 unsigned int commands_processed = 0;
1167 if ((channels[i].queued_commands.size() > 0) &&
1168 (channels[i].queued_reliables.size() < maxtransfer) &&
1169 (commands_processed < maxcommands)) {
1171 ConnectionCommand c = channels[i].queued_commands.front();
1173 LOG(dout_con << m_connection->getDesc()
1174 << " processing queued reliable command " << std::endl);
1176 // Packet is processed, remove it from queue
1177 if (processReliableSendCommand(c,max_packet_size)) {
1178 channels[i].queued_commands.pop_front();
1180 LOG(dout_con << m_connection->getDesc()
1181 << " Failed to queue packets for peer_id: " << c.peer_id
1182 << ", delaying sending of " << c.data.getSize()
1183 << " bytes" << std::endl);
1186 catch (ItemNotFoundException &e) {
1187 // intentionally empty
1193 u16 UDPPeer::getNextSplitSequenceNumber(u8 channel)
1195 assert(channel < CHANNEL_COUNT); // Pre-condition
1196 return channels[channel].readNextSplitSeqNum();
1199 void UDPPeer::setNextSplitSequenceNumber(u8 channel, u16 seqnum)
1201 assert(channel < CHANNEL_COUNT); // Pre-condition
1202 channels[channel].setNextSplitSeqNum(seqnum);
1205 SharedBuffer<u8> UDPPeer::addSpiltPacket(u8 channel,
1206 BufferedPacket toadd,
1209 assert(channel < CHANNEL_COUNT); // Pre-condition
1210 return channels[channel].incoming_splits.insert(toadd,reliable);
1213 /******************************************************************************/
1214 /* Connection Threads */
1215 /******************************************************************************/
1217 ConnectionSendThread::ConnectionSendThread(unsigned int max_packet_size,
1219 Thread("ConnectionSend"),
1220 m_max_packet_size(max_packet_size),
1222 m_max_data_packets_per_iteration(g_settings->getU16("max_packets_per_iteration"))
1226 void * ConnectionSendThread::run()
1228 assert(m_connection);
1230 LOG(dout_con<<m_connection->getDesc()
1231 <<"ConnectionSend thread started"<<std::endl);
1233 u64 curtime = porting::getTimeMs();
1234 u64 lasttime = curtime;
1236 PROFILE(std::stringstream ThreadIdentifier);
1237 PROFILE(ThreadIdentifier << "ConnectionSend: [" << m_connection->getDesc() << "]");
1239 /* if stop is requested don't stop immediately but try to send all */
1241 while(!stopRequested() || packetsQueued()) {
1242 BEGIN_DEBUG_EXCEPTION_HANDLER
1243 PROFILE(ScopeProfiler sp(g_profiler, ThreadIdentifier.str(), SPT_AVG));
1245 m_iteration_packets_avaialble = m_max_data_packets_per_iteration;
1247 /* wait for trigger or timeout */
1248 m_send_sleep_semaphore.wait(50);
1250 /* remove all triggers */
1251 while(m_send_sleep_semaphore.wait(0)) {}
1254 curtime = porting::getTimeMs();
1255 float dtime = CALC_DTIME(lasttime,curtime);
1257 /* first do all the reliable stuff */
1260 /* translate commands to packets */
1261 ConnectionCommand c = m_connection->m_command_queue.pop_frontNoEx(0);
1262 while(c.type != CONNCMD_NONE)
1265 processReliableCommand(c);
1267 processNonReliableCommand(c);
1269 c = m_connection->m_command_queue.pop_frontNoEx(0);
1272 /* send non reliable packets */
1275 END_DEBUG_EXCEPTION_HANDLER
1278 PROFILE(g_profiler->remove(ThreadIdentifier.str()));
1282 void ConnectionSendThread::Trigger()
1284 m_send_sleep_semaphore.post();
1287 bool ConnectionSendThread::packetsQueued()
1289 std::list<u16> peerIds = m_connection->getPeerIDs();
1291 if (!m_outgoing_queue.empty() && !peerIds.empty())
1294 for(std::list<u16>::iterator j = peerIds.begin();
1295 j != peerIds.end(); ++j)
1297 PeerHelper peer = m_connection->getPeerNoEx(*j);
1302 if (dynamic_cast<UDPPeer*>(&peer) == 0)
1305 for(u16 i=0; i < CHANNEL_COUNT; i++) {
1306 Channel *channel = &(dynamic_cast<UDPPeer*>(&peer))->channels[i];
1308 if (channel->queued_commands.size() > 0) {
1318 void ConnectionSendThread::runTimeouts(float dtime)
1320 std::list<u16> timeouted_peers;
1321 std::list<u16> peerIds = m_connection->getPeerIDs();
1323 for(std::list<u16>::iterator j = peerIds.begin();
1324 j != peerIds.end(); ++j)
1326 PeerHelper peer = m_connection->getPeerNoEx(*j);
1331 if (dynamic_cast<UDPPeer*>(&peer) == 0)
1334 PROFILE(std::stringstream peerIdentifier);
1335 PROFILE(peerIdentifier << "runTimeouts[" << m_connection->getDesc()
1336 << ";" << *j << ";RELIABLE]");
1337 PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier.str(), SPT_AVG));
1339 SharedBuffer<u8> data(2); // data for sending ping, required here because of goto
1344 if (peer->isTimedOut(m_timeout))
1346 infostream<<m_connection->getDesc()
1347 <<"RunTimeouts(): Peer "<<peer->id
1349 <<" (source=peer->timeout_counter)"
1351 // Add peer to the list
1352 timeouted_peers.push_back(peer->id);
1353 // Don't bother going through the buffers of this one
1357 float resend_timeout = dynamic_cast<UDPPeer*>(&peer)->getResendTimeout();
1358 bool retry_count_exceeded = false;
1359 for(u16 i=0; i<CHANNEL_COUNT; i++)
1361 std::list<BufferedPacket> timed_outs;
1362 Channel *channel = &(dynamic_cast<UDPPeer*>(&peer))->channels[i];
1364 if (dynamic_cast<UDPPeer*>(&peer)->getLegacyPeer())
1365 channel->setWindowSize(g_settings->getU16("workaround_window_size"));
1367 // Remove timed out incomplete unreliable split packets
1368 channel->incoming_splits.removeUnreliableTimedOuts(dtime, m_timeout);
1370 // Increment reliable packet times
1371 channel->outgoing_reliables_sent.incrementTimeouts(dtime);
1373 unsigned int numpeers = m_connection->m_peers.size();
1378 // Re-send timed out outgoing reliables
1379 timed_outs = channel->
1380 outgoing_reliables_sent.getTimedOuts(resend_timeout,
1381 (m_max_data_packets_per_iteration/numpeers));
1383 channel->UpdatePacketLossCounter(timed_outs.size());
1384 g_profiler->graphAdd("packets_lost", timed_outs.size());
1386 m_iteration_packets_avaialble -= timed_outs.size();
1388 for(std::list<BufferedPacket>::iterator k = timed_outs.begin();
1389 k != timed_outs.end(); ++k)
1391 u16 peer_id = readPeerId(*(k->data));
1392 u8 channelnum = readChannel(*(k->data));
1393 u16 seqnum = readU16(&(k->data[BASE_HEADER_SIZE+1]));
1395 channel->UpdateBytesLost(k->data.getSize());
1398 if (k-> resend_count > MAX_RELIABLE_RETRY) {
1399 retry_count_exceeded = true;
1400 timeouted_peers.push_back(peer->id);
1401 /* no need to check additional packets if a single one did timeout*/
1405 LOG(derr_con<<m_connection->getDesc()
1406 <<"RE-SENDING timed-out RELIABLE to "
1407 << k->address.serializeString()
1408 << "(t/o="<<resend_timeout<<"): "
1409 <<"from_peer_id="<<peer_id
1410 <<", channel="<<((int)channelnum&0xff)
1411 <<", seqnum="<<seqnum
1416 // do not handle rtt here as we can't decide if this packet was
1417 // lost or really takes more time to transmit
1420 if (retry_count_exceeded) {
1421 break; /* no need to check other channels if we already did timeout */
1424 channel->UpdateTimers(dtime,dynamic_cast<UDPPeer*>(&peer)->getLegacyPeer());
1427 /* skip to next peer if we did timeout */
1428 if (retry_count_exceeded)
1431 /* send ping if necessary */
1432 if (dynamic_cast<UDPPeer*>(&peer)->Ping(dtime,data)) {
1433 LOG(dout_con<<m_connection->getDesc()
1434 <<"Sending ping for peer_id: "
1435 << dynamic_cast<UDPPeer*>(&peer)->id <<std::endl);
1436 /* this may fail if there ain't a sequence number left */
1437 if (!rawSendAsPacket(dynamic_cast<UDPPeer*>(&peer)->id, 0, data, true))
1439 //retrigger with reduced ping interval
1440 dynamic_cast<UDPPeer*>(&peer)->Ping(4.0,data);
1444 dynamic_cast<UDPPeer*>(&peer)->RunCommandQueues(m_max_packet_size,
1445 m_max_commands_per_iteration,
1446 m_max_packets_requeued);
1449 // Remove timed out peers
1450 for(std::list<u16>::iterator i = timeouted_peers.begin();
1451 i != timeouted_peers.end(); ++i)
1453 LOG(derr_con<<m_connection->getDesc()
1454 <<"RunTimeouts(): Removing peer "<<(*i)<<std::endl);
1455 m_connection->deletePeer(*i, true);
1459 void ConnectionSendThread::rawSend(const BufferedPacket &packet)
1462 m_connection->m_udpSocket.Send(packet.address, *packet.data,
1463 packet.data.getSize());
1464 LOG(dout_con <<m_connection->getDesc()
1465 << " rawSend: " << packet.data.getSize()
1466 << " bytes sent" << std::endl);
1467 } catch(SendFailedException &e) {
1468 LOG(derr_con<<m_connection->getDesc()
1469 <<"Connection::rawSend(): SendFailedException: "
1470 <<packet.address.serializeString()<<std::endl);
1474 void ConnectionSendThread::sendAsPacketReliable(BufferedPacket& p, Channel* channel)
1477 p.absolute_send_time = porting::getTimeMs();
1478 // Buffer the packet
1479 channel->outgoing_reliables_sent.insert(p,
1480 (channel->readOutgoingSequenceNumber() - MAX_RELIABLE_WINDOW_SIZE)
1481 % (MAX_RELIABLE_WINDOW_SIZE+1));
1483 catch(AlreadyExistsException &e)
1485 LOG(derr_con<<m_connection->getDesc()
1486 <<"WARNING: Going to send a reliable packet"
1487 <<" in outgoing buffer" <<std::endl);
1494 bool ConnectionSendThread::rawSendAsPacket(u16 peer_id, u8 channelnum,
1495 SharedBuffer<u8> data, bool reliable)
1497 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
1499 LOG(dout_con<<m_connection->getDesc()
1500 <<" INFO: dropped packet for non existent peer_id: "
1501 << peer_id << std::endl);
1502 FATAL_ERROR_IF(!reliable, "Trying to send raw packet reliable but no peer found!");
1505 Channel *channel = &(dynamic_cast<UDPPeer*>(&peer)->channels[channelnum]);
1509 bool have_sequence_number_for_raw_packet = true;
1511 channel->getOutgoingSequenceNumber(have_sequence_number_for_raw_packet);
1513 if (!have_sequence_number_for_raw_packet)
1516 SharedBuffer<u8> reliable = makeReliablePacket(data, seqnum);
1517 Address peer_address;
1518 peer->getAddress(MTP_MINETEST_RELIABLE_UDP, peer_address);
1520 // Add base headers and make a packet
1521 BufferedPacket p = con::makePacket(peer_address, reliable,
1522 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1525 // first check if our send window is already maxed out
1526 if (channel->outgoing_reliables_sent.size()
1527 < channel->getWindowSize()) {
1528 LOG(dout_con<<m_connection->getDesc()
1529 <<" INFO: sending a reliable packet to peer_id " << peer_id
1530 <<" channel: " << channelnum
1531 <<" seqnum: " << seqnum << std::endl);
1532 sendAsPacketReliable(p,channel);
1536 LOG(dout_con<<m_connection->getDesc()
1537 <<" INFO: queueing reliable packet for peer_id: " << peer_id
1538 <<" channel: " << channelnum
1539 <<" seqnum: " << seqnum << std::endl);
1540 channel->queued_reliables.push(p);
1546 Address peer_address;
1548 if (peer->getAddress(MTP_UDP, peer_address))
1550 // Add base headers and make a packet
1551 BufferedPacket p = con::makePacket(peer_address, data,
1552 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1560 LOG(dout_con<<m_connection->getDesc()
1561 <<" INFO: dropped unreliable packet for peer_id: " << peer_id
1562 <<" because of (yet) missing udp address" << std::endl);
1571 void ConnectionSendThread::processReliableCommand(ConnectionCommand &c)
1573 assert(c.reliable); // Pre-condition
1577 LOG(dout_con<<m_connection->getDesc()
1578 <<"UDP processing reliable CONNCMD_NONE"<<std::endl);
1582 LOG(dout_con<<m_connection->getDesc()
1583 <<"UDP processing reliable CONNCMD_SEND"<<std::endl);
1587 case CONNCMD_SEND_TO_ALL:
1588 LOG(dout_con<<m_connection->getDesc()
1589 <<"UDP processing CONNCMD_SEND_TO_ALL"<<std::endl);
1590 sendToAllReliable(c);
1593 case CONCMD_CREATE_PEER:
1594 LOG(dout_con<<m_connection->getDesc()
1595 <<"UDP processing reliable CONCMD_CREATE_PEER"<<std::endl);
1596 if (!rawSendAsPacket(c.peer_id,c.channelnum,c.data,c.reliable))
1598 /* put to queue if we couldn't send it immediately */
1603 case CONCMD_DISABLE_LEGACY:
1604 LOG(dout_con<<m_connection->getDesc()
1605 <<"UDP processing reliable CONCMD_DISABLE_LEGACY"<<std::endl);
1606 if (!rawSendAsPacket(c.peer_id,c.channelnum,c.data,c.reliable))
1608 /* put to queue if we couldn't send it immediately */
1614 case CONNCMD_CONNECT:
1615 case CONNCMD_DISCONNECT:
1617 FATAL_ERROR("Got command that shouldn't be reliable as reliable command");
1619 LOG(dout_con<<m_connection->getDesc()
1620 <<" Invalid reliable command type: " << c.type <<std::endl);
1625 void ConnectionSendThread::processNonReliableCommand(ConnectionCommand &c)
1627 assert(!c.reliable); // Pre-condition
1631 LOG(dout_con<<m_connection->getDesc()
1632 <<" UDP processing CONNCMD_NONE"<<std::endl);
1635 LOG(dout_con<<m_connection->getDesc()
1636 <<" UDP processing CONNCMD_SERVE port="
1637 <<c.address.serializeString()<<std::endl);
1640 case CONNCMD_CONNECT:
1641 LOG(dout_con<<m_connection->getDesc()
1642 <<" UDP processing CONNCMD_CONNECT"<<std::endl);
1645 case CONNCMD_DISCONNECT:
1646 LOG(dout_con<<m_connection->getDesc()
1647 <<" UDP processing CONNCMD_DISCONNECT"<<std::endl);
1650 case CONNCMD_DISCONNECT_PEER:
1651 LOG(dout_con<<m_connection->getDesc()
1652 <<" UDP processing CONNCMD_DISCONNECT_PEER"<<std::endl);
1653 disconnect_peer(c.peer_id);
1656 LOG(dout_con<<m_connection->getDesc()
1657 <<" UDP processing CONNCMD_SEND"<<std::endl);
1658 send(c.peer_id, c.channelnum, c.data);
1660 case CONNCMD_SEND_TO_ALL:
1661 LOG(dout_con<<m_connection->getDesc()
1662 <<" UDP processing CONNCMD_SEND_TO_ALL"<<std::endl);
1663 sendToAll(c.channelnum, c.data);
1666 LOG(dout_con<<m_connection->getDesc()
1667 <<" UDP processing CONCMD_ACK"<<std::endl);
1668 sendAsPacket(c.peer_id,c.channelnum,c.data,true);
1670 case CONCMD_CREATE_PEER:
1671 FATAL_ERROR("Got command that should be reliable as unreliable command");
1673 LOG(dout_con<<m_connection->getDesc()
1674 <<" Invalid command type: " << c.type <<std::endl);
1678 void ConnectionSendThread::serve(Address bind_address)
1680 LOG(dout_con<<m_connection->getDesc()
1681 <<"UDP serving at port " << bind_address.serializeString() <<std::endl);
1683 m_connection->m_udpSocket.Bind(bind_address);
1684 m_connection->SetPeerID(PEER_ID_SERVER);
1686 catch(SocketException &e) {
1690 m_connection->putEvent(ce);
1694 void ConnectionSendThread::connect(Address address)
1696 LOG(dout_con<<m_connection->getDesc()<<" connecting to "<<address.serializeString()
1697 <<":"<<address.getPort()<<std::endl);
1699 UDPPeer *peer = m_connection->createServerPeer(address);
1703 e.peerAdded(peer->id, peer->address);
1704 m_connection->putEvent(e);
1708 if (address.isIPv6())
1709 bind_addr.setAddress((IPv6AddressBytes*) NULL);
1711 bind_addr.setAddress(0,0,0,0);
1713 m_connection->m_udpSocket.Bind(bind_addr);
1715 // Send a dummy packet to server with peer_id = PEER_ID_INEXISTENT
1716 m_connection->SetPeerID(PEER_ID_INEXISTENT);
1717 NetworkPacket pkt(0,0);
1718 m_connection->Send(PEER_ID_SERVER, 0, &pkt, true);
1721 void ConnectionSendThread::disconnect()
1723 LOG(dout_con<<m_connection->getDesc()<<" disconnecting"<<std::endl);
1725 // Create and send DISCO packet
1726 SharedBuffer<u8> data(2);
1727 writeU8(&data[0], TYPE_CONTROL);
1728 writeU8(&data[1], CONTROLTYPE_DISCO);
1732 std::list<u16> peerids = m_connection->getPeerIDs();
1734 for (std::list<u16>::iterator i = peerids.begin();
1738 sendAsPacket(*i, 0,data,false);
1742 void ConnectionSendThread::disconnect_peer(u16 peer_id)
1744 LOG(dout_con<<m_connection->getDesc()<<" disconnecting peer"<<std::endl);
1746 // Create and send DISCO packet
1747 SharedBuffer<u8> data(2);
1748 writeU8(&data[0], TYPE_CONTROL);
1749 writeU8(&data[1], CONTROLTYPE_DISCO);
1750 sendAsPacket(peer_id, 0,data,false);
1752 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
1757 if (dynamic_cast<UDPPeer*>(&peer) == 0)
1762 dynamic_cast<UDPPeer*>(&peer)->m_pending_disconnect = true;
1765 void ConnectionSendThread::send(u16 peer_id, u8 channelnum,
1766 SharedBuffer<u8> data)
1768 assert(channelnum < CHANNEL_COUNT); // Pre-condition
1770 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
1773 LOG(dout_con<<m_connection->getDesc()<<" peer: peer_id="<<peer_id
1774 << ">>>NOT<<< found on sending packet"
1775 << ", channel " << (channelnum % 0xFF)
1776 << ", size: " << data.getSize() <<std::endl);
1780 LOG(dout_con<<m_connection->getDesc()<<" sending to peer_id="<<peer_id
1781 << ", channel " << (channelnum % 0xFF)
1782 << ", size: " << data.getSize() <<std::endl);
1784 u16 split_sequence_number = peer->getNextSplitSequenceNumber(channelnum);
1786 u32 chunksize_max = m_max_packet_size - BASE_HEADER_SIZE;
1787 std::list<SharedBuffer<u8> > originals;
1789 originals = makeAutoSplitPacket(data, chunksize_max,split_sequence_number);
1791 peer->setNextSplitSequenceNumber(channelnum,split_sequence_number);
1793 for(std::list<SharedBuffer<u8> >::iterator i = originals.begin();
1794 i != originals.end(); ++i)
1796 SharedBuffer<u8> original = *i;
1797 sendAsPacket(peer_id, channelnum, original);
1801 void ConnectionSendThread::sendReliable(ConnectionCommand &c)
1803 PeerHelper peer = m_connection->getPeerNoEx(c.peer_id);
1807 peer->PutReliableSendCommand(c,m_max_packet_size);
1810 void ConnectionSendThread::sendToAll(u8 channelnum, SharedBuffer<u8> data)
1812 std::list<u16> peerids = m_connection->getPeerIDs();
1814 for (std::list<u16>::iterator i = peerids.begin();
1818 send(*i, channelnum, data);
1822 void ConnectionSendThread::sendToAllReliable(ConnectionCommand &c)
1824 std::list<u16> peerids = m_connection->getPeerIDs();
1826 for (std::list<u16>::iterator i = peerids.begin();
1830 PeerHelper peer = m_connection->getPeerNoEx(*i);
1835 peer->PutReliableSendCommand(c,m_max_packet_size);
1839 void ConnectionSendThread::sendPackets(float dtime)
1841 std::list<u16> peerIds = m_connection->getPeerIDs();
1842 std::list<u16> pendingDisconnect;
1843 std::map<u16,bool> pending_unreliable;
1845 for(std::list<u16>::iterator
1846 j = peerIds.begin();
1847 j != peerIds.end(); ++j)
1849 PeerHelper peer = m_connection->getPeerNoEx(*j);
1850 //peer may have been removed
1852 LOG(dout_con<<m_connection->getDesc()<< " Peer not found: peer_id=" << *j << std::endl);
1855 peer->m_increment_packets_remaining = m_iteration_packets_avaialble/m_connection->m_peers.size();
1857 if (dynamic_cast<UDPPeer*>(&peer) == 0)
1862 if (dynamic_cast<UDPPeer*>(&peer)->m_pending_disconnect)
1864 pendingDisconnect.push_back(*j);
1867 PROFILE(std::stringstream peerIdentifier);
1868 PROFILE(peerIdentifier << "sendPackets[" << m_connection->getDesc() << ";" << *j << ";RELIABLE]");
1869 PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier.str(), SPT_AVG));
1871 LOG(dout_con<<m_connection->getDesc()
1872 << " Handle per peer queues: peer_id=" << *j
1873 << " packet quota: " << peer->m_increment_packets_remaining << std::endl);
1874 // first send queued reliable packets for all peers (if possible)
1875 for (unsigned int i=0; i < CHANNEL_COUNT; i++)
1877 u16 next_to_ack = 0;
1878 dynamic_cast<UDPPeer*>(&peer)->channels[i].outgoing_reliables_sent.getFirstSeqnum(next_to_ack);
1879 u16 next_to_receive = 0;
1880 dynamic_cast<UDPPeer*>(&peer)->channels[i].incoming_reliables.getFirstSeqnum(next_to_receive);
1882 LOG(dout_con<<m_connection->getDesc()<< "\t channel: "
1883 << i << ", peer quota:"
1884 << peer->m_increment_packets_remaining
1886 << "\t\t\treliables on wire: "
1887 << dynamic_cast<UDPPeer*>(&peer)->channels[i].outgoing_reliables_sent.size()
1888 << ", waiting for ack for " << next_to_ack
1890 << "\t\t\tincoming_reliables: "
1891 << dynamic_cast<UDPPeer*>(&peer)->channels[i].incoming_reliables.size()
1892 << ", next reliable packet: "
1893 << dynamic_cast<UDPPeer*>(&peer)->channels[i].readNextIncomingSeqNum()
1894 << ", next queued: " << next_to_receive
1896 << "\t\t\treliables queued : "
1897 << dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.size()
1899 << "\t\t\tqueued commands : "
1900 << dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_commands.size()
1903 while ((dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.size() > 0) &&
1904 (dynamic_cast<UDPPeer*>(&peer)->channels[i].outgoing_reliables_sent.size()
1905 < dynamic_cast<UDPPeer*>(&peer)->channels[i].getWindowSize())&&
1906 (peer->m_increment_packets_remaining > 0))
1908 BufferedPacket p = dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.front();
1909 dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.pop();
1910 Channel* channel = &(dynamic_cast<UDPPeer*>(&peer)->channels[i]);
1911 LOG(dout_con<<m_connection->getDesc()
1912 <<" INFO: sending a queued reliable packet "
1914 <<", seqnum: " << readU16(&p.data[BASE_HEADER_SIZE+1])
1916 sendAsPacketReliable(p,channel);
1917 peer->m_increment_packets_remaining--;
1922 if (m_outgoing_queue.size())
1924 LOG(dout_con<<m_connection->getDesc()
1925 << " Handle non reliable queue ("
1926 << m_outgoing_queue.size() << " pkts)" << std::endl);
1929 unsigned int initial_queuesize = m_outgoing_queue.size();
1930 /* send non reliable packets*/
1931 for(unsigned int i=0;i < initial_queuesize;i++) {
1932 OutgoingPacket packet = m_outgoing_queue.front();
1933 m_outgoing_queue.pop();
1935 if (packet.reliable)
1938 PeerHelper peer = m_connection->getPeerNoEx(packet.peer_id);
1940 LOG(dout_con<<m_connection->getDesc()
1941 <<" Outgoing queue: peer_id="<<packet.peer_id
1942 << ">>>NOT<<< found on sending packet"
1943 << ", channel " << (packet.channelnum % 0xFF)
1944 << ", size: " << packet.data.getSize() <<std::endl);
1947 /* send acks immediately */
1948 else if (packet.ack)
1950 rawSendAsPacket(packet.peer_id, packet.channelnum,
1951 packet.data, packet.reliable);
1952 peer->m_increment_packets_remaining =
1953 MYMIN(0,peer->m_increment_packets_remaining--);
1956 ( peer->m_increment_packets_remaining > 0) ||
1957 (stopRequested())) {
1958 rawSendAsPacket(packet.peer_id, packet.channelnum,
1959 packet.data, packet.reliable);
1960 peer->m_increment_packets_remaining--;
1963 m_outgoing_queue.push(packet);
1964 pending_unreliable[packet.peer_id] = true;
1968 for(std::list<u16>::iterator
1969 k = pendingDisconnect.begin();
1970 k != pendingDisconnect.end(); ++k)
1972 if (!pending_unreliable[*k])
1974 m_connection->deletePeer(*k,false);
1979 void ConnectionSendThread::sendAsPacket(u16 peer_id, u8 channelnum,
1980 SharedBuffer<u8> data, bool ack)
1982 OutgoingPacket packet(peer_id, channelnum, data, false, ack);
1983 m_outgoing_queue.push(packet);
1986 ConnectionReceiveThread::ConnectionReceiveThread(unsigned int max_packet_size) :
1987 Thread("ConnectionReceive")
1991 void * ConnectionReceiveThread::run()
1993 assert(m_connection);
1995 LOG(dout_con<<m_connection->getDesc()
1996 <<"ConnectionReceive thread started"<<std::endl);
1998 PROFILE(std::stringstream ThreadIdentifier);
1999 PROFILE(ThreadIdentifier << "ConnectionReceive: [" << m_connection->getDesc() << "]");
2001 #ifdef DEBUG_CONNECTION_KBPS
2002 u64 curtime = porting::getTimeMs();
2003 u64 lasttime = curtime;
2004 float debug_print_timer = 0.0;
2007 while(!stopRequested()) {
2008 BEGIN_DEBUG_EXCEPTION_HANDLER
2009 PROFILE(ScopeProfiler sp(g_profiler, ThreadIdentifier.str(), SPT_AVG));
2011 #ifdef DEBUG_CONNECTION_KBPS
2013 curtime = porting::getTimeMs();
2014 float dtime = CALC_DTIME(lasttime,curtime);
2017 /* receive packets */
2020 #ifdef DEBUG_CONNECTION_KBPS
2021 debug_print_timer += dtime;
2022 if (debug_print_timer > 20.0) {
2023 debug_print_timer -= 20.0;
2025 std::list<u16> peerids = m_connection->getPeerIDs();
2027 for (std::list<u16>::iterator i = peerids.begin();
2031 PeerHelper peer = m_connection->getPeerNoEx(*i);
2035 float peer_current = 0.0;
2036 float peer_loss = 0.0;
2037 float avg_rate = 0.0;
2038 float avg_loss = 0.0;
2040 for(u16 j=0; j<CHANNEL_COUNT; j++)
2042 peer_current +=peer->channels[j].getCurrentDownloadRateKB();
2043 peer_loss += peer->channels[j].getCurrentLossRateKB();
2044 avg_rate += peer->channels[j].getAvgDownloadRateKB();
2045 avg_loss += peer->channels[j].getAvgLossRateKB();
2048 std::stringstream output;
2049 output << std::fixed << std::setprecision(1);
2050 output << "OUT to Peer " << *i << " RATES (good / loss) " << std::endl;
2051 output << "\tcurrent (sum): " << peer_current << "kb/s "<< peer_loss << "kb/s" << std::endl;
2052 output << "\taverage (sum): " << avg_rate << "kb/s "<< avg_loss << "kb/s" << std::endl;
2053 output << std::setfill(' ');
2054 for(u16 j=0; j<CHANNEL_COUNT; j++)
2056 output << "\tcha " << j << ":"
2057 << " CUR: " << std::setw(6) << peer->channels[j].getCurrentDownloadRateKB() <<"kb/s"
2058 << " AVG: " << std::setw(6) << peer->channels[j].getAvgDownloadRateKB() <<"kb/s"
2059 << " MAX: " << std::setw(6) << peer->channels[j].getMaxDownloadRateKB() <<"kb/s"
2061 << " CUR: " << std::setw(6) << peer->channels[j].getCurrentLossRateKB() <<"kb/s"
2062 << " AVG: " << std::setw(6) << peer->channels[j].getAvgLossRateKB() <<"kb/s"
2063 << " MAX: " << std::setw(6) << peer->channels[j].getMaxLossRateKB() <<"kb/s"
2064 << " / WS: " << peer->channels[j].getWindowSize()
2068 fprintf(stderr,"%s\n",output.str().c_str());
2072 END_DEBUG_EXCEPTION_HANDLER
2075 PROFILE(g_profiler->remove(ThreadIdentifier.str()));
2079 // Receive packets from the network and buffers and create ConnectionEvents
2080 void ConnectionReceiveThread::receive()
2082 // use IPv6 minimum allowed MTU as receive buffer size as this is
2083 // theoretical reliable upper boundary of a udp packet for all IPv6 enabled
2085 unsigned int packet_maxsize = 1500;
2086 SharedBuffer<u8> packetdata(packet_maxsize);
2088 bool packet_queued = true;
2090 unsigned int loop_count = 0;
2092 /* first of all read packets from socket */
2093 /* check for incoming data available */
2094 while( (loop_count < 10) &&
2095 (m_connection->m_udpSocket.WaitData(50))) {
2098 if (packet_queued) {
2099 bool data_left = true;
2101 SharedBuffer<u8> resultdata;
2104 data_left = getFromBuffers(peer_id, resultdata);
2107 e.dataReceived(peer_id, resultdata);
2108 m_connection->putEvent(e);
2111 catch(ProcessedSilentlyException &e) {
2112 /* try reading again */
2115 packet_queued = false;
2119 s32 received_size = m_connection->m_udpSocket.Receive(sender, *packetdata, packet_maxsize);
2121 if ((received_size < BASE_HEADER_SIZE) ||
2122 (readU32(&packetdata[0]) != m_connection->GetProtocolID()))
2124 LOG(derr_con<<m_connection->getDesc()
2125 <<"Receive(): Invalid incoming packet, "
2126 <<"size: " << received_size
2128 << ((received_size >= 4) ? readU32(&packetdata[0]) : -1)
2133 u16 peer_id = readPeerId(*packetdata);
2134 u8 channelnum = readChannel(*packetdata);
2136 if (channelnum > CHANNEL_COUNT-1) {
2137 LOG(derr_con<<m_connection->getDesc()
2138 <<"Receive(): Invalid channel "<<channelnum<<std::endl);
2139 throw InvalidIncomingDataException("Channel doesn't exist");
2142 /* Try to identify peer by sender address (may happen on join) */
2143 if (peer_id == PEER_ID_INEXISTENT) {
2144 peer_id = m_connection->lookupPeer(sender);
2145 // We do not have to remind the peer of its
2146 // peer id as the CONTROLTYPE_SET_PEER_ID
2147 // command was sent reliably.
2150 /* The peer was not found in our lists. Add it. */
2151 if (peer_id == PEER_ID_INEXISTENT) {
2152 peer_id = m_connection->createPeer(sender, MTP_MINETEST_RELIABLE_UDP, 0);
2155 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
2158 LOG(dout_con<<m_connection->getDesc()
2159 <<" got packet from unknown peer_id: "
2160 <<peer_id<<" Ignoring."<<std::endl);
2164 // Validate peer address
2166 Address peer_address;
2168 if (peer->getAddress(MTP_UDP, peer_address)) {
2169 if (peer_address != sender) {
2170 LOG(derr_con<<m_connection->getDesc()
2171 <<m_connection->getDesc()
2172 <<" Peer "<<peer_id<<" sending from different address."
2173 " Ignoring."<<std::endl);
2179 bool invalid_address = true;
2180 if (invalid_address) {
2181 LOG(derr_con<<m_connection->getDesc()
2182 <<m_connection->getDesc()
2183 <<" Peer "<<peer_id<<" unknown."
2184 " Ignoring."<<std::endl);
2189 peer->ResetTimeout();
2191 Channel *channel = 0;
2193 if (dynamic_cast<UDPPeer*>(&peer) != 0)
2195 channel = &(dynamic_cast<UDPPeer*>(&peer)->channels[channelnum]);
2199 channel->UpdateBytesReceived(received_size);
2202 // Throw the received packet to channel->processPacket()
2204 // Make a new SharedBuffer from the data without the base headers
2205 SharedBuffer<u8> strippeddata(received_size - BASE_HEADER_SIZE);
2206 memcpy(*strippeddata, &packetdata[BASE_HEADER_SIZE],
2207 strippeddata.getSize());
2210 // Process it (the result is some data with no headers made by us)
2211 SharedBuffer<u8> resultdata = processPacket
2212 (channel, strippeddata, peer_id, channelnum, false);
2214 LOG(dout_con<<m_connection->getDesc()
2215 <<" ProcessPacket from peer_id: " << peer_id
2216 << ",channel: " << (channelnum & 0xFF) << ", returned "
2217 << resultdata.getSize() << " bytes" <<std::endl);
2220 e.dataReceived(peer_id, resultdata);
2221 m_connection->putEvent(e);
2223 catch(ProcessedSilentlyException &e) {
2225 catch(ProcessedQueued &e) {
2226 packet_queued = true;
2229 catch(InvalidIncomingDataException &e) {
2231 catch(ProcessedSilentlyException &e) {
2236 bool ConnectionReceiveThread::getFromBuffers(u16 &peer_id, SharedBuffer<u8> &dst)
2238 std::list<u16> peerids = m_connection->getPeerIDs();
2240 for(std::list<u16>::iterator j = peerids.begin();
2241 j != peerids.end(); ++j)
2243 PeerHelper peer = m_connection->getPeerNoEx(*j);
2247 if (dynamic_cast<UDPPeer*>(&peer) == 0)
2250 for(u16 i=0; i<CHANNEL_COUNT; i++)
2252 Channel *channel = &(dynamic_cast<UDPPeer*>(&peer))->channels[i];
2254 if (checkIncomingBuffers(channel, peer_id, dst)) {
2262 bool ConnectionReceiveThread::checkIncomingBuffers(Channel *channel,
2263 u16 &peer_id, SharedBuffer<u8> &dst)
2265 u16 firstseqnum = 0;
2266 if (channel->incoming_reliables.getFirstSeqnum(firstseqnum))
2268 if (firstseqnum == channel->readNextIncomingSeqNum())
2270 BufferedPacket p = channel->incoming_reliables.popFirst();
2271 peer_id = readPeerId(*p.data);
2272 u8 channelnum = readChannel(*p.data);
2273 u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]);
2275 LOG(dout_con<<m_connection->getDesc()
2276 <<"UNBUFFERING TYPE_RELIABLE"
2277 <<" seqnum="<<seqnum
2278 <<" peer_id="<<peer_id
2279 <<" channel="<<((int)channelnum&0xff)
2282 channel->incNextIncomingSeqNum();
2284 u32 headers_size = BASE_HEADER_SIZE + RELIABLE_HEADER_SIZE;
2285 // Get out the inside packet and re-process it
2286 SharedBuffer<u8> payload(p.data.getSize() - headers_size);
2287 memcpy(*payload, &p.data[headers_size], payload.getSize());
2289 dst = processPacket(channel, payload, peer_id, channelnum, true);
2296 SharedBuffer<u8> ConnectionReceiveThread::processPacket(Channel *channel,
2297 SharedBuffer<u8> packetdata, u16 peer_id, u8 channelnum, bool reliable)
2299 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
2302 errorstream << "Peer not found (possible timeout)" << std::endl;
2303 throw ProcessedSilentlyException("Peer not found (possible timeout)");
2306 if (packetdata.getSize() < 1)
2307 throw InvalidIncomingDataException("packetdata.getSize() < 1");
2309 u8 type = readU8(&(packetdata[0]));
2311 if (MAX_UDP_PEERS <= 65535 && peer_id >= MAX_UDP_PEERS) {
2312 std::string errmsg = "Invalid peer_id=" + itos(peer_id);
2313 errorstream << errmsg << std::endl;
2314 throw InvalidIncomingDataException(errmsg.c_str());
2317 if (type == TYPE_CONTROL)
2319 if (packetdata.getSize() < 2)
2320 throw InvalidIncomingDataException("packetdata.getSize() < 2");
2322 u8 controltype = readU8(&(packetdata[1]));
2324 if (controltype == CONTROLTYPE_ACK)
2326 assert(channel != NULL);
2328 if (packetdata.getSize() < 4) {
2329 throw InvalidIncomingDataException(
2330 "packetdata.getSize() < 4 (ACK header size)");
2333 u16 seqnum = readU16(&packetdata[2]);
2334 LOG(dout_con<<m_connection->getDesc()
2335 <<" [ CONTROLTYPE_ACK: channelnum="
2336 <<((int)channelnum&0xff)<<", peer_id="<<peer_id
2337 <<", seqnum="<<seqnum<< " ]"<<std::endl);
2341 channel->outgoing_reliables_sent.popSeqnum(seqnum);
2343 // only calculate rtt from straight sent packets
2344 if (p.resend_count == 0) {
2345 // Get round trip time
2346 u64 current_time = porting::getTimeMs();
2348 // a overflow is quite unlikely but as it'd result in major
2349 // rtt miscalculation we handle it here
2350 if (current_time > p.absolute_send_time)
2352 float rtt = (current_time - p.absolute_send_time) / 1000.0;
2354 // Let peer calculate stuff according to it
2355 // (avg_rtt and resend_timeout)
2356 dynamic_cast<UDPPeer*>(&peer)->reportRTT(rtt);
2358 else if (p.totaltime > 0)
2360 float rtt = p.totaltime;
2362 // Let peer calculate stuff according to it
2363 // (avg_rtt and resend_timeout)
2364 dynamic_cast<UDPPeer*>(&peer)->reportRTT(rtt);
2367 //put bytes for max bandwidth calculation
2368 channel->UpdateBytesSent(p.data.getSize(),1);
2369 if (channel->outgoing_reliables_sent.size() == 0)
2371 m_connection->TriggerSend();
2374 catch(NotFoundException &e) {
2375 LOG(derr_con<<m_connection->getDesc()
2376 <<"WARNING: ACKed packet not "
2379 channel->UpdatePacketTooLateCounter();
2381 throw ProcessedSilentlyException("Got an ACK");
2383 else if (controltype == CONTROLTYPE_SET_PEER_ID) {
2384 // Got a packet to set our peer id
2385 if (packetdata.getSize() < 4)
2386 throw InvalidIncomingDataException
2387 ("packetdata.getSize() < 4 (SET_PEER_ID header size)");
2388 u16 peer_id_new = readU16(&packetdata[2]);
2389 LOG(dout_con<<m_connection->getDesc()
2390 <<"Got new peer id: "<<peer_id_new<<"... "<<std::endl);
2392 if (m_connection->GetPeerID() != PEER_ID_INEXISTENT)
2394 LOG(derr_con<<m_connection->getDesc()
2395 <<"WARNING: Not changing"
2396 " existing peer id."<<std::endl);
2400 LOG(dout_con<<m_connection->getDesc()<<"changing own peer id"<<std::endl);
2401 m_connection->SetPeerID(peer_id_new);
2404 ConnectionCommand cmd;
2406 SharedBuffer<u8> reply(2);
2407 writeU8(&reply[0], TYPE_CONTROL);
2408 writeU8(&reply[1], CONTROLTYPE_ENABLE_BIG_SEND_WINDOW);
2409 cmd.disableLegacy(PEER_ID_SERVER,reply);
2410 m_connection->putCommand(cmd);
2412 throw ProcessedSilentlyException("Got a SET_PEER_ID");
2414 else if (controltype == CONTROLTYPE_PING)
2416 // Just ignore it, the incoming data already reset
2417 // the timeout counter
2418 LOG(dout_con<<m_connection->getDesc()<<"PING"<<std::endl);
2419 throw ProcessedSilentlyException("Got a PING");
2421 else if (controltype == CONTROLTYPE_DISCO)
2423 // Just ignore it, the incoming data already reset
2424 // the timeout counter
2425 LOG(dout_con<<m_connection->getDesc()
2426 <<"DISCO: Removing peer "<<(peer_id)<<std::endl);
2428 if (m_connection->deletePeer(peer_id, false) == false)
2430 derr_con<<m_connection->getDesc()
2431 <<"DISCO: Peer not found"<<std::endl;
2434 throw ProcessedSilentlyException("Got a DISCO");
2436 else if (controltype == CONTROLTYPE_ENABLE_BIG_SEND_WINDOW)
2438 dynamic_cast<UDPPeer*>(&peer)->setNonLegacyPeer();
2439 throw ProcessedSilentlyException("Got non legacy control");
2442 LOG(derr_con<<m_connection->getDesc()
2443 <<"INVALID TYPE_CONTROL: invalid controltype="
2444 <<((int)controltype&0xff)<<std::endl);
2445 throw InvalidIncomingDataException("Invalid control type");
2448 else if (type == TYPE_ORIGINAL)
2450 if (packetdata.getSize() <= ORIGINAL_HEADER_SIZE)
2451 throw InvalidIncomingDataException
2452 ("packetdata.getSize() <= ORIGINAL_HEADER_SIZE");
2453 LOG(dout_con<<m_connection->getDesc()
2454 <<"RETURNING TYPE_ORIGINAL to user"
2456 // Get the inside packet out and return it
2457 SharedBuffer<u8> payload(packetdata.getSize() - ORIGINAL_HEADER_SIZE);
2458 memcpy(*payload, &(packetdata[ORIGINAL_HEADER_SIZE]), payload.getSize());
2461 else if (type == TYPE_SPLIT)
2463 Address peer_address;
2465 if (peer->getAddress(MTP_UDP, peer_address)) {
2467 // We have to create a packet again for buffering
2468 // This isn't actually too bad an idea.
2469 BufferedPacket packet = makePacket(
2472 m_connection->GetProtocolID(),
2476 // Buffer the packet
2477 SharedBuffer<u8> data =
2478 peer->addSpiltPacket(channelnum,packet,reliable);
2480 if (data.getSize() != 0)
2482 LOG(dout_con<<m_connection->getDesc()
2483 <<"RETURNING TYPE_SPLIT: Constructed full data, "
2484 <<"size="<<data.getSize()<<std::endl);
2487 LOG(dout_con<<m_connection->getDesc()<<"BUFFERED TYPE_SPLIT"<<std::endl);
2488 throw ProcessedSilentlyException("Buffered a split packet chunk");
2491 //TODO throw some error
2494 else if (type == TYPE_RELIABLE)
2496 assert(channel != NULL);
2498 // Recursive reliable packets not allowed
2500 throw InvalidIncomingDataException("Found nested reliable packets");
2502 if (packetdata.getSize() < RELIABLE_HEADER_SIZE)
2503 throw InvalidIncomingDataException
2504 ("packetdata.getSize() < RELIABLE_HEADER_SIZE");
2506 u16 seqnum = readU16(&packetdata[1]);
2507 bool is_future_packet = false;
2508 bool is_old_packet = false;
2510 /* packet is within our receive window send ack */
2511 if (seqnum_in_window(seqnum, channel->readNextIncomingSeqNum(),MAX_RELIABLE_WINDOW_SIZE))
2513 m_connection->sendAck(peer_id,channelnum,seqnum);
2516 is_future_packet = seqnum_higher(seqnum, channel->readNextIncomingSeqNum());
2517 is_old_packet = seqnum_higher(channel->readNextIncomingSeqNum(), seqnum);
2520 /* packet is not within receive window, don't send ack. *
2521 * if this was a valid packet it's gonna be retransmitted */
2522 if (is_future_packet)
2524 throw ProcessedSilentlyException("Received packet newer then expected, not sending ack");
2527 /* seems like our ack was lost, send another one for a old packet */
2530 LOG(dout_con<<m_connection->getDesc()
2531 << "RE-SENDING ACK: peer_id: " << peer_id
2532 << ", channel: " << (channelnum&0xFF)
2533 << ", seqnum: " << seqnum << std::endl;)
2534 m_connection->sendAck(peer_id,channelnum,seqnum);
2536 // we already have this packet so this one was on wire at least
2537 // the current timeout
2538 // we don't know how long this packet was on wire don't do silly guessing
2539 // dynamic_cast<UDPPeer*>(&peer)->reportRTT(dynamic_cast<UDPPeer*>(&peer)->getResendTimeout());
2541 throw ProcessedSilentlyException("Retransmitting ack for old packet");
2545 if (seqnum != channel->readNextIncomingSeqNum())
2547 Address peer_address;
2549 // this is a reliable packet so we have a udp address for sure
2550 peer->getAddress(MTP_MINETEST_RELIABLE_UDP, peer_address);
2551 // This one comes later, buffer it.
2552 // Actually we have to make a packet to buffer one.
2553 // Well, we have all the ingredients, so just do it.
2554 BufferedPacket packet = con::makePacket(
2557 m_connection->GetProtocolID(),
2561 channel->incoming_reliables.insert(packet,channel->readNextIncomingSeqNum());
2563 LOG(dout_con<<m_connection->getDesc()
2564 << "BUFFERING, TYPE_RELIABLE peer_id: " << peer_id
2565 << ", channel: " << (channelnum&0xFF)
2566 << ", seqnum: " << seqnum << std::endl;)
2568 throw ProcessedQueued("Buffered future reliable packet");
2570 catch(AlreadyExistsException &e)
2573 catch(IncomingDataCorruption &e)
2575 ConnectionCommand discon;
2576 discon.disconnect_peer(peer_id);
2577 m_connection->putCommand(discon);
2579 LOG(derr_con<<m_connection->getDesc()
2580 << "INVALID, TYPE_RELIABLE peer_id: " << peer_id
2581 << ", channel: " << (channelnum&0xFF)
2582 << ", seqnum: " << seqnum
2583 << "DROPPING CLIENT!" << std::endl;)
2587 /* we got a packet to process right now */
2588 LOG(dout_con<<m_connection->getDesc()
2589 << "RECURSIVE, TYPE_RELIABLE peer_id: " << peer_id
2590 << ", channel: " << (channelnum&0xFF)
2591 << ", seqnum: " << seqnum << std::endl;)
2594 /* check for resend case */
2595 u16 queued_seqnum = 0;
2596 if (channel->incoming_reliables.getFirstSeqnum(queued_seqnum))
2598 if (queued_seqnum == seqnum)
2600 BufferedPacket queued_packet = channel->incoming_reliables.popFirst();
2601 /** TODO find a way to verify the new against the old packet */
2605 channel->incNextIncomingSeqNum();
2607 // Get out the inside packet and re-process it
2608 SharedBuffer<u8> payload(packetdata.getSize() - RELIABLE_HEADER_SIZE);
2609 memcpy(*payload, &packetdata[RELIABLE_HEADER_SIZE], payload.getSize());
2611 return processPacket(channel, payload, peer_id, channelnum, true);
2615 derr_con<<m_connection->getDesc()
2616 <<"Got invalid type="<<((int)type&0xff)<<std::endl;
2617 throw InvalidIncomingDataException("Invalid packet type");
2620 // We should never get here.
2621 FATAL_ERROR("Invalid execution point");
2628 Connection::Connection(u32 protocol_id, u32 max_packet_size, float timeout,
2629 bool ipv6, PeerHandler *peerhandler) :
2631 m_protocol_id(protocol_id),
2632 m_sendThread(max_packet_size, timeout),
2633 m_receiveThread(max_packet_size),
2634 m_bc_peerhandler(peerhandler)
2637 m_udpSocket.setTimeoutMs(5);
2639 m_sendThread.setParent(this);
2640 m_receiveThread.setParent(this);
2642 m_sendThread.start();
2643 m_receiveThread.start();
2648 Connection::~Connection()
2650 m_shutting_down = true;
2651 // request threads to stop
2652 m_sendThread.stop();
2653 m_receiveThread.stop();
2655 //TODO for some unkonwn reason send/receive threads do not exit as they're
2656 // supposed to be but wait on peer timeout. To speed up shutdown we reduce
2657 // timeout to half a second.
2658 m_sendThread.setPeerTimeout(0.5);
2660 // wait for threads to finish
2661 m_sendThread.wait();
2662 m_receiveThread.wait();
2665 for(std::map<u16, Peer*>::iterator
2666 j = m_peers.begin();
2667 j != m_peers.end(); ++j)
2673 /* Internal stuff */
2674 void Connection::putEvent(ConnectionEvent &e)
2676 assert(e.type != CONNEVENT_NONE); // Pre-condition
2677 m_event_queue.push_back(e);
2680 PeerHelper Connection::getPeer(u16 peer_id)
2682 MutexAutoLock peerlock(m_peers_mutex);
2683 std::map<u16, Peer*>::iterator node = m_peers.find(peer_id);
2685 if (node == m_peers.end()) {
2686 throw PeerNotFoundException("GetPeer: Peer not found (possible timeout)");
2690 FATAL_ERROR_IF(node->second->id != peer_id, "Invalid peer id");
2692 return PeerHelper(node->second);
2695 PeerHelper Connection::getPeerNoEx(u16 peer_id)
2697 MutexAutoLock peerlock(m_peers_mutex);
2698 std::map<u16, Peer*>::iterator node = m_peers.find(peer_id);
2700 if (node == m_peers.end()) {
2701 return PeerHelper(NULL);
2705 FATAL_ERROR_IF(node->second->id != peer_id, "Invalid peer id");
2707 return PeerHelper(node->second);
2710 /* find peer_id for address */
2711 u16 Connection::lookupPeer(Address& sender)
2713 MutexAutoLock peerlock(m_peers_mutex);
2714 std::map<u16, Peer*>::iterator j;
2715 j = m_peers.begin();
2716 for(; j != m_peers.end(); ++j)
2718 Peer *peer = j->second;
2719 if (peer->isPendingDeletion())
2724 if ((peer->getAddress(MTP_MINETEST_RELIABLE_UDP, tocheck)) && (tocheck == sender))
2727 if ((peer->getAddress(MTP_UDP, tocheck)) && (tocheck == sender))
2731 return PEER_ID_INEXISTENT;
2734 std::list<Peer*> Connection::getPeers()
2736 std::list<Peer*> list;
2737 for(std::map<u16, Peer*>::iterator j = m_peers.begin();
2738 j != m_peers.end(); ++j)
2740 Peer *peer = j->second;
2741 list.push_back(peer);
2746 bool Connection::deletePeer(u16 peer_id, bool timeout)
2750 /* lock list as short as possible */
2752 MutexAutoLock peerlock(m_peers_mutex);
2753 if (m_peers.find(peer_id) == m_peers.end())
2755 peer = m_peers[peer_id];
2756 m_peers.erase(peer_id);
2757 m_peer_ids.remove(peer_id);
2760 Address peer_address;
2761 //any peer has a primary address this never fails!
2762 peer->getAddress(MTP_PRIMARY, peer_address);
2765 e.peerRemoved(peer_id, timeout, peer_address);
2775 ConnectionEvent Connection::waitEvent(u32 timeout_ms)
2778 return m_event_queue.pop_front(timeout_ms);
2779 } catch(ItemNotFoundException &ex) {
2781 e.type = CONNEVENT_NONE;
2786 void Connection::putCommand(ConnectionCommand &c)
2788 if (!m_shutting_down) {
2789 m_command_queue.push_back(c);
2790 m_sendThread.Trigger();
2794 void Connection::Serve(Address bind_addr)
2796 ConnectionCommand c;
2801 void Connection::Connect(Address address)
2803 ConnectionCommand c;
2808 bool Connection::Connected()
2810 MutexAutoLock peerlock(m_peers_mutex);
2812 if (m_peers.size() != 1)
2815 std::map<u16, Peer*>::iterator node = m_peers.find(PEER_ID_SERVER);
2816 if (node == m_peers.end())
2819 if (m_peer_id == PEER_ID_INEXISTENT)
2825 void Connection::Disconnect()
2827 ConnectionCommand c;
2832 void Connection::Receive(NetworkPacket* pkt)
2835 ConnectionEvent e = waitEvent(m_bc_receive_timeout);
2836 if (e.type != CONNEVENT_NONE)
2837 LOG(dout_con << getDesc() << ": Receive: got event: "
2838 << e.describe() << std::endl);
2840 case CONNEVENT_NONE:
2841 throw NoIncomingDataException("No incoming data");
2842 case CONNEVENT_DATA_RECEIVED:
2843 // Data size is lesser than command size, ignoring packet
2844 if (e.data.getSize() < 2) {
2848 pkt->putRawPacket(*e.data, e.data.getSize(), e.peer_id);
2850 case CONNEVENT_PEER_ADDED: {
2851 UDPPeer tmp(e.peer_id, e.address, this);
2852 if (m_bc_peerhandler)
2853 m_bc_peerhandler->peerAdded(&tmp);
2856 case CONNEVENT_PEER_REMOVED: {
2857 UDPPeer tmp(e.peer_id, e.address, this);
2858 if (m_bc_peerhandler)
2859 m_bc_peerhandler->deletingPeer(&tmp, e.timeout);
2862 case CONNEVENT_BIND_FAILED:
2863 throw ConnectionBindFailed("Failed to bind socket "
2864 "(port already in use?)");
2867 throw NoIncomingDataException("No incoming data");
2870 void Connection::Send(u16 peer_id, u8 channelnum,
2871 NetworkPacket* pkt, bool reliable)
2873 assert(channelnum < CHANNEL_COUNT); // Pre-condition
2875 ConnectionCommand c;
2877 c.send(peer_id, channelnum, pkt, reliable);
2881 Address Connection::GetPeerAddress(u16 peer_id)
2883 PeerHelper peer = getPeerNoEx(peer_id);
2886 throw PeerNotFoundException("No address for peer found!");
2887 Address peer_address;
2888 peer->getAddress(MTP_PRIMARY, peer_address);
2889 return peer_address;
2892 float Connection::getPeerStat(u16 peer_id, rtt_stat_type type)
2894 PeerHelper peer = getPeerNoEx(peer_id);
2895 if (!peer) return -1;
2896 return peer->getStat(type);
2899 float Connection::getLocalStat(rate_stat_type type)
2901 PeerHelper peer = getPeerNoEx(PEER_ID_SERVER);
2903 FATAL_ERROR_IF(!peer, "Connection::getLocalStat we couldn't get our own peer? are you serious???");
2907 for (u16 j=0; j<CHANNEL_COUNT; j++) {
2910 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getCurrentDownloadRateKB();
2913 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getAvgDownloadRateKB();
2916 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getCurrentIncomingRateKB();
2919 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getAvgIncomingRateKB();
2922 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getAvgLossRateKB();
2925 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getCurrentLossRateKB();
2928 FATAL_ERROR("Connection::getLocalStat Invalid stat type");
2934 u16 Connection::createPeer(Address& sender, MTProtocols protocol, int fd)
2936 // Somebody wants to make a new connection
2938 // Get a unique peer id (2 or higher)
2939 u16 peer_id_new = m_next_remote_peer_id;
2940 u16 overflow = MAX_UDP_PEERS;
2943 Find an unused peer id
2945 MutexAutoLock lock(m_peers_mutex);
2946 bool out_of_ids = false;
2949 if (m_peers.find(peer_id_new) == m_peers.end())
2952 // Check for overflow
2953 if (peer_id_new == overflow) {
2961 errorstream << getDesc() << " ran out of peer ids" << std::endl;
2962 return PEER_ID_INEXISTENT;
2967 peer = new UDPPeer(peer_id_new, sender, this);
2969 m_peers[peer->id] = peer;
2970 m_peer_ids.push_back(peer->id);
2972 m_next_remote_peer_id = (peer_id_new +1 ) % MAX_UDP_PEERS;
2974 LOG(dout_con << getDesc()
2975 << "createPeer(): giving peer_id=" << peer_id_new << std::endl);
2977 ConnectionCommand cmd;
2978 SharedBuffer<u8> reply(4);
2979 writeU8(&reply[0], TYPE_CONTROL);
2980 writeU8(&reply[1], CONTROLTYPE_SET_PEER_ID);
2981 writeU16(&reply[2], peer_id_new);
2982 cmd.createPeer(peer_id_new,reply);
2985 // Create peer addition event
2987 e.peerAdded(peer_id_new, sender);
2990 // We're now talking to a valid peer_id
2994 void Connection::PrintInfo(std::ostream &out)
2996 m_info_mutex.lock();
2997 out<<getDesc()<<": ";
2998 m_info_mutex.unlock();
3001 void Connection::PrintInfo()
3003 PrintInfo(dout_con);
3006 const std::string Connection::getDesc()
3008 return std::string("con(")+
3009 itos(m_udpSocket.GetHandle())+"/"+itos(m_peer_id)+")";
3012 void Connection::DisconnectPeer(u16 peer_id)
3014 ConnectionCommand discon;
3015 discon.disconnect_peer(peer_id);
3019 void Connection::sendAck(u16 peer_id, u8 channelnum, u16 seqnum)
3021 assert(channelnum < CHANNEL_COUNT); // Pre-condition
3023 LOG(dout_con<<getDesc()
3024 <<" Queuing ACK command to peer_id: " << peer_id <<
3025 " channel: " << (channelnum & 0xFF) <<
3026 " seqnum: " << seqnum << std::endl);
3028 ConnectionCommand c;
3029 SharedBuffer<u8> ack(4);
3030 writeU8(&ack[0], TYPE_CONTROL);
3031 writeU8(&ack[1], CONTROLTYPE_ACK);
3032 writeU16(&ack[2], seqnum);
3034 c.ack(peer_id, channelnum, ack);
3036 m_sendThread.Trigger();
3039 UDPPeer* Connection::createServerPeer(Address& address)
3041 if (getPeerNoEx(PEER_ID_SERVER) != 0)
3043 throw ConnectionException("Already connected to a server");
3046 UDPPeer *peer = new UDPPeer(PEER_ID_SERVER, address, this);
3049 MutexAutoLock lock(m_peers_mutex);
3050 m_peers[peer->id] = peer;
3051 m_peer_ids.push_back(peer->id);