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.
24 #include "connection.h"
25 #include "serialization.h"
28 #include "network/connectionthreads.h"
29 #include "network/networkpacket.h"
30 #include "network/peerhandler.h"
31 #include "util/serialize.h"
32 #include "util/numeric.h"
33 #include "util/string.h"
40 /******************************************************************************/
41 /* defines used for debugging and profiling */
42 /******************************************************************************/
47 /* this mutex is used to achieve log message consistency */
48 std::mutex log_message_mutex;
51 MutexAutoLock loglock(log_message_mutex); \
57 #define PING_TIMEOUT 5.0
59 BufferedPacket makePacket(Address &address, const SharedBuffer<u8> &data,
60 u32 protocol_id, session_t sender_peer_id, u8 channel)
62 u32 packet_size = data.getSize() + BASE_HEADER_SIZE;
63 BufferedPacket p(packet_size);
66 writeU32(&p.data[0], protocol_id);
67 writeU16(&p.data[4], sender_peer_id);
68 writeU8(&p.data[6], channel);
70 memcpy(&p.data[BASE_HEADER_SIZE], *data, data.getSize());
75 SharedBuffer<u8> makeOriginalPacket(const SharedBuffer<u8> &data)
78 u32 packet_size = data.getSize() + header_size;
79 SharedBuffer<u8> b(packet_size);
81 writeU8(&(b[0]), PACKET_TYPE_ORIGINAL);
82 if (data.getSize() > 0) {
83 memcpy(&(b[header_size]), *data, data.getSize());
88 // Split data in chunks and add TYPE_SPLIT headers to them
89 void makeSplitPacket(const SharedBuffer<u8> &data, u32 chunksize_max, u16 seqnum,
90 std::list<SharedBuffer<u8>> *chunks)
92 // Chunk packets, containing the TYPE_SPLIT header
93 u32 chunk_header_size = 7;
94 u32 maximum_data_size = chunksize_max - chunk_header_size;
100 end = start + maximum_data_size - 1;
101 if (end > data.getSize() - 1)
102 end = data.getSize() - 1;
104 u32 payload_size = end - start + 1;
105 u32 packet_size = chunk_header_size + payload_size;
107 SharedBuffer<u8> chunk(packet_size);
109 writeU8(&chunk[0], PACKET_TYPE_SPLIT);
110 writeU16(&chunk[1], seqnum);
111 // [3] u16 chunk_count is written at next stage
112 writeU16(&chunk[5], chunk_num);
113 memcpy(&chunk[chunk_header_size], &data[start], payload_size);
115 chunks->push_back(chunk);
121 while (end != data.getSize() - 1);
123 for (SharedBuffer<u8> &chunk : *chunks) {
125 writeU16(&(chunk[3]), chunk_count);
129 void makeAutoSplitPacket(const SharedBuffer<u8> &data, u32 chunksize_max,
130 u16 &split_seqnum, std::list<SharedBuffer<u8>> *list)
132 u32 original_header_size = 1;
134 if (data.getSize() + original_header_size > chunksize_max) {
135 makeSplitPacket(data, chunksize_max, split_seqnum, list);
140 list->push_back(makeOriginalPacket(data));
143 SharedBuffer<u8> makeReliablePacket(const SharedBuffer<u8> &data, u16 seqnum)
146 u32 packet_size = data.getSize() + header_size;
147 SharedBuffer<u8> b(packet_size);
149 writeU8(&b[0], PACKET_TYPE_RELIABLE);
150 writeU16(&b[1], seqnum);
152 memcpy(&b[header_size], *data, data.getSize());
161 void ReliablePacketBuffer::print()
163 MutexAutoLock listlock(m_list_mutex);
164 LOG(dout_con<<"Dump of ReliablePacketBuffer:" << std::endl);
165 unsigned int index = 0;
166 for (BufferedPacket &bufferedPacket : m_list) {
167 u16 s = readU16(&(bufferedPacket.data[BASE_HEADER_SIZE+1]));
168 LOG(dout_con<<index<< ":" << s << std::endl);
173 bool ReliablePacketBuffer::empty()
175 MutexAutoLock listlock(m_list_mutex);
176 return m_list.empty();
179 u32 ReliablePacketBuffer::size()
181 MutexAutoLock listlock(m_list_mutex);
182 return m_list.size();
185 bool ReliablePacketBuffer::containsPacket(u16 seqnum)
187 return !(findPacket(seqnum) == m_list.end());
190 RPBSearchResult ReliablePacketBuffer::findPacket(u16 seqnum)
192 std::list<BufferedPacket>::iterator i = m_list.begin();
193 for(; i != m_list.end(); ++i)
195 u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
196 /*dout_con<<"findPacket(): finding seqnum="<<seqnum
197 <<", comparing to s="<<s<<std::endl;*/
204 RPBSearchResult ReliablePacketBuffer::notFound()
209 bool ReliablePacketBuffer::getFirstSeqnum(u16& result)
211 MutexAutoLock listlock(m_list_mutex);
214 const BufferedPacket &p = *m_list.begin();
215 result = readU16(&p.data[BASE_HEADER_SIZE + 1]);
219 BufferedPacket ReliablePacketBuffer::popFirst()
221 MutexAutoLock listlock(m_list_mutex);
223 throw NotFoundException("Buffer is empty");
224 BufferedPacket p = *m_list.begin();
225 m_list.erase(m_list.begin());
227 if (m_list.empty()) {
228 m_oldest_non_answered_ack = 0;
230 m_oldest_non_answered_ack =
231 readU16(&m_list.begin()->data[BASE_HEADER_SIZE + 1]);
236 BufferedPacket ReliablePacketBuffer::popSeqnum(u16 seqnum)
238 MutexAutoLock listlock(m_list_mutex);
239 RPBSearchResult r = findPacket(seqnum);
240 if (r == notFound()) {
241 LOG(dout_con<<"Sequence number: " << seqnum
242 << " not found in reliable buffer"<<std::endl);
243 throw NotFoundException("seqnum not found in buffer");
245 BufferedPacket p = *r;
248 RPBSearchResult next = r;
250 if (next != notFound()) {
251 u16 s = readU16(&(next->data[BASE_HEADER_SIZE+1]));
252 m_oldest_non_answered_ack = s;
257 if (m_list.empty()) {
258 m_oldest_non_answered_ack = 0;
260 m_oldest_non_answered_ack =
261 readU16(&m_list.begin()->data[BASE_HEADER_SIZE + 1]);
266 void ReliablePacketBuffer::insert(BufferedPacket &p, u16 next_expected)
268 MutexAutoLock listlock(m_list_mutex);
269 if (p.data.getSize() < BASE_HEADER_SIZE + 3) {
270 errorstream << "ReliablePacketBuffer::insert(): Invalid data size for "
271 "reliable packet" << std::endl;
274 u8 type = readU8(&p.data[BASE_HEADER_SIZE + 0]);
275 if (type != PACKET_TYPE_RELIABLE) {
276 errorstream << "ReliablePacketBuffer::insert(): type is not reliable"
280 u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE + 1]);
282 if (!seqnum_in_window(seqnum, next_expected, MAX_RELIABLE_WINDOW_SIZE)) {
283 errorstream << "ReliablePacketBuffer::insert(): seqnum is outside of "
284 "expected window " << std::endl;
287 if (seqnum == next_expected) {
288 errorstream << "ReliablePacketBuffer::insert(): seqnum is next expected"
293 sanity_check(m_list.size() <= SEQNUM_MAX); // FIXME: Handle the error?
295 // Find the right place for the packet and insert it there
296 // If list is empty, just add it
300 m_oldest_non_answered_ack = seqnum;
305 // Otherwise find the right place
306 std::list<BufferedPacket>::iterator i = m_list.begin();
307 // Find the first packet in the list which has a higher seqnum
308 u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
310 /* case seqnum is smaller then next_expected seqnum */
311 /* this is true e.g. on wrap around */
312 if (seqnum < next_expected) {
313 while(((s < seqnum) || (s >= next_expected)) && (i != m_list.end())) {
315 if (i != m_list.end())
316 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
319 /* non wrap around case (at least for incoming and next_expected */
322 while(((s < seqnum) && (s >= next_expected)) && (i != m_list.end())) {
324 if (i != m_list.end())
325 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
330 /* nothing to do this seems to be a resent packet */
331 /* for paranoia reason data should be compared */
333 (readU16(&(i->data[BASE_HEADER_SIZE+1])) != seqnum) ||
334 (i->data.getSize() != p.data.getSize()) ||
335 (i->address != p.address)
338 /* if this happens your maximum transfer window may be to big */
340 "Duplicated seqnum %d non matching packet detected:\n",
342 fprintf(stderr, "Old: seqnum: %05d size: %04d, address: %s\n",
343 readU16(&(i->data[BASE_HEADER_SIZE+1])),i->data.getSize(),
344 i->address.serializeString().c_str());
345 fprintf(stderr, "New: seqnum: %05d size: %04u, address: %s\n",
346 readU16(&(p.data[BASE_HEADER_SIZE+1])),p.data.getSize(),
347 p.address.serializeString().c_str());
348 throw IncomingDataCorruption("duplicated packet isn't same as original one");
351 /* insert or push back */
352 else if (i != m_list.end()) {
358 /* update last packet number */
359 m_oldest_non_answered_ack = readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]);
362 void ReliablePacketBuffer::incrementTimeouts(float dtime)
364 MutexAutoLock listlock(m_list_mutex);
365 for (BufferedPacket &bufferedPacket : m_list) {
366 bufferedPacket.time += dtime;
367 bufferedPacket.totaltime += dtime;
371 std::list<BufferedPacket> ReliablePacketBuffer::getTimedOuts(float timeout,
372 unsigned int max_packets)
374 MutexAutoLock listlock(m_list_mutex);
375 std::list<BufferedPacket> timed_outs;
376 for (BufferedPacket &bufferedPacket : m_list) {
377 if (bufferedPacket.time >= timeout) {
378 timed_outs.push_back(bufferedPacket);
380 //this packet will be sent right afterwards reset timeout here
381 bufferedPacket.time = 0.0f;
382 if (timed_outs.size() >= max_packets)
393 IncomingSplitBuffer::~IncomingSplitBuffer()
395 MutexAutoLock listlock(m_map_mutex);
396 for (auto &i : m_buf) {
401 This will throw a GotSplitPacketException when a full
402 split packet is constructed.
404 SharedBuffer<u8> IncomingSplitBuffer::insert(const BufferedPacket &p, bool reliable)
406 MutexAutoLock listlock(m_map_mutex);
407 u32 headersize = BASE_HEADER_SIZE + 7;
408 if (p.data.getSize() < headersize) {
409 errorstream << "Invalid data size for split packet" << std::endl;
410 return SharedBuffer<u8>();
412 u8 type = readU8(&p.data[BASE_HEADER_SIZE+0]);
413 u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]);
414 u16 chunk_count = readU16(&p.data[BASE_HEADER_SIZE+3]);
415 u16 chunk_num = readU16(&p.data[BASE_HEADER_SIZE+5]);
417 if (type != PACKET_TYPE_SPLIT) {
418 errorstream << "IncomingSplitBuffer::insert(): type is not split"
420 return SharedBuffer<u8>();
422 if (chunk_num >= chunk_count) {
423 errorstream << "IncomingSplitBuffer::insert(): chunk_num=" << chunk_num
424 << " >= chunk_count=" << chunk_count << std::endl;
425 return SharedBuffer<u8>();
428 // Add if doesn't exist
429 if (m_buf.find(seqnum) == m_buf.end()) {
430 m_buf[seqnum] = new IncomingSplitPacket(chunk_count, reliable);
433 IncomingSplitPacket *sp = m_buf[seqnum];
435 if (chunk_count != sp->chunk_count) {
436 errorstream << "IncomingSplitBuffer::insert(): chunk_count="
437 << chunk_count << " != sp->chunk_count=" << sp->chunk_count
439 return SharedBuffer<u8>();
441 if (reliable != sp->reliable)
442 LOG(derr_con<<"Connection: WARNING: reliable="<<reliable
443 <<" != sp->reliable="<<sp->reliable
446 // If chunk already exists, ignore it.
447 // Sometimes two identical packets may arrive when there is network
448 // lag and the server re-sends stuff.
449 if (sp->chunks.find(chunk_num) != sp->chunks.end())
450 return SharedBuffer<u8>();
452 // Cut chunk data out of packet
453 u32 chunkdatasize = p.data.getSize() - headersize;
454 SharedBuffer<u8> chunkdata(chunkdatasize);
455 memcpy(*chunkdata, &(p.data[headersize]), chunkdatasize);
457 // Set chunk data in buffer
458 sp->chunks[chunk_num] = chunkdata;
460 // If not all chunks are received, return empty buffer
461 if (!sp->allReceived())
462 return SharedBuffer<u8>();
464 // Calculate total size
466 for (const auto &chunk : sp->chunks) {
467 totalsize += chunk.second.getSize();
470 SharedBuffer<u8> fulldata(totalsize);
472 // Copy chunks to data buffer
474 for (u32 chunk_i=0; chunk_i<sp->chunk_count; chunk_i++) {
475 const SharedBuffer<u8> &buf = sp->chunks[chunk_i];
476 u16 buf_chunkdatasize = buf.getSize();
477 memcpy(&fulldata[start], *buf, buf_chunkdatasize);
478 start += buf_chunkdatasize;
481 // Remove sp from buffer
487 void IncomingSplitBuffer::removeUnreliableTimedOuts(float dtime, float timeout)
489 std::deque<u16> remove_queue;
491 MutexAutoLock listlock(m_map_mutex);
492 for (auto &i : m_buf) {
493 IncomingSplitPacket *p = i.second;
494 // Reliable ones are not removed by timeout
498 if (p->time >= timeout)
499 remove_queue.push_back(i.first);
502 for (u16 j : remove_queue) {
503 MutexAutoLock listlock(m_map_mutex);
504 LOG(dout_con<<"NOTE: Removing timed out unreliable split packet"<<std::endl);
514 void ConnectionCommand::send(session_t peer_id_, u8 channelnum_, NetworkPacket *pkt,
519 channelnum = channelnum_;
520 data = pkt->oldForgePacket();
521 reliable = reliable_;
528 u16 Channel::readNextIncomingSeqNum()
530 MutexAutoLock internal(m_internal_mutex);
531 return next_incoming_seqnum;
534 u16 Channel::incNextIncomingSeqNum()
536 MutexAutoLock internal(m_internal_mutex);
537 u16 retval = next_incoming_seqnum;
538 next_incoming_seqnum++;
542 u16 Channel::readNextSplitSeqNum()
544 MutexAutoLock internal(m_internal_mutex);
545 return next_outgoing_split_seqnum;
547 void Channel::setNextSplitSeqNum(u16 seqnum)
549 MutexAutoLock internal(m_internal_mutex);
550 next_outgoing_split_seqnum = seqnum;
553 u16 Channel::getOutgoingSequenceNumber(bool& successful)
555 MutexAutoLock internal(m_internal_mutex);
556 u16 retval = next_outgoing_seqnum;
557 u16 lowest_unacked_seqnumber;
559 /* shortcut if there ain't any packet in outgoing list */
560 if (outgoing_reliables_sent.empty())
562 next_outgoing_seqnum++;
566 if (outgoing_reliables_sent.getFirstSeqnum(lowest_unacked_seqnumber))
568 if (lowest_unacked_seqnumber < next_outgoing_seqnum) {
569 // ugly cast but this one is required in order to tell compiler we
570 // know about difference of two unsigned may be negative in general
571 // but we already made sure it won't happen in this case
572 if (((u16)(next_outgoing_seqnum - lowest_unacked_seqnumber)) > window_size) {
578 // ugly cast but this one is required in order to tell compiler we
579 // know about difference of two unsigned may be negative in general
580 // but we already made sure it won't happen in this case
581 if ((next_outgoing_seqnum + (u16)(SEQNUM_MAX - lowest_unacked_seqnumber)) >
589 next_outgoing_seqnum++;
593 u16 Channel::readOutgoingSequenceNumber()
595 MutexAutoLock internal(m_internal_mutex);
596 return next_outgoing_seqnum;
599 bool Channel::putBackSequenceNumber(u16 seqnum)
601 if (((seqnum + 1) % (SEQNUM_MAX+1)) == next_outgoing_seqnum) {
603 next_outgoing_seqnum = seqnum;
609 void Channel::UpdateBytesSent(unsigned int bytes, unsigned int packets)
611 MutexAutoLock internal(m_internal_mutex);
612 current_bytes_transfered += bytes;
613 current_packet_successful += packets;
616 void Channel::UpdateBytesReceived(unsigned int bytes) {
617 MutexAutoLock internal(m_internal_mutex);
618 current_bytes_received += bytes;
621 void Channel::UpdateBytesLost(unsigned int bytes)
623 MutexAutoLock internal(m_internal_mutex);
624 current_bytes_lost += bytes;
628 void Channel::UpdatePacketLossCounter(unsigned int count)
630 MutexAutoLock internal(m_internal_mutex);
631 current_packet_loss += count;
634 void Channel::UpdatePacketTooLateCounter()
636 MutexAutoLock internal(m_internal_mutex);
637 current_packet_too_late++;
640 void Channel::UpdateTimers(float dtime)
642 bpm_counter += dtime;
643 packet_loss_counter += dtime;
645 if (packet_loss_counter > 1.0f) {
646 packet_loss_counter -= 1.0f;
648 unsigned int packet_loss = 11; /* use a neutral value for initialization */
649 unsigned int packets_successful = 0;
650 //unsigned int packet_too_late = 0;
652 bool reasonable_amount_of_data_transmitted = false;
655 MutexAutoLock internal(m_internal_mutex);
656 packet_loss = current_packet_loss;
657 //packet_too_late = current_packet_too_late;
658 packets_successful = current_packet_successful;
660 if (current_bytes_transfered > (unsigned int) (window_size*512/2)) {
661 reasonable_amount_of_data_transmitted = true;
663 current_packet_loss = 0;
664 current_packet_too_late = 0;
665 current_packet_successful = 0;
668 /* dynamic window size */
669 float successful_to_lost_ratio = 0.0f;
672 if (packets_successful > 0) {
673 successful_to_lost_ratio = packet_loss/packets_successful;
674 } else if (packet_loss > 0) {
675 window_size = std::max(
677 MIN_RELIABLE_WINDOW_SIZE);
682 if ((successful_to_lost_ratio < 0.01f) &&
683 (window_size < MAX_RELIABLE_WINDOW_SIZE)) {
684 /* don't even think about increasing if we didn't even
685 * use major parts of our window */
686 if (reasonable_amount_of_data_transmitted)
687 window_size = std::min(
689 MAX_RELIABLE_WINDOW_SIZE);
690 } else if ((successful_to_lost_ratio < 0.05f) &&
691 (window_size < MAX_RELIABLE_WINDOW_SIZE)) {
692 /* don't even think about increasing if we didn't even
693 * use major parts of our window */
694 if (reasonable_amount_of_data_transmitted)
695 window_size = std::min(
697 MAX_RELIABLE_WINDOW_SIZE);
698 } else if (successful_to_lost_ratio > 0.15f) {
699 window_size = std::max(
701 MIN_RELIABLE_WINDOW_SIZE);
702 } else if (successful_to_lost_ratio > 0.1f) {
703 window_size = std::max(
705 MIN_RELIABLE_WINDOW_SIZE);
710 if (bpm_counter > 10.0f) {
712 MutexAutoLock internal(m_internal_mutex);
714 (((float) current_bytes_transfered)/bpm_counter)/1024.0f;
715 current_bytes_transfered = 0;
717 (((float) current_bytes_lost)/bpm_counter)/1024.0f;
718 current_bytes_lost = 0;
720 (((float) current_bytes_received)/bpm_counter)/1024.0f;
721 current_bytes_received = 0;
725 if (cur_kbps > max_kbps) {
729 if (cur_kbps_lost > max_kbps_lost) {
730 max_kbps_lost = cur_kbps_lost;
733 if (cur_incoming_kbps > max_incoming_kbps) {
734 max_incoming_kbps = cur_incoming_kbps;
737 rate_samples = MYMIN(rate_samples+1,10);
738 float old_fraction = ((float) (rate_samples-1) )/( (float) rate_samples);
739 avg_kbps = avg_kbps * old_fraction +
740 cur_kbps * (1.0 - old_fraction);
741 avg_kbps_lost = avg_kbps_lost * old_fraction +
742 cur_kbps_lost * (1.0 - old_fraction);
743 avg_incoming_kbps = avg_incoming_kbps * old_fraction +
744 cur_incoming_kbps * (1.0 - old_fraction);
753 PeerHelper::PeerHelper(Peer* peer) :
756 if (peer && !peer->IncUseCount())
760 PeerHelper::~PeerHelper()
763 m_peer->DecUseCount();
768 PeerHelper& PeerHelper::operator=(Peer* peer)
771 if (peer && !peer->IncUseCount())
776 Peer* PeerHelper::operator->() const
781 Peer* PeerHelper::operator&() const
786 bool PeerHelper::operator!()
791 bool PeerHelper::operator!=(void* ptr)
793 return ((void*) m_peer != ptr);
796 bool Peer::IncUseCount()
798 MutexAutoLock lock(m_exclusive_access_mutex);
800 if (!m_pending_deletion) {
808 void Peer::DecUseCount()
811 MutexAutoLock lock(m_exclusive_access_mutex);
812 sanity_check(m_usage > 0);
815 if (!((m_pending_deletion) && (m_usage == 0)))
821 void Peer::RTTStatistics(float rtt, const std::string &profiler_id,
822 unsigned int num_samples) {
824 if (m_last_rtt > 0) {
825 /* set min max values */
826 if (rtt < m_rtt.min_rtt)
828 if (rtt >= m_rtt.max_rtt)
831 /* do average calculation */
832 if (m_rtt.avg_rtt < 0.0)
835 m_rtt.avg_rtt = m_rtt.avg_rtt * (num_samples/(num_samples-1)) +
836 rtt * (1/num_samples);
838 /* do jitter calculation */
840 //just use some neutral value at beginning
841 float jitter = m_rtt.jitter_min;
843 if (rtt > m_last_rtt)
844 jitter = rtt-m_last_rtt;
846 if (rtt <= m_last_rtt)
847 jitter = m_last_rtt - rtt;
849 if (jitter < m_rtt.jitter_min)
850 m_rtt.jitter_min = jitter;
851 if (jitter >= m_rtt.jitter_max)
852 m_rtt.jitter_max = jitter;
854 if (m_rtt.jitter_avg < 0.0)
855 m_rtt.jitter_avg = jitter;
857 m_rtt.jitter_avg = m_rtt.jitter_avg * (num_samples/(num_samples-1)) +
858 jitter * (1/num_samples);
860 if (!profiler_id.empty()) {
861 g_profiler->graphAdd(profiler_id + " RTT [ms]", rtt * 1000.f);
862 g_profiler->graphAdd(profiler_id + " jitter [ms]", jitter * 1000.f);
865 /* save values required for next loop */
869 bool Peer::isTimedOut(float timeout)
871 MutexAutoLock lock(m_exclusive_access_mutex);
872 u64 current_time = porting::getTimeMs();
874 float dtime = CALC_DTIME(m_last_timeout_check,current_time);
875 m_last_timeout_check = current_time;
877 m_timeout_counter += dtime;
879 return m_timeout_counter > timeout;
885 MutexAutoLock usage_lock(m_exclusive_access_mutex);
886 m_pending_deletion = true;
891 PROFILE(std::stringstream peerIdentifier1);
892 PROFILE(peerIdentifier1 << "runTimeouts[" << m_connection->getDesc()
893 << ";" << id << ";RELIABLE]");
894 PROFILE(g_profiler->remove(peerIdentifier1.str()));
895 PROFILE(std::stringstream peerIdentifier2);
896 PROFILE(peerIdentifier2 << "sendPackets[" << m_connection->getDesc()
897 << ";" << id << ";RELIABLE]");
898 PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier2.str(), SPT_AVG));
903 UDPPeer::UDPPeer(u16 a_id, Address a_address, Connection* connection) :
904 Peer(a_address,a_id,connection)
906 for (Channel &channel : channels)
907 channel.setWindowSize(g_settings->getU16("max_packets_per_iteration"));
910 bool UDPPeer::getAddress(MTProtocols type,Address& toset)
912 if ((type == MTP_UDP) || (type == MTP_MINETEST_RELIABLE_UDP) || (type == MTP_PRIMARY))
921 void UDPPeer::reportRTT(float rtt)
926 RTTStatistics(rtt,"rudp",MAX_RELIABLE_WINDOW_SIZE*10);
928 float timeout = getStat(AVG_RTT) * RESEND_TIMEOUT_FACTOR;
929 if (timeout < RESEND_TIMEOUT_MIN)
930 timeout = RESEND_TIMEOUT_MIN;
931 if (timeout > RESEND_TIMEOUT_MAX)
932 timeout = RESEND_TIMEOUT_MAX;
934 MutexAutoLock usage_lock(m_exclusive_access_mutex);
935 resend_timeout = timeout;
938 bool UDPPeer::Ping(float dtime,SharedBuffer<u8>& data)
940 m_ping_timer += dtime;
941 if (m_ping_timer >= PING_TIMEOUT)
943 // Create and send PING packet
944 writeU8(&data[0], PACKET_TYPE_CONTROL);
945 writeU8(&data[1], CONTROLTYPE_PING);
952 void UDPPeer::PutReliableSendCommand(ConnectionCommand &c,
953 unsigned int max_packet_size)
955 if (m_pending_disconnect)
958 if ( channels[c.channelnum].queued_commands.empty() &&
959 /* don't queue more packets then window size */
960 (channels[c.channelnum].queued_reliables.size()
961 < (channels[c.channelnum].getWindowSize()/2))) {
962 LOG(dout_con<<m_connection->getDesc()
963 <<" processing reliable command for peer id: " << c.peer_id
964 <<" data size: " << c.data.getSize() << std::endl);
965 if (!processReliableSendCommand(c,max_packet_size)) {
966 channels[c.channelnum].queued_commands.push_back(c);
970 LOG(dout_con<<m_connection->getDesc()
971 <<" Queueing reliable command for peer id: " << c.peer_id
972 <<" data size: " << c.data.getSize() <<std::endl);
973 channels[c.channelnum].queued_commands.push_back(c);
977 bool UDPPeer::processReliableSendCommand(
978 ConnectionCommand &c,
979 unsigned int max_packet_size)
981 if (m_pending_disconnect)
984 u32 chunksize_max = max_packet_size
986 - RELIABLE_HEADER_SIZE;
988 sanity_check(c.data.getSize() < MAX_RELIABLE_WINDOW_SIZE*512);
990 std::list<SharedBuffer<u8>> originals;
991 u16 split_sequence_number = channels[c.channelnum].readNextSplitSeqNum();
994 originals.emplace_back(c.data);
996 makeAutoSplitPacket(c.data, chunksize_max,split_sequence_number, &originals);
997 channels[c.channelnum].setNextSplitSeqNum(split_sequence_number);
1000 bool have_sequence_number = true;
1001 bool have_initial_sequence_number = false;
1002 std::queue<BufferedPacket> toadd;
1003 volatile u16 initial_sequence_number = 0;
1005 for (SharedBuffer<u8> &original : originals) {
1006 u16 seqnum = channels[c.channelnum].getOutgoingSequenceNumber(have_sequence_number);
1008 /* oops, we don't have enough sequence numbers to send this packet */
1009 if (!have_sequence_number)
1012 if (!have_initial_sequence_number)
1014 initial_sequence_number = seqnum;
1015 have_initial_sequence_number = true;
1018 SharedBuffer<u8> reliable = makeReliablePacket(original, seqnum);
1020 // Add base headers and make a packet
1021 BufferedPacket p = con::makePacket(address, reliable,
1022 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1028 if (have_sequence_number) {
1029 volatile u16 pcount = 0;
1030 while (!toadd.empty()) {
1031 BufferedPacket p = toadd.front();
1033 // LOG(dout_con<<connection->getDesc()
1034 // << " queuing reliable packet for peer_id: " << c.peer_id
1035 // << " channel: " << (c.channelnum&0xFF)
1036 // << " seqnum: " << readU16(&p.data[BASE_HEADER_SIZE+1])
1038 channels[c.channelnum].queued_reliables.push(p);
1041 sanity_check(channels[c.channelnum].queued_reliables.size() < 0xFFFF);
1045 volatile u16 packets_available = toadd.size();
1046 /* we didn't get a single sequence number no need to fill queue */
1047 if (!have_initial_sequence_number) {
1051 while (!toadd.empty()) {
1055 bool successfully_put_back_sequence_number
1056 = channels[c.channelnum].putBackSequenceNumber(
1057 (initial_sequence_number+toadd.size() % (SEQNUM_MAX+1)));
1059 FATAL_ERROR_IF(!successfully_put_back_sequence_number, "error");
1062 LOG(dout_con<<m_connection->getDesc()
1063 << " Windowsize exceeded on reliable sending "
1064 << c.data.getSize() << " bytes"
1065 << std::endl << "\t\tinitial_sequence_number: "
1066 << initial_sequence_number
1067 << std::endl << "\t\tgot at most : "
1068 << packets_available << " packets"
1069 << std::endl << "\t\tpackets queued : "
1070 << channels[c.channelnum].outgoing_reliables_sent.size()
1076 void UDPPeer::RunCommandQueues(
1077 unsigned int max_packet_size,
1078 unsigned int maxcommands,
1079 unsigned int maxtransfer)
1082 for (Channel &channel : channels) {
1083 unsigned int commands_processed = 0;
1085 if ((!channel.queued_commands.empty()) &&
1086 (channel.queued_reliables.size() < maxtransfer) &&
1087 (commands_processed < maxcommands)) {
1089 ConnectionCommand c = channel.queued_commands.front();
1091 LOG(dout_con << m_connection->getDesc()
1092 << " processing queued reliable command " << std::endl);
1094 // Packet is processed, remove it from queue
1095 if (processReliableSendCommand(c,max_packet_size)) {
1096 channel.queued_commands.pop_front();
1098 LOG(dout_con << m_connection->getDesc()
1099 << " Failed to queue packets for peer_id: " << c.peer_id
1100 << ", delaying sending of " << c.data.getSize()
1101 << " bytes" << std::endl);
1104 catch (ItemNotFoundException &e) {
1105 // intentionally empty
1111 u16 UDPPeer::getNextSplitSequenceNumber(u8 channel)
1113 assert(channel < CHANNEL_COUNT); // Pre-condition
1114 return channels[channel].readNextSplitSeqNum();
1117 void UDPPeer::setNextSplitSequenceNumber(u8 channel, u16 seqnum)
1119 assert(channel < CHANNEL_COUNT); // Pre-condition
1120 channels[channel].setNextSplitSeqNum(seqnum);
1123 SharedBuffer<u8> UDPPeer::addSplitPacket(u8 channel, const BufferedPacket &toadd,
1126 assert(channel < CHANNEL_COUNT); // Pre-condition
1127 return channels[channel].incoming_splits.insert(toadd, reliable);
1134 Connection::Connection(u32 protocol_id, u32 max_packet_size, float timeout,
1135 bool ipv6, PeerHandler *peerhandler) :
1137 m_protocol_id(protocol_id),
1138 m_sendThread(new ConnectionSendThread(max_packet_size, timeout)),
1139 m_receiveThread(new ConnectionReceiveThread(max_packet_size)),
1140 m_bc_peerhandler(peerhandler)
1143 m_udpSocket.setTimeoutMs(5);
1145 m_sendThread->setParent(this);
1146 m_receiveThread->setParent(this);
1148 m_sendThread->start();
1149 m_receiveThread->start();
1153 Connection::~Connection()
1155 m_shutting_down = true;
1156 // request threads to stop
1157 m_sendThread->stop();
1158 m_receiveThread->stop();
1160 //TODO for some unkonwn reason send/receive threads do not exit as they're
1161 // supposed to be but wait on peer timeout. To speed up shutdown we reduce
1162 // timeout to half a second.
1163 m_sendThread->setPeerTimeout(0.5);
1165 // wait for threads to finish
1166 m_sendThread->wait();
1167 m_receiveThread->wait();
1170 for (auto &peer : m_peers) {
1175 /* Internal stuff */
1176 void Connection::putEvent(ConnectionEvent &e)
1178 assert(e.type != CONNEVENT_NONE); // Pre-condition
1179 m_event_queue.push_back(e);
1182 void Connection::TriggerSend()
1184 m_sendThread->Trigger();
1187 PeerHelper Connection::getPeerNoEx(session_t peer_id)
1189 MutexAutoLock peerlock(m_peers_mutex);
1190 std::map<session_t, Peer *>::iterator node = m_peers.find(peer_id);
1192 if (node == m_peers.end()) {
1193 return PeerHelper(NULL);
1197 FATAL_ERROR_IF(node->second->id != peer_id, "Invalid peer id");
1199 return PeerHelper(node->second);
1202 /* find peer_id for address */
1203 u16 Connection::lookupPeer(Address& sender)
1205 MutexAutoLock peerlock(m_peers_mutex);
1206 std::map<u16, Peer*>::iterator j;
1207 j = m_peers.begin();
1208 for(; j != m_peers.end(); ++j)
1210 Peer *peer = j->second;
1211 if (peer->isPendingDeletion())
1216 if ((peer->getAddress(MTP_MINETEST_RELIABLE_UDP, tocheck)) && (tocheck == sender))
1219 if ((peer->getAddress(MTP_UDP, tocheck)) && (tocheck == sender))
1223 return PEER_ID_INEXISTENT;
1226 bool Connection::deletePeer(session_t peer_id, bool timeout)
1230 /* lock list as short as possible */
1232 MutexAutoLock peerlock(m_peers_mutex);
1233 if (m_peers.find(peer_id) == m_peers.end())
1235 peer = m_peers[peer_id];
1236 m_peers.erase(peer_id);
1237 m_peer_ids.remove(peer_id);
1240 Address peer_address;
1241 //any peer has a primary address this never fails!
1242 peer->getAddress(MTP_PRIMARY, peer_address);
1245 e.peerRemoved(peer_id, timeout, peer_address);
1255 ConnectionEvent Connection::waitEvent(u32 timeout_ms)
1258 return m_event_queue.pop_front(timeout_ms);
1259 } catch(ItemNotFoundException &ex) {
1261 e.type = CONNEVENT_NONE;
1266 void Connection::putCommand(ConnectionCommand &c)
1268 if (!m_shutting_down) {
1269 m_command_queue.push_back(c);
1270 m_sendThread->Trigger();
1274 void Connection::Serve(Address bind_addr)
1276 ConnectionCommand c;
1281 void Connection::Connect(Address address)
1283 ConnectionCommand c;
1288 bool Connection::Connected()
1290 MutexAutoLock peerlock(m_peers_mutex);
1292 if (m_peers.size() != 1)
1295 std::map<session_t, Peer *>::iterator node = m_peers.find(PEER_ID_SERVER);
1296 if (node == m_peers.end())
1299 if (m_peer_id == PEER_ID_INEXISTENT)
1305 void Connection::Disconnect()
1307 ConnectionCommand c;
1312 void Connection::Receive(NetworkPacket* pkt)
1315 ConnectionEvent e = waitEvent(m_bc_receive_timeout);
1316 if (e.type != CONNEVENT_NONE)
1317 LOG(dout_con << getDesc() << ": Receive: got event: "
1318 << e.describe() << std::endl);
1320 case CONNEVENT_NONE:
1321 throw NoIncomingDataException("No incoming data");
1322 case CONNEVENT_DATA_RECEIVED:
1323 // Data size is lesser than command size, ignoring packet
1324 if (e.data.getSize() < 2) {
1328 pkt->putRawPacket(*e.data, e.data.getSize(), e.peer_id);
1330 case CONNEVENT_PEER_ADDED: {
1331 UDPPeer tmp(e.peer_id, e.address, this);
1332 if (m_bc_peerhandler)
1333 m_bc_peerhandler->peerAdded(&tmp);
1336 case CONNEVENT_PEER_REMOVED: {
1337 UDPPeer tmp(e.peer_id, e.address, this);
1338 if (m_bc_peerhandler)
1339 m_bc_peerhandler->deletingPeer(&tmp, e.timeout);
1342 case CONNEVENT_BIND_FAILED:
1343 throw ConnectionBindFailed("Failed to bind socket "
1344 "(port already in use?)");
1347 throw NoIncomingDataException("No incoming data");
1350 void Connection::Send(session_t peer_id, u8 channelnum,
1351 NetworkPacket *pkt, bool reliable)
1353 assert(channelnum < CHANNEL_COUNT); // Pre-condition
1355 ConnectionCommand c;
1357 c.send(peer_id, channelnum, pkt, reliable);
1361 Address Connection::GetPeerAddress(session_t peer_id)
1363 PeerHelper peer = getPeerNoEx(peer_id);
1366 throw PeerNotFoundException("No address for peer found!");
1367 Address peer_address;
1368 peer->getAddress(MTP_PRIMARY, peer_address);
1369 return peer_address;
1372 float Connection::getPeerStat(session_t peer_id, rtt_stat_type type)
1374 PeerHelper peer = getPeerNoEx(peer_id);
1375 if (!peer) return -1;
1376 return peer->getStat(type);
1379 float Connection::getLocalStat(rate_stat_type type)
1381 PeerHelper peer = getPeerNoEx(PEER_ID_SERVER);
1383 FATAL_ERROR_IF(!peer, "Connection::getLocalStat we couldn't get our own peer? are you serious???");
1387 for (Channel &channel : dynamic_cast<UDPPeer *>(&peer)->channels) {
1390 retval += channel.getCurrentDownloadRateKB();
1393 retval += channel.getAvgDownloadRateKB();
1396 retval += channel.getCurrentIncomingRateKB();
1399 retval += channel.getAvgIncomingRateKB();
1402 retval += channel.getAvgLossRateKB();
1405 retval += channel.getCurrentLossRateKB();
1408 FATAL_ERROR("Connection::getLocalStat Invalid stat type");
1414 u16 Connection::createPeer(Address& sender, MTProtocols protocol, int fd)
1416 // Somebody wants to make a new connection
1418 // Get a unique peer id (2 or higher)
1419 session_t peer_id_new = m_next_remote_peer_id;
1420 u16 overflow = MAX_UDP_PEERS;
1423 Find an unused peer id
1425 MutexAutoLock lock(m_peers_mutex);
1426 bool out_of_ids = false;
1429 if (m_peers.find(peer_id_new) == m_peers.end())
1432 // Check for overflow
1433 if (peer_id_new == overflow) {
1441 errorstream << getDesc() << " ran out of peer ids" << std::endl;
1442 return PEER_ID_INEXISTENT;
1447 peer = new UDPPeer(peer_id_new, sender, this);
1449 m_peers[peer->id] = peer;
1450 m_peer_ids.push_back(peer->id);
1452 m_next_remote_peer_id = (peer_id_new +1 ) % MAX_UDP_PEERS;
1454 LOG(dout_con << getDesc()
1455 << "createPeer(): giving peer_id=" << peer_id_new << std::endl);
1457 ConnectionCommand cmd;
1458 SharedBuffer<u8> reply(4);
1459 writeU8(&reply[0], PACKET_TYPE_CONTROL);
1460 writeU8(&reply[1], CONTROLTYPE_SET_PEER_ID);
1461 writeU16(&reply[2], peer_id_new);
1462 cmd.createPeer(peer_id_new,reply);
1465 // Create peer addition event
1467 e.peerAdded(peer_id_new, sender);
1470 // We're now talking to a valid peer_id
1474 void Connection::PrintInfo(std::ostream &out)
1476 m_info_mutex.lock();
1477 out<<getDesc()<<": ";
1478 m_info_mutex.unlock();
1481 const std::string Connection::getDesc()
1483 return std::string("con(")+
1484 itos(m_udpSocket.GetHandle())+"/"+itos(m_peer_id)+")";
1487 void Connection::DisconnectPeer(session_t peer_id)
1489 ConnectionCommand discon;
1490 discon.disconnect_peer(peer_id);
1494 void Connection::sendAck(session_t peer_id, u8 channelnum, u16 seqnum)
1496 assert(channelnum < CHANNEL_COUNT); // Pre-condition
1498 LOG(dout_con<<getDesc()
1499 <<" Queuing ACK command to peer_id: " << peer_id <<
1500 " channel: " << (channelnum & 0xFF) <<
1501 " seqnum: " << seqnum << std::endl);
1503 ConnectionCommand c;
1504 SharedBuffer<u8> ack(4);
1505 writeU8(&ack[0], PACKET_TYPE_CONTROL);
1506 writeU8(&ack[1], CONTROLTYPE_ACK);
1507 writeU16(&ack[2], seqnum);
1509 c.ack(peer_id, channelnum, ack);
1511 m_sendThread->Trigger();
1514 UDPPeer* Connection::createServerPeer(Address& address)
1516 if (getPeerNoEx(PEER_ID_SERVER) != 0)
1518 throw ConnectionException("Already connected to a server");
1521 UDPPeer *peer = new UDPPeer(PEER_ID_SERVER, address, this);
1524 MutexAutoLock lock(m_peers_mutex);
1525 m_peers[peer->id] = peer;
1526 m_peer_ids.push_back(peer->id);