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 (SharedBuffer<u8> &chunk : chunks) {
156 writeU16(&(chunk[3]), chunk_count);
162 std::list<SharedBuffer<u8> > makeAutoSplitPacket(
163 SharedBuffer<u8> data,
167 u32 original_header_size = 1;
168 std::list<SharedBuffer<u8> > list;
169 if (data.getSize() + original_header_size > chunksize_max)
171 list = makeSplitPacket(data, chunksize_max, split_seqnum);
176 list.push_back(makeOriginalPacket(data));
180 SharedBuffer<u8> makeReliablePacket(
181 const SharedBuffer<u8> &data,
185 u32 packet_size = data.getSize() + header_size;
186 SharedBuffer<u8> b(packet_size);
188 writeU8(&b[0], TYPE_RELIABLE);
189 writeU16(&b[1], seqnum);
191 memcpy(&b[header_size], *data, data.getSize());
200 void ReliablePacketBuffer::print()
202 MutexAutoLock listlock(m_list_mutex);
203 LOG(dout_con<<"Dump of ReliablePacketBuffer:" << std::endl);
204 unsigned int index = 0;
205 for (BufferedPacket &bufferedPacket : m_list) {
206 u16 s = readU16(&(bufferedPacket.data[BASE_HEADER_SIZE+1]));
207 LOG(dout_con<<index<< ":" << s << std::endl);
211 bool ReliablePacketBuffer::empty()
213 MutexAutoLock listlock(m_list_mutex);
214 return m_list.empty();
217 u32 ReliablePacketBuffer::size()
222 bool ReliablePacketBuffer::containsPacket(u16 seqnum)
224 return !(findPacket(seqnum) == m_list.end());
227 RPBSearchResult ReliablePacketBuffer::findPacket(u16 seqnum)
229 std::list<BufferedPacket>::iterator i = m_list.begin();
230 for(; i != m_list.end(); ++i)
232 u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
233 /*dout_con<<"findPacket(): finding seqnum="<<seqnum
234 <<", comparing to s="<<s<<std::endl;*/
240 RPBSearchResult ReliablePacketBuffer::notFound()
244 bool ReliablePacketBuffer::getFirstSeqnum(u16& result)
246 MutexAutoLock listlock(m_list_mutex);
249 BufferedPacket p = *m_list.begin();
250 result = readU16(&p.data[BASE_HEADER_SIZE+1]);
254 BufferedPacket ReliablePacketBuffer::popFirst()
256 MutexAutoLock listlock(m_list_mutex);
258 throw NotFoundException("Buffer is empty");
259 BufferedPacket p = *m_list.begin();
260 m_list.erase(m_list.begin());
263 if (m_list_size == 0) {
264 m_oldest_non_answered_ack = 0;
266 m_oldest_non_answered_ack =
267 readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]);
271 BufferedPacket ReliablePacketBuffer::popSeqnum(u16 seqnum)
273 MutexAutoLock listlock(m_list_mutex);
274 RPBSearchResult r = findPacket(seqnum);
275 if (r == notFound()) {
276 LOG(dout_con<<"Sequence number: " << seqnum
277 << " not found in reliable buffer"<<std::endl);
278 throw NotFoundException("seqnum not found in buffer");
280 BufferedPacket p = *r;
283 RPBSearchResult next = r;
285 if (next != notFound()) {
286 u16 s = readU16(&(next->data[BASE_HEADER_SIZE+1]));
287 m_oldest_non_answered_ack = s;
293 if (m_list_size == 0)
294 { m_oldest_non_answered_ack = 0; }
296 { m_oldest_non_answered_ack = readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]); }
299 void ReliablePacketBuffer::insert(BufferedPacket &p,u16 next_expected)
301 MutexAutoLock listlock(m_list_mutex);
302 if (p.data.getSize() < BASE_HEADER_SIZE + 3) {
303 errorstream << "ReliablePacketBuffer::insert(): Invalid data size for "
304 "reliable packet" << std::endl;
307 u8 type = readU8(&p.data[BASE_HEADER_SIZE + 0]);
308 if (type != TYPE_RELIABLE) {
309 errorstream << "ReliablePacketBuffer::insert(): type is not reliable"
313 u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE + 1]);
315 if (!seqnum_in_window(seqnum, next_expected, MAX_RELIABLE_WINDOW_SIZE)) {
316 errorstream << "ReliablePacketBuffer::insert(): seqnum is outside of "
317 "expected window " << std::endl;
320 if (seqnum == next_expected) {
321 errorstream << "ReliablePacketBuffer::insert(): seqnum is next expected"
327 sanity_check(m_list_size <= SEQNUM_MAX+1); // FIXME: Handle the error?
329 // Find the right place for the packet and insert it there
330 // If list is empty, just add it
334 m_oldest_non_answered_ack = seqnum;
339 // Otherwise find the right place
340 std::list<BufferedPacket>::iterator i = m_list.begin();
341 // Find the first packet in the list which has a higher seqnum
342 u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
344 /* case seqnum is smaller then next_expected seqnum */
345 /* this is true e.g. on wrap around */
346 if (seqnum < next_expected) {
347 while(((s < seqnum) || (s >= next_expected)) && (i != m_list.end())) {
349 if (i != m_list.end())
350 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
353 /* non wrap around case (at least for incoming and next_expected */
356 while(((s < seqnum) && (s >= next_expected)) && (i != m_list.end())) {
358 if (i != m_list.end())
359 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
365 (readU16(&(i->data[BASE_HEADER_SIZE+1])) != seqnum) ||
366 (i->data.getSize() != p.data.getSize()) ||
367 (i->address != p.address)
370 /* if this happens your maximum transfer window may be to big */
372 "Duplicated seqnum %d non matching packet detected:\n",
374 fprintf(stderr, "Old: seqnum: %05d size: %04d, address: %s\n",
375 readU16(&(i->data[BASE_HEADER_SIZE+1])),i->data.getSize(),
376 i->address.serializeString().c_str());
377 fprintf(stderr, "New: seqnum: %05d size: %04u, address: %s\n",
378 readU16(&(p.data[BASE_HEADER_SIZE+1])),p.data.getSize(),
379 p.address.serializeString().c_str());
380 throw IncomingDataCorruption("duplicated packet isn't same as original one");
383 /* nothing to do this seems to be a resent packet */
384 /* for paranoia reason data should be compared */
387 /* insert or push back */
388 else if (i != m_list.end()) {
395 /* update last packet number */
396 m_oldest_non_answered_ack = readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]);
399 void ReliablePacketBuffer::incrementTimeouts(float dtime)
401 MutexAutoLock listlock(m_list_mutex);
402 for (BufferedPacket &bufferedPacket : m_list) {
403 bufferedPacket.time += dtime;
404 bufferedPacket.totaltime += dtime;
408 std::list<BufferedPacket> ReliablePacketBuffer::getTimedOuts(float timeout,
409 unsigned int max_packets)
411 MutexAutoLock listlock(m_list_mutex);
412 std::list<BufferedPacket> timed_outs;
413 for (BufferedPacket &bufferedPacket : m_list) {
414 if (bufferedPacket.time >= timeout) {
415 timed_outs.push_back(bufferedPacket);
417 //this packet will be sent right afterwards reset timeout here
418 bufferedPacket.time = 0.0f;
419 if (timed_outs.size() >= max_packets)
430 IncomingSplitBuffer::~IncomingSplitBuffer()
432 MutexAutoLock listlock(m_map_mutex);
433 for (auto &i : m_buf) {
438 This will throw a GotSplitPacketException when a full
439 split packet is constructed.
441 SharedBuffer<u8> IncomingSplitBuffer::insert(BufferedPacket &p, bool reliable)
443 MutexAutoLock listlock(m_map_mutex);
444 u32 headersize = BASE_HEADER_SIZE + 7;
445 if (p.data.getSize() < headersize) {
446 errorstream << "Invalid data size for split packet" << std::endl;
447 return SharedBuffer<u8>();
449 u8 type = readU8(&p.data[BASE_HEADER_SIZE+0]);
450 u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]);
451 u16 chunk_count = readU16(&p.data[BASE_HEADER_SIZE+3]);
452 u16 chunk_num = readU16(&p.data[BASE_HEADER_SIZE+5]);
454 if (type != TYPE_SPLIT) {
455 errorstream << "IncomingSplitBuffer::insert(): type is not split"
457 return SharedBuffer<u8>();
460 // Add if doesn't exist
461 if (m_buf.find(seqnum) == m_buf.end())
463 IncomingSplitPacket *sp = new IncomingSplitPacket();
464 sp->chunk_count = chunk_count;
465 sp->reliable = reliable;
469 IncomingSplitPacket *sp = m_buf[seqnum];
471 // TODO: These errors should be thrown or something? Dunno.
472 if (chunk_count != sp->chunk_count)
473 LOG(derr_con<<"Connection: WARNING: chunk_count="<<chunk_count
474 <<" != sp->chunk_count="<<sp->chunk_count
476 if (reliable != sp->reliable)
477 LOG(derr_con<<"Connection: WARNING: reliable="<<reliable
478 <<" != sp->reliable="<<sp->reliable
481 // If chunk already exists, ignore it.
482 // Sometimes two identical packets may arrive when there is network
483 // lag and the server re-sends stuff.
484 if (sp->chunks.find(chunk_num) != sp->chunks.end())
485 return SharedBuffer<u8>();
487 // Cut chunk data out of packet
488 u32 chunkdatasize = p.data.getSize() - headersize;
489 SharedBuffer<u8> chunkdata(chunkdatasize);
490 memcpy(*chunkdata, &(p.data[headersize]), chunkdatasize);
492 // Set chunk data in buffer
493 sp->chunks[chunk_num] = chunkdata;
495 // If not all chunks are received, return empty buffer
496 if (!sp->allReceived())
497 return SharedBuffer<u8>();
499 // Calculate total size
501 for (const auto &chunk : sp->chunks) {
502 totalsize += chunk.second.getSize();
505 SharedBuffer<u8> fulldata(totalsize);
507 // Copy chunks to data buffer
509 for(u32 chunk_i=0; chunk_i<sp->chunk_count;
512 SharedBuffer<u8> buf = sp->chunks[chunk_i];
513 u16 chunkdatasize = buf.getSize();
514 memcpy(&fulldata[start], *buf, chunkdatasize);
515 start += chunkdatasize;;
518 // Remove sp from buffer
524 void IncomingSplitBuffer::removeUnreliableTimedOuts(float dtime, float timeout)
526 std::list<u16> remove_queue;
528 MutexAutoLock listlock(m_map_mutex);
529 for (auto &i : m_buf) {
530 IncomingSplitPacket *p = i.second;
531 // Reliable ones are not removed by timeout
535 if (p->time >= timeout)
536 remove_queue.push_back(i.first);
539 for (u16 j : remove_queue) {
540 MutexAutoLock listlock(m_map_mutex);
541 LOG(dout_con<<"NOTE: Removing timed out unreliable split packet"<<std::endl);
551 void ConnectionCommand::send(u16 peer_id_, u8 channelnum_, NetworkPacket *pkt,
556 channelnum = channelnum_;
557 data = pkt->oldForgePacket();
558 reliable = reliable_;
565 u16 Channel::readNextIncomingSeqNum()
567 MutexAutoLock internal(m_internal_mutex);
568 return next_incoming_seqnum;
571 u16 Channel::incNextIncomingSeqNum()
573 MutexAutoLock internal(m_internal_mutex);
574 u16 retval = next_incoming_seqnum;
575 next_incoming_seqnum++;
579 u16 Channel::readNextSplitSeqNum()
581 MutexAutoLock internal(m_internal_mutex);
582 return next_outgoing_split_seqnum;
584 void Channel::setNextSplitSeqNum(u16 seqnum)
586 MutexAutoLock internal(m_internal_mutex);
587 next_outgoing_split_seqnum = seqnum;
590 u16 Channel::getOutgoingSequenceNumber(bool& successful)
592 MutexAutoLock internal(m_internal_mutex);
593 u16 retval = next_outgoing_seqnum;
594 u16 lowest_unacked_seqnumber;
596 /* shortcut if there ain't any packet in outgoing list */
597 if (outgoing_reliables_sent.empty())
599 next_outgoing_seqnum++;
603 if (outgoing_reliables_sent.getFirstSeqnum(lowest_unacked_seqnumber))
605 if (lowest_unacked_seqnumber < next_outgoing_seqnum) {
606 // ugly cast but this one is required in order to tell compiler we
607 // know about difference of two unsigned may be negative in general
608 // but we already made sure it won't happen in this case
609 if (((u16)(next_outgoing_seqnum - lowest_unacked_seqnumber)) > window_size) {
615 // ugly cast but this one is required in order to tell compiler we
616 // know about difference of two unsigned may be negative in general
617 // but we already made sure it won't happen in this case
618 if ((next_outgoing_seqnum + (u16)(SEQNUM_MAX - lowest_unacked_seqnumber)) >
626 next_outgoing_seqnum++;
630 u16 Channel::readOutgoingSequenceNumber()
632 MutexAutoLock internal(m_internal_mutex);
633 return next_outgoing_seqnum;
636 bool Channel::putBackSequenceNumber(u16 seqnum)
638 if (((seqnum + 1) % (SEQNUM_MAX+1)) == next_outgoing_seqnum) {
640 next_outgoing_seqnum = seqnum;
646 void Channel::UpdateBytesSent(unsigned int bytes, unsigned int packets)
648 MutexAutoLock internal(m_internal_mutex);
649 current_bytes_transfered += bytes;
650 current_packet_successfull += packets;
653 void Channel::UpdateBytesReceived(unsigned int bytes) {
654 MutexAutoLock internal(m_internal_mutex);
655 current_bytes_received += bytes;
658 void Channel::UpdateBytesLost(unsigned int bytes)
660 MutexAutoLock internal(m_internal_mutex);
661 current_bytes_lost += bytes;
665 void Channel::UpdatePacketLossCounter(unsigned int count)
667 MutexAutoLock internal(m_internal_mutex);
668 current_packet_loss += count;
671 void Channel::UpdatePacketTooLateCounter()
673 MutexAutoLock internal(m_internal_mutex);
674 current_packet_too_late++;
677 void Channel::UpdateTimers(float dtime,bool legacy_peer)
679 bpm_counter += dtime;
680 packet_loss_counter += dtime;
682 if (packet_loss_counter > 1.0)
684 packet_loss_counter -= 1.0;
686 unsigned int packet_loss = 11; /* use a neutral value for initialization */
687 unsigned int packets_successfull = 0;
688 //unsigned int packet_too_late = 0;
690 bool reasonable_amount_of_data_transmitted = false;
693 MutexAutoLock internal(m_internal_mutex);
694 packet_loss = current_packet_loss;
695 //packet_too_late = current_packet_too_late;
696 packets_successfull = current_packet_successfull;
698 if (current_bytes_transfered > (unsigned int) (window_size*512/2))
700 reasonable_amount_of_data_transmitted = true;
702 current_packet_loss = 0;
703 current_packet_too_late = 0;
704 current_packet_successfull = 0;
707 /* dynamic window size is only available for non legacy peers */
709 float successfull_to_lost_ratio = 0.0;
712 if (packets_successfull > 0) {
713 successfull_to_lost_ratio = packet_loss/packets_successfull;
715 else if (packet_loss > 0)
719 MIN_RELIABLE_WINDOW_SIZE);
725 if ((successfull_to_lost_ratio < 0.01) &&
726 (window_size < MAX_RELIABLE_WINDOW_SIZE))
728 /* don't even think about increasing if we didn't even
729 * use major parts of our window */
730 if (reasonable_amount_of_data_transmitted)
733 MAX_RELIABLE_WINDOW_SIZE);
735 else if ((successfull_to_lost_ratio < 0.05) &&
736 (window_size < MAX_RELIABLE_WINDOW_SIZE))
738 /* don't even think about increasing if we didn't even
739 * use major parts of our window */
740 if (reasonable_amount_of_data_transmitted)
743 MAX_RELIABLE_WINDOW_SIZE);
745 else if (successfull_to_lost_ratio > 0.15)
749 MIN_RELIABLE_WINDOW_SIZE);
751 else if (successfull_to_lost_ratio > 0.1)
755 MIN_RELIABLE_WINDOW_SIZE);
761 if (bpm_counter > 10.0)
764 MutexAutoLock internal(m_internal_mutex);
766 (((float) current_bytes_transfered)/bpm_counter)/1024.0;
767 current_bytes_transfered = 0;
769 (((float) current_bytes_lost)/bpm_counter)/1024.0;
770 current_bytes_lost = 0;
772 (((float) current_bytes_received)/bpm_counter)/1024.0;
773 current_bytes_received = 0;
777 if (cur_kbps > max_kbps)
782 if (cur_kbps_lost > max_kbps_lost)
784 max_kbps_lost = cur_kbps_lost;
787 if (cur_incoming_kbps > max_incoming_kbps) {
788 max_incoming_kbps = cur_incoming_kbps;
791 rate_samples = MYMIN(rate_samples+1,10);
792 float old_fraction = ((float) (rate_samples-1) )/( (float) rate_samples);
793 avg_kbps = avg_kbps * old_fraction +
794 cur_kbps * (1.0 - old_fraction);
795 avg_kbps_lost = avg_kbps_lost * old_fraction +
796 cur_kbps_lost * (1.0 - old_fraction);
797 avg_incoming_kbps = avg_incoming_kbps * old_fraction +
798 cur_incoming_kbps * (1.0 - old_fraction);
807 PeerHelper::PeerHelper(Peer* peer) :
810 if (peer && !peer->IncUseCount())
814 PeerHelper::~PeerHelper()
817 m_peer->DecUseCount();
822 PeerHelper& PeerHelper::operator=(Peer* peer)
825 if (peer && !peer->IncUseCount())
830 Peer* PeerHelper::operator->() const
835 Peer* PeerHelper::operator&() const
840 bool PeerHelper::operator!() {
844 bool PeerHelper::operator!=(void* ptr)
846 return ((void*) m_peer != ptr);
849 bool Peer::IncUseCount()
851 MutexAutoLock lock(m_exclusive_access_mutex);
853 if (!m_pending_deletion) {
861 void Peer::DecUseCount()
864 MutexAutoLock lock(m_exclusive_access_mutex);
865 sanity_check(m_usage > 0);
868 if (!((m_pending_deletion) && (m_usage == 0)))
874 void Peer::RTTStatistics(float rtt, const std::string &profiler_id,
875 unsigned int num_samples) {
877 if (m_last_rtt > 0) {
878 /* set min max values */
879 if (rtt < m_rtt.min_rtt)
881 if (rtt >= m_rtt.max_rtt)
884 /* do average calculation */
885 if (m_rtt.avg_rtt < 0.0)
888 m_rtt.avg_rtt = m_rtt.avg_rtt * (num_samples/(num_samples-1)) +
889 rtt * (1/num_samples);
891 /* do jitter calculation */
893 //just use some neutral value at beginning
894 float jitter = m_rtt.jitter_min;
896 if (rtt > m_last_rtt)
897 jitter = rtt-m_last_rtt;
899 if (rtt <= m_last_rtt)
900 jitter = m_last_rtt - rtt;
902 if (jitter < m_rtt.jitter_min)
903 m_rtt.jitter_min = jitter;
904 if (jitter >= m_rtt.jitter_max)
905 m_rtt.jitter_max = jitter;
907 if (m_rtt.jitter_avg < 0.0)
908 m_rtt.jitter_avg = jitter;
910 m_rtt.jitter_avg = m_rtt.jitter_avg * (num_samples/(num_samples-1)) +
911 jitter * (1/num_samples);
913 if (!profiler_id.empty()) {
914 g_profiler->graphAdd(profiler_id + "_rtt", rtt);
915 g_profiler->graphAdd(profiler_id + "_jitter", jitter);
918 /* save values required for next loop */
922 bool Peer::isTimedOut(float timeout)
924 MutexAutoLock lock(m_exclusive_access_mutex);
925 u64 current_time = porting::getTimeMs();
927 float dtime = CALC_DTIME(m_last_timeout_check,current_time);
928 m_last_timeout_check = current_time;
930 m_timeout_counter += dtime;
932 return m_timeout_counter > timeout;
938 MutexAutoLock usage_lock(m_exclusive_access_mutex);
939 m_pending_deletion = true;
944 PROFILE(std::stringstream peerIdentifier1);
945 PROFILE(peerIdentifier1 << "runTimeouts[" << m_connection->getDesc()
946 << ";" << id << ";RELIABLE]");
947 PROFILE(g_profiler->remove(peerIdentifier1.str()));
948 PROFILE(std::stringstream peerIdentifier2);
949 PROFILE(peerIdentifier2 << "sendPackets[" << m_connection->getDesc()
950 << ";" << id << ";RELIABLE]");
951 PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier2.str(), SPT_AVG));
956 UDPPeer::UDPPeer(u16 a_id, Address a_address, Connection* connection) :
957 Peer(a_address,a_id,connection)
961 bool UDPPeer::getAddress(MTProtocols type,Address& toset)
963 if ((type == MTP_UDP) || (type == MTP_MINETEST_RELIABLE_UDP) || (type == MTP_PRIMARY))
972 void UDPPeer::setNonLegacyPeer()
974 m_legacy_peer = false;
975 for(unsigned int i=0; i< CHANNEL_COUNT; i++)
977 channels->setWindowSize(g_settings->getU16("max_packets_per_iteration"));
981 void UDPPeer::reportRTT(float rtt)
986 RTTStatistics(rtt,"rudp",MAX_RELIABLE_WINDOW_SIZE*10);
988 float timeout = getStat(AVG_RTT) * RESEND_TIMEOUT_FACTOR;
989 if (timeout < RESEND_TIMEOUT_MIN)
990 timeout = RESEND_TIMEOUT_MIN;
991 if (timeout > RESEND_TIMEOUT_MAX)
992 timeout = RESEND_TIMEOUT_MAX;
994 MutexAutoLock usage_lock(m_exclusive_access_mutex);
995 resend_timeout = timeout;
998 bool UDPPeer::Ping(float dtime,SharedBuffer<u8>& data)
1000 m_ping_timer += dtime;
1001 if (m_ping_timer >= PING_TIMEOUT)
1003 // Create and send PING packet
1004 writeU8(&data[0], TYPE_CONTROL);
1005 writeU8(&data[1], CONTROLTYPE_PING);
1012 void UDPPeer::PutReliableSendCommand(ConnectionCommand &c,
1013 unsigned int max_packet_size)
1015 if (m_pending_disconnect)
1018 if ( channels[c.channelnum].queued_commands.empty() &&
1019 /* don't queue more packets then window size */
1020 (channels[c.channelnum].queued_reliables.size()
1021 < (channels[c.channelnum].getWindowSize()/2))) {
1022 LOG(dout_con<<m_connection->getDesc()
1023 <<" processing reliable command for peer id: " << c.peer_id
1024 <<" data size: " << c.data.getSize() << std::endl);
1025 if (!processReliableSendCommand(c,max_packet_size)) {
1026 channels[c.channelnum].queued_commands.push_back(c);
1030 LOG(dout_con<<m_connection->getDesc()
1031 <<" Queueing reliable command for peer id: " << c.peer_id
1032 <<" data size: " << c.data.getSize() <<std::endl);
1033 channels[c.channelnum].queued_commands.push_back(c);
1037 bool UDPPeer::processReliableSendCommand(
1038 ConnectionCommand &c,
1039 unsigned int max_packet_size)
1041 if (m_pending_disconnect)
1044 u32 chunksize_max = max_packet_size
1046 - RELIABLE_HEADER_SIZE;
1048 sanity_check(c.data.getSize() < MAX_RELIABLE_WINDOW_SIZE*512);
1050 std::list<SharedBuffer<u8> > originals;
1051 u16 split_sequence_number = channels[c.channelnum].readNextSplitSeqNum();
1055 originals.emplace_back(c.data);
1058 originals = makeAutoSplitPacket(c.data, chunksize_max,split_sequence_number);
1059 channels[c.channelnum].setNextSplitSeqNum(split_sequence_number);
1062 bool have_sequence_number = true;
1063 bool have_initial_sequence_number = false;
1064 std::queue<BufferedPacket> toadd;
1065 volatile u16 initial_sequence_number = 0;
1067 for (SharedBuffer<u8> &original : originals) {
1068 u16 seqnum = channels[c.channelnum].getOutgoingSequenceNumber(have_sequence_number);
1070 /* oops, we don't have enough sequence numbers to send this packet */
1071 if (!have_sequence_number)
1074 if (!have_initial_sequence_number)
1076 initial_sequence_number = seqnum;
1077 have_initial_sequence_number = true;
1080 SharedBuffer<u8> reliable = makeReliablePacket(original, seqnum);
1082 // Add base headers and make a packet
1083 BufferedPacket p = con::makePacket(address, reliable,
1084 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1090 if (have_sequence_number) {
1091 volatile u16 pcount = 0;
1092 while (!toadd.empty()) {
1093 BufferedPacket p = toadd.front();
1095 // LOG(dout_con<<connection->getDesc()
1096 // << " queuing reliable packet for peer_id: " << c.peer_id
1097 // << " channel: " << (c.channelnum&0xFF)
1098 // << " seqnum: " << readU16(&p.data[BASE_HEADER_SIZE+1])
1100 channels[c.channelnum].queued_reliables.push(p);
1103 sanity_check(channels[c.channelnum].queued_reliables.size() < 0xFFFF);
1107 volatile u16 packets_available = toadd.size();
1108 /* we didn't get a single sequence number no need to fill queue */
1109 if (!have_initial_sequence_number) {
1113 while (!toadd.empty()) {
1117 bool successfully_put_back_sequence_number
1118 = channels[c.channelnum].putBackSequenceNumber(
1119 (initial_sequence_number+toadd.size() % (SEQNUM_MAX+1)));
1121 FATAL_ERROR_IF(!successfully_put_back_sequence_number, "error");
1124 LOG(dout_con<<m_connection->getDesc()
1125 << " Windowsize exceeded on reliable sending "
1126 << c.data.getSize() << " bytes"
1127 << std::endl << "\t\tinitial_sequence_number: "
1128 << initial_sequence_number
1129 << std::endl << "\t\tgot at most : "
1130 << packets_available << " packets"
1131 << std::endl << "\t\tpackets queued : "
1132 << channels[c.channelnum].outgoing_reliables_sent.size()
1138 void UDPPeer::RunCommandQueues(
1139 unsigned int max_packet_size,
1140 unsigned int maxcommands,
1141 unsigned int maxtransfer)
1144 for (Channel &channel : channels) {
1145 unsigned int commands_processed = 0;
1147 if ((!channel.queued_commands.empty()) &&
1148 (channel.queued_reliables.size() < maxtransfer) &&
1149 (commands_processed < maxcommands)) {
1151 ConnectionCommand c = channel.queued_commands.front();
1153 LOG(dout_con << m_connection->getDesc()
1154 << " processing queued reliable command " << std::endl);
1156 // Packet is processed, remove it from queue
1157 if (processReliableSendCommand(c,max_packet_size)) {
1158 channel.queued_commands.pop_front();
1160 LOG(dout_con << m_connection->getDesc()
1161 << " Failed to queue packets for peer_id: " << c.peer_id
1162 << ", delaying sending of " << c.data.getSize()
1163 << " bytes" << std::endl);
1166 catch (ItemNotFoundException &e) {
1167 // intentionally empty
1173 u16 UDPPeer::getNextSplitSequenceNumber(u8 channel)
1175 assert(channel < CHANNEL_COUNT); // Pre-condition
1176 return channels[channel].readNextSplitSeqNum();
1179 void UDPPeer::setNextSplitSequenceNumber(u8 channel, u16 seqnum)
1181 assert(channel < CHANNEL_COUNT); // Pre-condition
1182 channels[channel].setNextSplitSeqNum(seqnum);
1185 SharedBuffer<u8> UDPPeer::addSpiltPacket(u8 channel,
1186 BufferedPacket toadd,
1189 assert(channel < CHANNEL_COUNT); // Pre-condition
1190 return channels[channel].incoming_splits.insert(toadd,reliable);
1193 /******************************************************************************/
1194 /* Connection Threads */
1195 /******************************************************************************/
1197 ConnectionSendThread::ConnectionSendThread(unsigned int max_packet_size,
1199 Thread("ConnectionSend"),
1200 m_max_packet_size(max_packet_size),
1202 m_max_data_packets_per_iteration(g_settings->getU16("max_packets_per_iteration"))
1206 void * ConnectionSendThread::run()
1208 assert(m_connection);
1210 LOG(dout_con<<m_connection->getDesc()
1211 <<"ConnectionSend thread started"<<std::endl);
1213 u64 curtime = porting::getTimeMs();
1214 u64 lasttime = curtime;
1216 PROFILE(std::stringstream ThreadIdentifier);
1217 PROFILE(ThreadIdentifier << "ConnectionSend: [" << m_connection->getDesc() << "]");
1219 /* if stop is requested don't stop immediately but try to send all */
1221 while(!stopRequested() || packetsQueued()) {
1222 BEGIN_DEBUG_EXCEPTION_HANDLER
1223 PROFILE(ScopeProfiler sp(g_profiler, ThreadIdentifier.str(), SPT_AVG));
1225 m_iteration_packets_avaialble = m_max_data_packets_per_iteration;
1227 /* wait for trigger or timeout */
1228 m_send_sleep_semaphore.wait(50);
1230 /* remove all triggers */
1231 while(m_send_sleep_semaphore.wait(0)) {}
1234 curtime = porting::getTimeMs();
1235 float dtime = CALC_DTIME(lasttime,curtime);
1237 /* first do all the reliable stuff */
1240 /* translate commands to packets */
1241 ConnectionCommand c = m_connection->m_command_queue.pop_frontNoEx(0);
1242 while(c.type != CONNCMD_NONE)
1245 processReliableCommand(c);
1247 processNonReliableCommand(c);
1249 c = m_connection->m_command_queue.pop_frontNoEx(0);
1252 /* send non reliable packets */
1255 END_DEBUG_EXCEPTION_HANDLER
1258 PROFILE(g_profiler->remove(ThreadIdentifier.str()));
1262 void ConnectionSendThread::Trigger()
1264 m_send_sleep_semaphore.post();
1267 bool ConnectionSendThread::packetsQueued()
1269 std::list<u16> peerIds = m_connection->getPeerIDs();
1271 if (!m_outgoing_queue.empty() && !peerIds.empty())
1274 for (u16 peerId : peerIds) {
1275 PeerHelper peer = m_connection->getPeerNoEx(peerId);
1280 if (dynamic_cast<UDPPeer*>(&peer) == 0)
1283 for (Channel &channel : (dynamic_cast<UDPPeer *>(&peer))->channels) {
1284 if (channel.queued_commands.size() > 0) {
1294 void ConnectionSendThread::runTimeouts(float dtime)
1296 std::list<u16> timeouted_peers;
1297 std::list<u16> peerIds = m_connection->getPeerIDs();
1299 for (u16 &peerId : peerIds) {
1300 PeerHelper peer = m_connection->getPeerNoEx(peerId);
1305 if (dynamic_cast<UDPPeer*>(&peer) == 0)
1308 PROFILE(std::stringstream peerIdentifier);
1309 PROFILE(peerIdentifier << "runTimeouts[" << m_connection->getDesc()
1310 << ";" << peerId << ";RELIABLE]");
1311 PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier.str(), SPT_AVG));
1313 SharedBuffer<u8> data(2); // data for sending ping, required here because of goto
1318 if (peer->isTimedOut(m_timeout))
1320 infostream<<m_connection->getDesc()
1321 <<"RunTimeouts(): Peer "<<peer->id
1323 <<" (source=peer->timeout_counter)"
1325 // Add peer to the list
1326 timeouted_peers.push_back(peer->id);
1327 // Don't bother going through the buffers of this one
1331 float resend_timeout = dynamic_cast<UDPPeer*>(&peer)->getResendTimeout();
1332 bool retry_count_exceeded = false;
1333 for (Channel &channel : (dynamic_cast<UDPPeer *>(&peer))->channels) {
1334 std::list<BufferedPacket> timed_outs;
1336 if (dynamic_cast<UDPPeer*>(&peer)->getLegacyPeer())
1337 channel.setWindowSize(g_settings->getU16("workaround_window_size"));
1339 // Remove timed out incomplete unreliable split packets
1340 channel.incoming_splits.removeUnreliableTimedOuts(dtime, m_timeout);
1342 // Increment reliable packet times
1343 channel.outgoing_reliables_sent.incrementTimeouts(dtime);
1345 unsigned int numpeers = m_connection->m_peers.size();
1350 // Re-send timed out outgoing reliables
1351 timed_outs = channel.outgoing_reliables_sent.getTimedOuts(resend_timeout,
1352 (m_max_data_packets_per_iteration/numpeers));
1354 channel.UpdatePacketLossCounter(timed_outs.size());
1355 g_profiler->graphAdd("packets_lost", timed_outs.size());
1357 m_iteration_packets_avaialble -= timed_outs.size();
1359 for(std::list<BufferedPacket>::iterator k = timed_outs.begin();
1360 k != timed_outs.end(); ++k)
1362 u16 peer_id = readPeerId(*(k->data));
1363 u8 channelnum = readChannel(*(k->data));
1364 u16 seqnum = readU16(&(k->data[BASE_HEADER_SIZE+1]));
1366 channel.UpdateBytesLost(k->data.getSize());
1369 if (k-> resend_count > MAX_RELIABLE_RETRY) {
1370 retry_count_exceeded = true;
1371 timeouted_peers.push_back(peer->id);
1372 /* no need to check additional packets if a single one did timeout*/
1376 LOG(derr_con<<m_connection->getDesc()
1377 <<"RE-SENDING timed-out RELIABLE to "
1378 << k->address.serializeString()
1379 << "(t/o="<<resend_timeout<<"): "
1380 <<"from_peer_id="<<peer_id
1381 <<", channel="<<((int)channelnum&0xff)
1382 <<", seqnum="<<seqnum
1387 // do not handle rtt here as we can't decide if this packet was
1388 // lost or really takes more time to transmit
1391 if (retry_count_exceeded) {
1392 break; /* no need to check other channels if we already did timeout */
1395 channel.UpdateTimers(dtime,dynamic_cast<UDPPeer*>(&peer)->getLegacyPeer());
1398 /* skip to next peer if we did timeout */
1399 if (retry_count_exceeded)
1402 /* send ping if necessary */
1403 if (dynamic_cast<UDPPeer*>(&peer)->Ping(dtime,data)) {
1404 LOG(dout_con<<m_connection->getDesc()
1405 <<"Sending ping for peer_id: "
1406 << dynamic_cast<UDPPeer*>(&peer)->id <<std::endl);
1407 /* this may fail if there ain't a sequence number left */
1408 if (!rawSendAsPacket(dynamic_cast<UDPPeer*>(&peer)->id, 0, data, true))
1410 //retrigger with reduced ping interval
1411 dynamic_cast<UDPPeer*>(&peer)->Ping(4.0,data);
1415 dynamic_cast<UDPPeer*>(&peer)->RunCommandQueues(m_max_packet_size,
1416 m_max_commands_per_iteration,
1417 m_max_packets_requeued);
1420 // Remove timed out peers
1421 for (u16 timeouted_peer : timeouted_peers) {
1422 LOG(derr_con << m_connection->getDesc()
1423 << "RunTimeouts(): Removing peer "<< timeouted_peer <<std::endl);
1424 m_connection->deletePeer(timeouted_peer, true);
1428 void ConnectionSendThread::rawSend(const BufferedPacket &packet)
1431 m_connection->m_udpSocket.Send(packet.address, *packet.data,
1432 packet.data.getSize());
1433 LOG(dout_con <<m_connection->getDesc()
1434 << " rawSend: " << packet.data.getSize()
1435 << " bytes sent" << std::endl);
1436 } catch(SendFailedException &e) {
1437 LOG(derr_con<<m_connection->getDesc()
1438 <<"Connection::rawSend(): SendFailedException: "
1439 <<packet.address.serializeString()<<std::endl);
1443 void ConnectionSendThread::sendAsPacketReliable(BufferedPacket& p, Channel* channel)
1446 p.absolute_send_time = porting::getTimeMs();
1447 // Buffer the packet
1448 channel->outgoing_reliables_sent.insert(p,
1449 (channel->readOutgoingSequenceNumber() - MAX_RELIABLE_WINDOW_SIZE)
1450 % (MAX_RELIABLE_WINDOW_SIZE+1));
1452 catch(AlreadyExistsException &e)
1454 LOG(derr_con<<m_connection->getDesc()
1455 <<"WARNING: Going to send a reliable packet"
1456 <<" in outgoing buffer" <<std::endl);
1463 bool ConnectionSendThread::rawSendAsPacket(u16 peer_id, u8 channelnum,
1464 SharedBuffer<u8> data, bool reliable)
1466 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
1468 LOG(dout_con<<m_connection->getDesc()
1469 <<" INFO: dropped packet for non existent peer_id: "
1470 << peer_id << std::endl);
1471 FATAL_ERROR_IF(!reliable, "Trying to send raw packet reliable but no peer found!");
1474 Channel *channel = &(dynamic_cast<UDPPeer*>(&peer)->channels[channelnum]);
1478 bool have_sequence_number_for_raw_packet = true;
1480 channel->getOutgoingSequenceNumber(have_sequence_number_for_raw_packet);
1482 if (!have_sequence_number_for_raw_packet)
1485 SharedBuffer<u8> reliable = makeReliablePacket(data, seqnum);
1486 Address peer_address;
1487 peer->getAddress(MTP_MINETEST_RELIABLE_UDP, peer_address);
1489 // Add base headers and make a packet
1490 BufferedPacket p = con::makePacket(peer_address, reliable,
1491 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1494 // first check if our send window is already maxed out
1495 if (channel->outgoing_reliables_sent.size()
1496 < channel->getWindowSize()) {
1497 LOG(dout_con<<m_connection->getDesc()
1498 <<" INFO: sending a reliable packet to peer_id " << peer_id
1499 <<" channel: " << channelnum
1500 <<" seqnum: " << seqnum << std::endl);
1501 sendAsPacketReliable(p,channel);
1505 LOG(dout_con<<m_connection->getDesc()
1506 <<" INFO: queueing reliable packet for peer_id: " << peer_id
1507 <<" channel: " << channelnum
1508 <<" seqnum: " << seqnum << std::endl);
1509 channel->queued_reliables.push(p);
1513 Address peer_address;
1514 if (peer->getAddress(MTP_UDP, peer_address)) {
1515 // Add base headers and make a packet
1516 BufferedPacket p = con::makePacket(peer_address, data,
1517 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1525 LOG(dout_con << m_connection->getDesc()
1526 << " INFO: dropped unreliable packet for peer_id: " << peer_id
1527 << " because of (yet) missing udp address" << std::endl);
1531 void ConnectionSendThread::processReliableCommand(ConnectionCommand &c)
1533 assert(c.reliable); // Pre-condition
1537 LOG(dout_con<<m_connection->getDesc()
1538 <<"UDP processing reliable CONNCMD_NONE"<<std::endl);
1542 LOG(dout_con<<m_connection->getDesc()
1543 <<"UDP processing reliable CONNCMD_SEND"<<std::endl);
1547 case CONNCMD_SEND_TO_ALL:
1548 LOG(dout_con<<m_connection->getDesc()
1549 <<"UDP processing CONNCMD_SEND_TO_ALL"<<std::endl);
1550 sendToAllReliable(c);
1553 case CONCMD_CREATE_PEER:
1554 LOG(dout_con<<m_connection->getDesc()
1555 <<"UDP processing reliable CONCMD_CREATE_PEER"<<std::endl);
1556 if (!rawSendAsPacket(c.peer_id,c.channelnum,c.data,c.reliable))
1558 /* put to queue if we couldn't send it immediately */
1563 case CONCMD_DISABLE_LEGACY:
1564 LOG(dout_con<<m_connection->getDesc()
1565 <<"UDP processing reliable CONCMD_DISABLE_LEGACY"<<std::endl);
1566 if (!rawSendAsPacket(c.peer_id,c.channelnum,c.data,c.reliable))
1568 /* put to queue if we couldn't send it immediately */
1574 case CONNCMD_CONNECT:
1575 case CONNCMD_DISCONNECT:
1577 FATAL_ERROR("Got command that shouldn't be reliable as reliable command");
1579 LOG(dout_con<<m_connection->getDesc()
1580 <<" Invalid reliable command type: " << c.type <<std::endl);
1585 void ConnectionSendThread::processNonReliableCommand(ConnectionCommand &c)
1587 assert(!c.reliable); // Pre-condition
1591 LOG(dout_con<<m_connection->getDesc()
1592 <<" UDP processing CONNCMD_NONE"<<std::endl);
1595 LOG(dout_con<<m_connection->getDesc()
1596 <<" UDP processing CONNCMD_SERVE port="
1597 <<c.address.serializeString()<<std::endl);
1600 case CONNCMD_CONNECT:
1601 LOG(dout_con<<m_connection->getDesc()
1602 <<" UDP processing CONNCMD_CONNECT"<<std::endl);
1605 case CONNCMD_DISCONNECT:
1606 LOG(dout_con<<m_connection->getDesc()
1607 <<" UDP processing CONNCMD_DISCONNECT"<<std::endl);
1610 case CONNCMD_DISCONNECT_PEER:
1611 LOG(dout_con<<m_connection->getDesc()
1612 <<" UDP processing CONNCMD_DISCONNECT_PEER"<<std::endl);
1613 disconnect_peer(c.peer_id);
1616 LOG(dout_con<<m_connection->getDesc()
1617 <<" UDP processing CONNCMD_SEND"<<std::endl);
1618 send(c.peer_id, c.channelnum, c.data);
1620 case CONNCMD_SEND_TO_ALL:
1621 LOG(dout_con<<m_connection->getDesc()
1622 <<" UDP processing CONNCMD_SEND_TO_ALL"<<std::endl);
1623 sendToAll(c.channelnum, c.data);
1626 LOG(dout_con<<m_connection->getDesc()
1627 <<" UDP processing CONCMD_ACK"<<std::endl);
1628 sendAsPacket(c.peer_id,c.channelnum,c.data,true);
1630 case CONCMD_CREATE_PEER:
1631 FATAL_ERROR("Got command that should be reliable as unreliable command");
1633 LOG(dout_con<<m_connection->getDesc()
1634 <<" Invalid command type: " << c.type <<std::endl);
1638 void ConnectionSendThread::serve(Address bind_address)
1640 LOG(dout_con<<m_connection->getDesc()
1641 <<"UDP serving at port " << bind_address.serializeString() <<std::endl);
1643 m_connection->m_udpSocket.Bind(bind_address);
1644 m_connection->SetPeerID(PEER_ID_SERVER);
1646 catch(SocketException &e) {
1650 m_connection->putEvent(ce);
1654 void ConnectionSendThread::connect(Address address)
1656 LOG(dout_con<<m_connection->getDesc()<<" connecting to "<<address.serializeString()
1657 <<":"<<address.getPort()<<std::endl);
1659 UDPPeer *peer = m_connection->createServerPeer(address);
1663 e.peerAdded(peer->id, peer->address);
1664 m_connection->putEvent(e);
1668 if (address.isIPv6())
1669 bind_addr.setAddress((IPv6AddressBytes*) NULL);
1671 bind_addr.setAddress(0,0,0,0);
1673 m_connection->m_udpSocket.Bind(bind_addr);
1675 // Send a dummy packet to server with peer_id = PEER_ID_INEXISTENT
1676 m_connection->SetPeerID(PEER_ID_INEXISTENT);
1677 NetworkPacket pkt(0,0);
1678 m_connection->Send(PEER_ID_SERVER, 0, &pkt, true);
1681 void ConnectionSendThread::disconnect()
1683 LOG(dout_con<<m_connection->getDesc()<<" disconnecting"<<std::endl);
1685 // Create and send DISCO packet
1686 SharedBuffer<u8> data(2);
1687 writeU8(&data[0], TYPE_CONTROL);
1688 writeU8(&data[1], CONTROLTYPE_DISCO);
1692 std::list<u16> peerids = m_connection->getPeerIDs();
1694 for (u16 peerid : peerids) {
1695 sendAsPacket(peerid, 0,data,false);
1699 void ConnectionSendThread::disconnect_peer(u16 peer_id)
1701 LOG(dout_con<<m_connection->getDesc()<<" disconnecting peer"<<std::endl);
1703 // Create and send DISCO packet
1704 SharedBuffer<u8> data(2);
1705 writeU8(&data[0], TYPE_CONTROL);
1706 writeU8(&data[1], CONTROLTYPE_DISCO);
1707 sendAsPacket(peer_id, 0,data,false);
1709 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
1714 if (dynamic_cast<UDPPeer*>(&peer) == 0)
1719 dynamic_cast<UDPPeer*>(&peer)->m_pending_disconnect = true;
1722 void ConnectionSendThread::send(u16 peer_id, u8 channelnum,
1723 SharedBuffer<u8> data)
1725 assert(channelnum < CHANNEL_COUNT); // Pre-condition
1727 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
1730 LOG(dout_con<<m_connection->getDesc()<<" peer: peer_id="<<peer_id
1731 << ">>>NOT<<< found on sending packet"
1732 << ", channel " << (channelnum % 0xFF)
1733 << ", size: " << data.getSize() <<std::endl);
1737 LOG(dout_con<<m_connection->getDesc()<<" sending to peer_id="<<peer_id
1738 << ", channel " << (channelnum % 0xFF)
1739 << ", size: " << data.getSize() <<std::endl);
1741 u16 split_sequence_number = peer->getNextSplitSequenceNumber(channelnum);
1743 u32 chunksize_max = m_max_packet_size - BASE_HEADER_SIZE;
1744 std::list<SharedBuffer<u8> > originals;
1746 originals = makeAutoSplitPacket(data, chunksize_max,split_sequence_number);
1748 peer->setNextSplitSequenceNumber(channelnum,split_sequence_number);
1750 for (const SharedBuffer<u8> &original : originals) {
1751 sendAsPacket(peer_id, channelnum, original);
1755 void ConnectionSendThread::sendReliable(ConnectionCommand &c)
1757 PeerHelper peer = m_connection->getPeerNoEx(c.peer_id);
1761 peer->PutReliableSendCommand(c,m_max_packet_size);
1764 void ConnectionSendThread::sendToAll(u8 channelnum, SharedBuffer<u8> data)
1766 std::list<u16> peerids = m_connection->getPeerIDs();
1768 for (u16 peerid : peerids) {
1769 send(peerid, channelnum, data);
1773 void ConnectionSendThread::sendToAllReliable(ConnectionCommand &c)
1775 std::list<u16> peerids = m_connection->getPeerIDs();
1777 for (u16 peerid : peerids) {
1778 PeerHelper peer = m_connection->getPeerNoEx(peerid);
1783 peer->PutReliableSendCommand(c,m_max_packet_size);
1787 void ConnectionSendThread::sendPackets(float dtime)
1789 std::list<u16> peerIds = m_connection->getPeerIDs();
1790 std::list<u16> pendingDisconnect;
1791 std::map<u16,bool> pending_unreliable;
1793 for (u16 peerId : peerIds) {
1794 PeerHelper peer = m_connection->getPeerNoEx(peerId);
1795 //peer may have been removed
1797 LOG(dout_con<<m_connection->getDesc()<< " Peer not found: peer_id=" << peerId
1801 peer->m_increment_packets_remaining = m_iteration_packets_avaialble/m_connection->m_peers.size();
1803 UDPPeer *udpPeer = dynamic_cast<UDPPeer*>(&peer);
1809 if (udpPeer->m_pending_disconnect) {
1810 pendingDisconnect.push_back(peerId);
1813 PROFILE(std::stringstream peerIdentifier);
1814 PROFILE(peerIdentifier << "sendPackets[" << m_connection->getDesc() << ";" << peerId
1816 PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier.str(), SPT_AVG));
1818 LOG(dout_con<<m_connection->getDesc()
1819 << " Handle per peer queues: peer_id=" << peerId
1820 << " packet quota: " << peer->m_increment_packets_remaining << std::endl);
1822 // first send queued reliable packets for all peers (if possible)
1823 for (unsigned int i=0; i < CHANNEL_COUNT; i++) {
1824 Channel &channel = udpPeer->channels[i];
1825 u16 next_to_ack = 0;
1827 channel.outgoing_reliables_sent.getFirstSeqnum(next_to_ack);
1828 u16 next_to_receive = 0;
1829 channel.incoming_reliables.getFirstSeqnum(next_to_receive);
1831 LOG(dout_con<<m_connection->getDesc()<< "\t channel: "
1832 << i << ", peer quota:"
1833 << peer->m_increment_packets_remaining
1835 << "\t\t\treliables on wire: "
1836 << channel.outgoing_reliables_sent.size()
1837 << ", waiting for ack for " << next_to_ack
1839 << "\t\t\tincoming_reliables: "
1840 << channel.incoming_reliables.size()
1841 << ", next reliable packet: "
1842 << channel.readNextIncomingSeqNum()
1843 << ", next queued: " << next_to_receive
1845 << "\t\t\treliables queued : "
1846 << channel.queued_reliables.size()
1848 << "\t\t\tqueued commands : "
1849 << channel.queued_commands.size()
1852 while ((!channel.queued_reliables.empty()) &&
1853 (channel.outgoing_reliables_sent.size()
1854 < channel.getWindowSize())&&
1855 (peer->m_increment_packets_remaining > 0))
1857 BufferedPacket p = channel.queued_reliables.front();
1858 channel.queued_reliables.pop();
1859 LOG(dout_con<<m_connection->getDesc()
1860 <<" INFO: sending a queued reliable packet "
1862 <<", seqnum: " << readU16(&p.data[BASE_HEADER_SIZE+1])
1864 sendAsPacketReliable(p, &channel);
1865 peer->m_increment_packets_remaining--;
1870 if (!m_outgoing_queue.empty()) {
1871 LOG(dout_con<<m_connection->getDesc()
1872 << " Handle non reliable queue ("
1873 << m_outgoing_queue.size() << " pkts)" << std::endl);
1876 unsigned int initial_queuesize = m_outgoing_queue.size();
1877 /* send non reliable packets*/
1878 for(unsigned int i=0;i < initial_queuesize;i++) {
1879 OutgoingPacket packet = m_outgoing_queue.front();
1880 m_outgoing_queue.pop();
1882 if (packet.reliable)
1885 PeerHelper peer = m_connection->getPeerNoEx(packet.peer_id);
1887 LOG(dout_con<<m_connection->getDesc()
1888 <<" Outgoing queue: peer_id="<<packet.peer_id
1889 << ">>>NOT<<< found on sending packet"
1890 << ", channel " << (packet.channelnum % 0xFF)
1891 << ", size: " << packet.data.getSize() <<std::endl);
1895 /* send acks immediately */
1897 rawSendAsPacket(packet.peer_id, packet.channelnum,
1898 packet.data, packet.reliable);
1899 peer->m_increment_packets_remaining =
1900 MYMIN(0,peer->m_increment_packets_remaining--);
1903 ( peer->m_increment_packets_remaining > 0) ||
1904 (stopRequested())) {
1905 rawSendAsPacket(packet.peer_id, packet.channelnum,
1906 packet.data, packet.reliable);
1907 peer->m_increment_packets_remaining--;
1910 m_outgoing_queue.push(packet);
1911 pending_unreliable[packet.peer_id] = true;
1915 for (u16 peerId : pendingDisconnect) {
1916 if (!pending_unreliable[peerId])
1918 m_connection->deletePeer(peerId,false);
1923 void ConnectionSendThread::sendAsPacket(u16 peer_id, u8 channelnum,
1924 SharedBuffer<u8> data, bool ack)
1926 OutgoingPacket packet(peer_id, channelnum, data, false, ack);
1927 m_outgoing_queue.push(packet);
1930 ConnectionReceiveThread::ConnectionReceiveThread(unsigned int max_packet_size) :
1931 Thread("ConnectionReceive")
1935 void * ConnectionReceiveThread::run()
1937 assert(m_connection);
1939 LOG(dout_con<<m_connection->getDesc()
1940 <<"ConnectionReceive thread started"<<std::endl);
1942 PROFILE(std::stringstream ThreadIdentifier);
1943 PROFILE(ThreadIdentifier << "ConnectionReceive: [" << m_connection->getDesc() << "]");
1945 #ifdef DEBUG_CONNECTION_KBPS
1946 u64 curtime = porting::getTimeMs();
1947 u64 lasttime = curtime;
1948 float debug_print_timer = 0.0;
1951 while(!stopRequested()) {
1952 BEGIN_DEBUG_EXCEPTION_HANDLER
1953 PROFILE(ScopeProfiler sp(g_profiler, ThreadIdentifier.str(), SPT_AVG));
1955 #ifdef DEBUG_CONNECTION_KBPS
1957 curtime = porting::getTimeMs();
1958 float dtime = CALC_DTIME(lasttime,curtime);
1961 /* receive packets */
1964 #ifdef DEBUG_CONNECTION_KBPS
1965 debug_print_timer += dtime;
1966 if (debug_print_timer > 20.0) {
1967 debug_print_timer -= 20.0;
1969 std::list<u16> peerids = m_connection->getPeerIDs();
1971 for (std::list<u16>::iterator i = peerids.begin();
1975 PeerHelper peer = m_connection->getPeerNoEx(*i);
1979 float peer_current = 0.0;
1980 float peer_loss = 0.0;
1981 float avg_rate = 0.0;
1982 float avg_loss = 0.0;
1984 for(u16 j=0; j<CHANNEL_COUNT; j++)
1986 peer_current +=peer->channels[j].getCurrentDownloadRateKB();
1987 peer_loss += peer->channels[j].getCurrentLossRateKB();
1988 avg_rate += peer->channels[j].getAvgDownloadRateKB();
1989 avg_loss += peer->channels[j].getAvgLossRateKB();
1992 std::stringstream output;
1993 output << std::fixed << std::setprecision(1);
1994 output << "OUT to Peer " << *i << " RATES (good / loss) " << std::endl;
1995 output << "\tcurrent (sum): " << peer_current << "kb/s "<< peer_loss << "kb/s" << std::endl;
1996 output << "\taverage (sum): " << avg_rate << "kb/s "<< avg_loss << "kb/s" << std::endl;
1997 output << std::setfill(' ');
1998 for(u16 j=0; j<CHANNEL_COUNT; j++)
2000 output << "\tcha " << j << ":"
2001 << " CUR: " << std::setw(6) << peer->channels[j].getCurrentDownloadRateKB() <<"kb/s"
2002 << " AVG: " << std::setw(6) << peer->channels[j].getAvgDownloadRateKB() <<"kb/s"
2003 << " MAX: " << std::setw(6) << peer->channels[j].getMaxDownloadRateKB() <<"kb/s"
2005 << " CUR: " << std::setw(6) << peer->channels[j].getCurrentLossRateKB() <<"kb/s"
2006 << " AVG: " << std::setw(6) << peer->channels[j].getAvgLossRateKB() <<"kb/s"
2007 << " MAX: " << std::setw(6) << peer->channels[j].getMaxLossRateKB() <<"kb/s"
2008 << " / WS: " << peer->channels[j].getWindowSize()
2012 fprintf(stderr,"%s\n",output.str().c_str());
2016 END_DEBUG_EXCEPTION_HANDLER
2019 PROFILE(g_profiler->remove(ThreadIdentifier.str()));
2023 // Receive packets from the network and buffers and create ConnectionEvents
2024 void ConnectionReceiveThread::receive()
2026 // use IPv6 minimum allowed MTU as receive buffer size as this is
2027 // theoretical reliable upper boundary of a udp packet for all IPv6 enabled
2029 unsigned int packet_maxsize = 1500;
2030 SharedBuffer<u8> packetdata(packet_maxsize);
2032 bool packet_queued = true;
2034 unsigned int loop_count = 0;
2036 /* first of all read packets from socket */
2037 /* check for incoming data available */
2038 while( (loop_count < 10) &&
2039 (m_connection->m_udpSocket.WaitData(50))) {
2042 if (packet_queued) {
2043 bool data_left = true;
2045 SharedBuffer<u8> resultdata;
2048 data_left = getFromBuffers(peer_id, resultdata);
2051 e.dataReceived(peer_id, resultdata);
2052 m_connection->putEvent(e);
2055 catch(ProcessedSilentlyException &e) {
2056 /* try reading again */
2059 packet_queued = false;
2063 s32 received_size = m_connection->m_udpSocket.Receive(sender, *packetdata, packet_maxsize);
2065 if ((received_size < BASE_HEADER_SIZE) ||
2066 (readU32(&packetdata[0]) != m_connection->GetProtocolID()))
2068 LOG(derr_con<<m_connection->getDesc()
2069 <<"Receive(): Invalid incoming packet, "
2070 <<"size: " << received_size
2072 << ((received_size >= 4) ? readU32(&packetdata[0]) : -1)
2077 u16 peer_id = readPeerId(*packetdata);
2078 u8 channelnum = readChannel(*packetdata);
2080 if (channelnum > CHANNEL_COUNT-1) {
2081 LOG(derr_con<<m_connection->getDesc()
2082 <<"Receive(): Invalid channel "<<channelnum<<std::endl);
2083 throw InvalidIncomingDataException("Channel doesn't exist");
2086 /* Try to identify peer by sender address (may happen on join) */
2087 if (peer_id == PEER_ID_INEXISTENT) {
2088 peer_id = m_connection->lookupPeer(sender);
2089 // We do not have to remind the peer of its
2090 // peer id as the CONTROLTYPE_SET_PEER_ID
2091 // command was sent reliably.
2094 /* The peer was not found in our lists. Add it. */
2095 if (peer_id == PEER_ID_INEXISTENT) {
2096 peer_id = m_connection->createPeer(sender, MTP_MINETEST_RELIABLE_UDP, 0);
2099 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
2102 LOG(dout_con<<m_connection->getDesc()
2103 <<" got packet from unknown peer_id: "
2104 <<peer_id<<" Ignoring."<<std::endl);
2108 // Validate peer address
2110 Address peer_address;
2112 if (peer->getAddress(MTP_UDP, peer_address)) {
2113 if (peer_address != sender) {
2114 LOG(derr_con<<m_connection->getDesc()
2115 <<m_connection->getDesc()
2116 <<" Peer "<<peer_id<<" sending from different address."
2117 " Ignoring."<<std::endl);
2123 bool invalid_address = true;
2124 if (invalid_address) {
2125 LOG(derr_con<<m_connection->getDesc()
2126 <<m_connection->getDesc()
2127 <<" Peer "<<peer_id<<" unknown."
2128 " Ignoring."<<std::endl);
2133 peer->ResetTimeout();
2135 Channel *channel = 0;
2137 if (dynamic_cast<UDPPeer*>(&peer) != 0)
2139 channel = &(dynamic_cast<UDPPeer*>(&peer)->channels[channelnum]);
2143 channel->UpdateBytesReceived(received_size);
2146 // Throw the received packet to channel->processPacket()
2148 // Make a new SharedBuffer from the data without the base headers
2149 SharedBuffer<u8> strippeddata(received_size - BASE_HEADER_SIZE);
2150 memcpy(*strippeddata, &packetdata[BASE_HEADER_SIZE],
2151 strippeddata.getSize());
2154 // Process it (the result is some data with no headers made by us)
2155 SharedBuffer<u8> resultdata = processPacket
2156 (channel, strippeddata, peer_id, channelnum, false);
2158 LOG(dout_con<<m_connection->getDesc()
2159 <<" ProcessPacket from peer_id: " << peer_id
2160 << ",channel: " << (channelnum & 0xFF) << ", returned "
2161 << resultdata.getSize() << " bytes" <<std::endl);
2164 e.dataReceived(peer_id, resultdata);
2165 m_connection->putEvent(e);
2167 catch(ProcessedSilentlyException &e) {
2169 catch(ProcessedQueued &e) {
2170 packet_queued = true;
2173 catch(InvalidIncomingDataException &e) {
2175 catch(ProcessedSilentlyException &e) {
2180 bool ConnectionReceiveThread::getFromBuffers(u16 &peer_id, SharedBuffer<u8> &dst)
2182 std::list<u16> peerids = m_connection->getPeerIDs();
2184 for (u16 peerid : peerids) {
2185 PeerHelper peer = m_connection->getPeerNoEx(peerid);
2189 if (dynamic_cast<UDPPeer*>(&peer) == 0)
2192 for (Channel &channel : (dynamic_cast<UDPPeer *>(&peer))->channels) {
2193 if (checkIncomingBuffers(&channel, peer_id, dst)) {
2201 bool ConnectionReceiveThread::checkIncomingBuffers(Channel *channel,
2202 u16 &peer_id, SharedBuffer<u8> &dst)
2204 u16 firstseqnum = 0;
2205 if (channel->incoming_reliables.getFirstSeqnum(firstseqnum))
2207 if (firstseqnum == channel->readNextIncomingSeqNum())
2209 BufferedPacket p = channel->incoming_reliables.popFirst();
2210 peer_id = readPeerId(*p.data);
2211 u8 channelnum = readChannel(*p.data);
2212 u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]);
2214 LOG(dout_con<<m_connection->getDesc()
2215 <<"UNBUFFERING TYPE_RELIABLE"
2216 <<" seqnum="<<seqnum
2217 <<" peer_id="<<peer_id
2218 <<" channel="<<((int)channelnum&0xff)
2221 channel->incNextIncomingSeqNum();
2223 u32 headers_size = BASE_HEADER_SIZE + RELIABLE_HEADER_SIZE;
2224 // Get out the inside packet and re-process it
2225 SharedBuffer<u8> payload(p.data.getSize() - headers_size);
2226 memcpy(*payload, &p.data[headers_size], payload.getSize());
2228 dst = processPacket(channel, payload, peer_id, channelnum, true);
2235 SharedBuffer<u8> ConnectionReceiveThread::processPacket(Channel *channel,
2236 SharedBuffer<u8> packetdata, u16 peer_id, u8 channelnum, bool reliable)
2238 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
2241 errorstream << "Peer not found (possible timeout)" << std::endl;
2242 throw ProcessedSilentlyException("Peer not found (possible timeout)");
2245 if (packetdata.getSize() < 1)
2246 throw InvalidIncomingDataException("packetdata.getSize() < 1");
2248 u8 type = readU8(&(packetdata[0]));
2250 if (MAX_UDP_PEERS <= 65535 && peer_id >= MAX_UDP_PEERS) {
2251 std::string errmsg = "Invalid peer_id=" + itos(peer_id);
2252 errorstream << errmsg << std::endl;
2253 throw InvalidIncomingDataException(errmsg.c_str());
2256 if (type == TYPE_CONTROL)
2258 if (packetdata.getSize() < 2)
2259 throw InvalidIncomingDataException("packetdata.getSize() < 2");
2261 u8 controltype = readU8(&(packetdata[1]));
2263 if (controltype == CONTROLTYPE_ACK)
2265 assert(channel != NULL);
2267 if (packetdata.getSize() < 4) {
2268 throw InvalidIncomingDataException(
2269 "packetdata.getSize() < 4 (ACK header size)");
2272 u16 seqnum = readU16(&packetdata[2]);
2273 LOG(dout_con<<m_connection->getDesc()
2274 <<" [ CONTROLTYPE_ACK: channelnum="
2275 <<((int)channelnum&0xff)<<", peer_id="<<peer_id
2276 <<", seqnum="<<seqnum<< " ]"<<std::endl);
2280 channel->outgoing_reliables_sent.popSeqnum(seqnum);
2282 // only calculate rtt from straight sent packets
2283 if (p.resend_count == 0) {
2284 // Get round trip time
2285 u64 current_time = porting::getTimeMs();
2287 // a overflow is quite unlikely but as it'd result in major
2288 // rtt miscalculation we handle it here
2289 if (current_time > p.absolute_send_time)
2291 float rtt = (current_time - p.absolute_send_time) / 1000.0;
2293 // Let peer calculate stuff according to it
2294 // (avg_rtt and resend_timeout)
2295 dynamic_cast<UDPPeer*>(&peer)->reportRTT(rtt);
2297 else if (p.totaltime > 0)
2299 float rtt = p.totaltime;
2301 // Let peer calculate stuff according to it
2302 // (avg_rtt and resend_timeout)
2303 dynamic_cast<UDPPeer*>(&peer)->reportRTT(rtt);
2306 //put bytes for max bandwidth calculation
2307 channel->UpdateBytesSent(p.data.getSize(),1);
2308 if (channel->outgoing_reliables_sent.size() == 0)
2310 m_connection->TriggerSend();
2313 catch(NotFoundException &e) {
2314 LOG(derr_con<<m_connection->getDesc()
2315 <<"WARNING: ACKed packet not "
2318 channel->UpdatePacketTooLateCounter();
2320 throw ProcessedSilentlyException("Got an ACK");
2322 else if (controltype == CONTROLTYPE_SET_PEER_ID) {
2323 // Got a packet to set our peer id
2324 if (packetdata.getSize() < 4)
2325 throw InvalidIncomingDataException
2326 ("packetdata.getSize() < 4 (SET_PEER_ID header size)");
2327 u16 peer_id_new = readU16(&packetdata[2]);
2328 LOG(dout_con<<m_connection->getDesc()
2329 <<"Got new peer id: "<<peer_id_new<<"... "<<std::endl);
2331 if (m_connection->GetPeerID() != PEER_ID_INEXISTENT)
2333 LOG(derr_con<<m_connection->getDesc()
2334 <<"WARNING: Not changing"
2335 " existing peer id."<<std::endl);
2339 LOG(dout_con<<m_connection->getDesc()<<"changing own peer id"<<std::endl);
2340 m_connection->SetPeerID(peer_id_new);
2343 ConnectionCommand cmd;
2345 SharedBuffer<u8> reply(2);
2346 writeU8(&reply[0], TYPE_CONTROL);
2347 writeU8(&reply[1], CONTROLTYPE_ENABLE_BIG_SEND_WINDOW);
2348 cmd.disableLegacy(PEER_ID_SERVER,reply);
2349 m_connection->putCommand(cmd);
2351 throw ProcessedSilentlyException("Got a SET_PEER_ID");
2353 else if (controltype == CONTROLTYPE_PING)
2355 // Just ignore it, the incoming data already reset
2356 // the timeout counter
2357 LOG(dout_con<<m_connection->getDesc()<<"PING"<<std::endl);
2358 throw ProcessedSilentlyException("Got a PING");
2360 else if (controltype == CONTROLTYPE_DISCO)
2362 // Just ignore it, the incoming data already reset
2363 // the timeout counter
2364 LOG(dout_con<<m_connection->getDesc()
2365 <<"DISCO: Removing peer "<<(peer_id)<<std::endl);
2367 if (!m_connection->deletePeer(peer_id, false)) {
2368 derr_con<<m_connection->getDesc()
2369 <<"DISCO: Peer not found"<<std::endl;
2372 throw ProcessedSilentlyException("Got a DISCO");
2374 else if (controltype == CONTROLTYPE_ENABLE_BIG_SEND_WINDOW)
2376 dynamic_cast<UDPPeer*>(&peer)->setNonLegacyPeer();
2377 throw ProcessedSilentlyException("Got non legacy control");
2380 LOG(derr_con<<m_connection->getDesc()
2381 <<"INVALID TYPE_CONTROL: invalid controltype="
2382 <<((int)controltype&0xff)<<std::endl);
2383 throw InvalidIncomingDataException("Invalid control type");
2386 else if (type == TYPE_ORIGINAL)
2388 if (packetdata.getSize() <= ORIGINAL_HEADER_SIZE)
2389 throw InvalidIncomingDataException
2390 ("packetdata.getSize() <= ORIGINAL_HEADER_SIZE");
2391 LOG(dout_con<<m_connection->getDesc()
2392 <<"RETURNING TYPE_ORIGINAL to user"
2394 // Get the inside packet out and return it
2395 SharedBuffer<u8> payload(packetdata.getSize() - ORIGINAL_HEADER_SIZE);
2396 memcpy(*payload, &(packetdata[ORIGINAL_HEADER_SIZE]), payload.getSize());
2399 else if (type == TYPE_SPLIT)
2401 Address peer_address;
2403 if (peer->getAddress(MTP_UDP, peer_address)) {
2405 // We have to create a packet again for buffering
2406 // This isn't actually too bad an idea.
2407 BufferedPacket packet = makePacket(
2410 m_connection->GetProtocolID(),
2414 // Buffer the packet
2415 SharedBuffer<u8> data =
2416 peer->addSpiltPacket(channelnum,packet,reliable);
2418 if (data.getSize() != 0)
2420 LOG(dout_con<<m_connection->getDesc()
2421 <<"RETURNING TYPE_SPLIT: Constructed full data, "
2422 <<"size="<<data.getSize()<<std::endl);
2425 LOG(dout_con<<m_connection->getDesc()<<"BUFFERED TYPE_SPLIT"<<std::endl);
2426 throw ProcessedSilentlyException("Buffered a split packet chunk");
2429 //TODO throw some error
2432 else if (type == TYPE_RELIABLE)
2434 assert(channel != NULL);
2436 // Recursive reliable packets not allowed
2438 throw InvalidIncomingDataException("Found nested reliable packets");
2440 if (packetdata.getSize() < RELIABLE_HEADER_SIZE)
2441 throw InvalidIncomingDataException
2442 ("packetdata.getSize() < RELIABLE_HEADER_SIZE");
2444 u16 seqnum = readU16(&packetdata[1]);
2445 bool is_future_packet = false;
2446 bool is_old_packet = false;
2448 /* packet is within our receive window send ack */
2449 if (seqnum_in_window(seqnum, channel->readNextIncomingSeqNum(),MAX_RELIABLE_WINDOW_SIZE))
2451 m_connection->sendAck(peer_id,channelnum,seqnum);
2454 is_future_packet = seqnum_higher(seqnum, channel->readNextIncomingSeqNum());
2455 is_old_packet = seqnum_higher(channel->readNextIncomingSeqNum(), seqnum);
2458 /* packet is not within receive window, don't send ack. *
2459 * if this was a valid packet it's gonna be retransmitted */
2460 if (is_future_packet)
2462 throw ProcessedSilentlyException("Received packet newer then expected, not sending ack");
2465 /* seems like our ack was lost, send another one for a old packet */
2468 LOG(dout_con<<m_connection->getDesc()
2469 << "RE-SENDING ACK: peer_id: " << peer_id
2470 << ", channel: " << (channelnum&0xFF)
2471 << ", seqnum: " << seqnum << std::endl;)
2472 m_connection->sendAck(peer_id,channelnum,seqnum);
2474 // we already have this packet so this one was on wire at least
2475 // the current timeout
2476 // we don't know how long this packet was on wire don't do silly guessing
2477 // dynamic_cast<UDPPeer*>(&peer)->reportRTT(dynamic_cast<UDPPeer*>(&peer)->getResendTimeout());
2479 throw ProcessedSilentlyException("Retransmitting ack for old packet");
2483 if (seqnum != channel->readNextIncomingSeqNum())
2485 Address peer_address;
2487 // this is a reliable packet so we have a udp address for sure
2488 peer->getAddress(MTP_MINETEST_RELIABLE_UDP, peer_address);
2489 // This one comes later, buffer it.
2490 // Actually we have to make a packet to buffer one.
2491 // Well, we have all the ingredients, so just do it.
2492 BufferedPacket packet = con::makePacket(
2495 m_connection->GetProtocolID(),
2499 channel->incoming_reliables.insert(packet,channel->readNextIncomingSeqNum());
2501 LOG(dout_con<<m_connection->getDesc()
2502 << "BUFFERING, TYPE_RELIABLE peer_id: " << peer_id
2503 << ", channel: " << (channelnum&0xFF)
2504 << ", seqnum: " << seqnum << std::endl;)
2506 throw ProcessedQueued("Buffered future reliable packet");
2508 catch(AlreadyExistsException &e)
2511 catch(IncomingDataCorruption &e)
2513 ConnectionCommand discon;
2514 discon.disconnect_peer(peer_id);
2515 m_connection->putCommand(discon);
2517 LOG(derr_con<<m_connection->getDesc()
2518 << "INVALID, TYPE_RELIABLE peer_id: " << peer_id
2519 << ", channel: " << (channelnum&0xFF)
2520 << ", seqnum: " << seqnum
2521 << "DROPPING CLIENT!" << std::endl;)
2525 /* we got a packet to process right now */
2526 LOG(dout_con<<m_connection->getDesc()
2527 << "RECURSIVE, TYPE_RELIABLE peer_id: " << peer_id
2528 << ", channel: " << (channelnum&0xFF)
2529 << ", seqnum: " << seqnum << std::endl;)
2532 /* check for resend case */
2533 u16 queued_seqnum = 0;
2534 if (channel->incoming_reliables.getFirstSeqnum(queued_seqnum))
2536 if (queued_seqnum == seqnum)
2538 BufferedPacket queued_packet = channel->incoming_reliables.popFirst();
2539 /** TODO find a way to verify the new against the old packet */
2543 channel->incNextIncomingSeqNum();
2545 // Get out the inside packet and re-process it
2546 SharedBuffer<u8> payload(packetdata.getSize() - RELIABLE_HEADER_SIZE);
2547 memcpy(*payload, &packetdata[RELIABLE_HEADER_SIZE], payload.getSize());
2549 return processPacket(channel, payload, peer_id, channelnum, true);
2553 derr_con<<m_connection->getDesc()
2554 <<"Got invalid type="<<((int)type&0xff)<<std::endl;
2555 throw InvalidIncomingDataException("Invalid packet type");
2558 // We should never get here.
2559 FATAL_ERROR("Invalid execution point");
2566 Connection::Connection(u32 protocol_id, u32 max_packet_size, float timeout,
2567 bool ipv6, PeerHandler *peerhandler) :
2569 m_protocol_id(protocol_id),
2570 m_sendThread(max_packet_size, timeout),
2571 m_receiveThread(max_packet_size),
2572 m_bc_peerhandler(peerhandler)
2575 m_udpSocket.setTimeoutMs(5);
2577 m_sendThread.setParent(this);
2578 m_receiveThread.setParent(this);
2580 m_sendThread.start();
2581 m_receiveThread.start();
2586 Connection::~Connection()
2588 m_shutting_down = true;
2589 // request threads to stop
2590 m_sendThread.stop();
2591 m_receiveThread.stop();
2593 //TODO for some unkonwn reason send/receive threads do not exit as they're
2594 // supposed to be but wait on peer timeout. To speed up shutdown we reduce
2595 // timeout to half a second.
2596 m_sendThread.setPeerTimeout(0.5);
2598 // wait for threads to finish
2599 m_sendThread.wait();
2600 m_receiveThread.wait();
2603 for (auto &peer : m_peers) {
2608 /* Internal stuff */
2609 void Connection::putEvent(ConnectionEvent &e)
2611 assert(e.type != CONNEVENT_NONE); // Pre-condition
2612 m_event_queue.push_back(e);
2615 PeerHelper Connection::getPeer(u16 peer_id)
2617 MutexAutoLock peerlock(m_peers_mutex);
2618 std::map<u16, Peer*>::iterator node = m_peers.find(peer_id);
2620 if (node == m_peers.end()) {
2621 throw PeerNotFoundException("GetPeer: Peer not found (possible timeout)");
2625 FATAL_ERROR_IF(node->second->id != peer_id, "Invalid peer id");
2627 return PeerHelper(node->second);
2630 PeerHelper Connection::getPeerNoEx(u16 peer_id)
2632 MutexAutoLock peerlock(m_peers_mutex);
2633 std::map<u16, Peer*>::iterator node = m_peers.find(peer_id);
2635 if (node == m_peers.end()) {
2636 return PeerHelper(NULL);
2640 FATAL_ERROR_IF(node->second->id != peer_id, "Invalid peer id");
2642 return PeerHelper(node->second);
2645 /* find peer_id for address */
2646 u16 Connection::lookupPeer(Address& sender)
2648 MutexAutoLock peerlock(m_peers_mutex);
2649 std::map<u16, Peer*>::iterator j;
2650 j = m_peers.begin();
2651 for(; j != m_peers.end(); ++j)
2653 Peer *peer = j->second;
2654 if (peer->isPendingDeletion())
2659 if ((peer->getAddress(MTP_MINETEST_RELIABLE_UDP, tocheck)) && (tocheck == sender))
2662 if ((peer->getAddress(MTP_UDP, tocheck)) && (tocheck == sender))
2666 return PEER_ID_INEXISTENT;
2669 std::list<Peer*> Connection::getPeers()
2671 std::list<Peer*> list;
2672 for (auto &p : m_peers) {
2673 Peer *peer = p.second;
2674 list.push_back(peer);
2679 bool Connection::deletePeer(u16 peer_id, bool timeout)
2683 /* lock list as short as possible */
2685 MutexAutoLock peerlock(m_peers_mutex);
2686 if (m_peers.find(peer_id) == m_peers.end())
2688 peer = m_peers[peer_id];
2689 m_peers.erase(peer_id);
2690 m_peer_ids.remove(peer_id);
2693 Address peer_address;
2694 //any peer has a primary address this never fails!
2695 peer->getAddress(MTP_PRIMARY, peer_address);
2698 e.peerRemoved(peer_id, timeout, peer_address);
2708 ConnectionEvent Connection::waitEvent(u32 timeout_ms)
2711 return m_event_queue.pop_front(timeout_ms);
2712 } catch(ItemNotFoundException &ex) {
2714 e.type = CONNEVENT_NONE;
2719 void Connection::putCommand(ConnectionCommand &c)
2721 if (!m_shutting_down) {
2722 m_command_queue.push_back(c);
2723 m_sendThread.Trigger();
2727 void Connection::Serve(Address bind_addr)
2729 ConnectionCommand c;
2734 void Connection::Connect(Address address)
2736 ConnectionCommand c;
2741 bool Connection::Connected()
2743 MutexAutoLock peerlock(m_peers_mutex);
2745 if (m_peers.size() != 1)
2748 std::map<u16, Peer*>::iterator node = m_peers.find(PEER_ID_SERVER);
2749 if (node == m_peers.end())
2752 if (m_peer_id == PEER_ID_INEXISTENT)
2758 void Connection::Disconnect()
2760 ConnectionCommand c;
2765 void Connection::Receive(NetworkPacket* pkt)
2768 ConnectionEvent e = waitEvent(m_bc_receive_timeout);
2769 if (e.type != CONNEVENT_NONE)
2770 LOG(dout_con << getDesc() << ": Receive: got event: "
2771 << e.describe() << std::endl);
2773 case CONNEVENT_NONE:
2774 throw NoIncomingDataException("No incoming data");
2775 case CONNEVENT_DATA_RECEIVED:
2776 // Data size is lesser than command size, ignoring packet
2777 if (e.data.getSize() < 2) {
2781 pkt->putRawPacket(*e.data, e.data.getSize(), e.peer_id);
2783 case CONNEVENT_PEER_ADDED: {
2784 UDPPeer tmp(e.peer_id, e.address, this);
2785 if (m_bc_peerhandler)
2786 m_bc_peerhandler->peerAdded(&tmp);
2789 case CONNEVENT_PEER_REMOVED: {
2790 UDPPeer tmp(e.peer_id, e.address, this);
2791 if (m_bc_peerhandler)
2792 m_bc_peerhandler->deletingPeer(&tmp, e.timeout);
2795 case CONNEVENT_BIND_FAILED:
2796 throw ConnectionBindFailed("Failed to bind socket "
2797 "(port already in use?)");
2800 throw NoIncomingDataException("No incoming data");
2803 void Connection::Send(u16 peer_id, u8 channelnum,
2804 NetworkPacket* pkt, bool reliable)
2806 assert(channelnum < CHANNEL_COUNT); // Pre-condition
2808 ConnectionCommand c;
2810 c.send(peer_id, channelnum, pkt, reliable);
2814 Address Connection::GetPeerAddress(u16 peer_id)
2816 PeerHelper peer = getPeerNoEx(peer_id);
2819 throw PeerNotFoundException("No address for peer found!");
2820 Address peer_address;
2821 peer->getAddress(MTP_PRIMARY, peer_address);
2822 return peer_address;
2825 float Connection::getPeerStat(u16 peer_id, rtt_stat_type type)
2827 PeerHelper peer = getPeerNoEx(peer_id);
2828 if (!peer) return -1;
2829 return peer->getStat(type);
2832 float Connection::getLocalStat(rate_stat_type type)
2834 PeerHelper peer = getPeerNoEx(PEER_ID_SERVER);
2836 FATAL_ERROR_IF(!peer, "Connection::getLocalStat we couldn't get our own peer? are you serious???");
2840 for (Channel &channel : dynamic_cast<UDPPeer *>(&peer)->channels) {
2843 retval += channel.getCurrentDownloadRateKB();
2846 retval += channel.getAvgDownloadRateKB();
2849 retval += channel.getCurrentIncomingRateKB();
2852 retval += channel.getAvgIncomingRateKB();
2855 retval += channel.getAvgLossRateKB();
2858 retval += channel.getCurrentLossRateKB();
2861 FATAL_ERROR("Connection::getLocalStat Invalid stat type");
2867 u16 Connection::createPeer(Address& sender, MTProtocols protocol, int fd)
2869 // Somebody wants to make a new connection
2871 // Get a unique peer id (2 or higher)
2872 u16 peer_id_new = m_next_remote_peer_id;
2873 u16 overflow = MAX_UDP_PEERS;
2876 Find an unused peer id
2878 MutexAutoLock lock(m_peers_mutex);
2879 bool out_of_ids = false;
2882 if (m_peers.find(peer_id_new) == m_peers.end())
2885 // Check for overflow
2886 if (peer_id_new == overflow) {
2894 errorstream << getDesc() << " ran out of peer ids" << std::endl;
2895 return PEER_ID_INEXISTENT;
2900 peer = new UDPPeer(peer_id_new, sender, this);
2902 m_peers[peer->id] = peer;
2903 m_peer_ids.push_back(peer->id);
2905 m_next_remote_peer_id = (peer_id_new +1 ) % MAX_UDP_PEERS;
2907 LOG(dout_con << getDesc()
2908 << "createPeer(): giving peer_id=" << peer_id_new << std::endl);
2910 ConnectionCommand cmd;
2911 SharedBuffer<u8> reply(4);
2912 writeU8(&reply[0], TYPE_CONTROL);
2913 writeU8(&reply[1], CONTROLTYPE_SET_PEER_ID);
2914 writeU16(&reply[2], peer_id_new);
2915 cmd.createPeer(peer_id_new,reply);
2918 // Create peer addition event
2920 e.peerAdded(peer_id_new, sender);
2923 // We're now talking to a valid peer_id
2927 void Connection::PrintInfo(std::ostream &out)
2929 m_info_mutex.lock();
2930 out<<getDesc()<<": ";
2931 m_info_mutex.unlock();
2934 void Connection::PrintInfo()
2936 PrintInfo(dout_con);
2939 const std::string Connection::getDesc()
2941 return std::string("con(")+
2942 itos(m_udpSocket.GetHandle())+"/"+itos(m_peer_id)+")";
2945 void Connection::DisconnectPeer(u16 peer_id)
2947 ConnectionCommand discon;
2948 discon.disconnect_peer(peer_id);
2952 void Connection::sendAck(u16 peer_id, u8 channelnum, u16 seqnum)
2954 assert(channelnum < CHANNEL_COUNT); // Pre-condition
2956 LOG(dout_con<<getDesc()
2957 <<" Queuing ACK command to peer_id: " << peer_id <<
2958 " channel: " << (channelnum & 0xFF) <<
2959 " seqnum: " << seqnum << std::endl);
2961 ConnectionCommand c;
2962 SharedBuffer<u8> ack(4);
2963 writeU8(&ack[0], TYPE_CONTROL);
2964 writeU8(&ack[1], CONTROLTYPE_ACK);
2965 writeU16(&ack[2], seqnum);
2967 c.ack(peer_id, channelnum, ack);
2969 m_sendThread.Trigger();
2972 UDPPeer* Connection::createServerPeer(Address& address)
2974 if (getPeerNoEx(PEER_ID_SERVER) != 0)
2976 throw ConnectionException("Already connected to a server");
2979 UDPPeer *peer = new UDPPeer(PEER_ID_SERVER, address, this);
2982 MutexAutoLock lock(m_peers_mutex);
2983 m_peers[peer->id] = peer;
2984 m_peer_ids.push_back(peer->id);