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 RPBSearchResult ReliablePacketBuffer::findPacket(u16 seqnum)
187 std::list<BufferedPacket>::iterator i = m_list.begin();
188 for(; i != m_list.end(); ++i)
190 u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
197 RPBSearchResult ReliablePacketBuffer::notFound()
202 bool ReliablePacketBuffer::getFirstSeqnum(u16& result)
204 MutexAutoLock listlock(m_list_mutex);
207 const BufferedPacket &p = *m_list.begin();
208 result = readU16(&p.data[BASE_HEADER_SIZE + 1]);
212 BufferedPacket ReliablePacketBuffer::popFirst()
214 MutexAutoLock listlock(m_list_mutex);
216 throw NotFoundException("Buffer is empty");
217 BufferedPacket p = *m_list.begin();
218 m_list.erase(m_list.begin());
220 if (m_list.empty()) {
221 m_oldest_non_answered_ack = 0;
223 m_oldest_non_answered_ack =
224 readU16(&m_list.begin()->data[BASE_HEADER_SIZE + 1]);
229 BufferedPacket ReliablePacketBuffer::popSeqnum(u16 seqnum)
231 MutexAutoLock listlock(m_list_mutex);
232 RPBSearchResult r = findPacket(seqnum);
233 if (r == notFound()) {
234 LOG(dout_con<<"Sequence number: " << seqnum
235 << " not found in reliable buffer"<<std::endl);
236 throw NotFoundException("seqnum not found in buffer");
238 BufferedPacket p = *r;
241 RPBSearchResult next = r;
243 if (next != notFound()) {
244 u16 s = readU16(&(next->data[BASE_HEADER_SIZE+1]));
245 m_oldest_non_answered_ack = s;
250 if (m_list.empty()) {
251 m_oldest_non_answered_ack = 0;
253 m_oldest_non_answered_ack =
254 readU16(&m_list.begin()->data[BASE_HEADER_SIZE + 1]);
259 void ReliablePacketBuffer::insert(BufferedPacket &p, u16 next_expected)
261 MutexAutoLock listlock(m_list_mutex);
262 if (p.data.getSize() < BASE_HEADER_SIZE + 3) {
263 errorstream << "ReliablePacketBuffer::insert(): Invalid data size for "
264 "reliable packet" << std::endl;
267 u8 type = readU8(&p.data[BASE_HEADER_SIZE + 0]);
268 if (type != PACKET_TYPE_RELIABLE) {
269 errorstream << "ReliablePacketBuffer::insert(): type is not reliable"
273 u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE + 1]);
275 if (!seqnum_in_window(seqnum, next_expected, MAX_RELIABLE_WINDOW_SIZE)) {
276 errorstream << "ReliablePacketBuffer::insert(): seqnum is outside of "
277 "expected window " << std::endl;
280 if (seqnum == next_expected) {
281 errorstream << "ReliablePacketBuffer::insert(): seqnum is next expected"
286 sanity_check(m_list.size() <= SEQNUM_MAX); // FIXME: Handle the error?
288 // Find the right place for the packet and insert it there
289 // If list is empty, just add it
293 m_oldest_non_answered_ack = seqnum;
298 // Otherwise find the right place
299 std::list<BufferedPacket>::iterator i = m_list.begin();
300 // Find the first packet in the list which has a higher seqnum
301 u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
303 /* case seqnum is smaller then next_expected seqnum */
304 /* this is true e.g. on wrap around */
305 if (seqnum < next_expected) {
306 while(((s < seqnum) || (s >= next_expected)) && (i != m_list.end())) {
308 if (i != m_list.end())
309 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
312 /* non wrap around case (at least for incoming and next_expected */
315 while(((s < seqnum) && (s >= next_expected)) && (i != m_list.end())) {
317 if (i != m_list.end())
318 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
323 /* nothing to do this seems to be a resent packet */
324 /* for paranoia reason data should be compared */
326 (readU16(&(i->data[BASE_HEADER_SIZE+1])) != seqnum) ||
327 (i->data.getSize() != p.data.getSize()) ||
328 (i->address != p.address)
331 /* if this happens your maximum transfer window may be to big */
333 "Duplicated seqnum %d non matching packet detected:\n",
335 fprintf(stderr, "Old: seqnum: %05d size: %04d, address: %s\n",
336 readU16(&(i->data[BASE_HEADER_SIZE+1])),i->data.getSize(),
337 i->address.serializeString().c_str());
338 fprintf(stderr, "New: seqnum: %05d size: %04u, address: %s\n",
339 readU16(&(p.data[BASE_HEADER_SIZE+1])),p.data.getSize(),
340 p.address.serializeString().c_str());
341 throw IncomingDataCorruption("duplicated packet isn't same as original one");
344 /* insert or push back */
345 else if (i != m_list.end()) {
351 /* update last packet number */
352 m_oldest_non_answered_ack = readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]);
355 void ReliablePacketBuffer::incrementTimeouts(float dtime)
357 MutexAutoLock listlock(m_list_mutex);
358 for (BufferedPacket &bufferedPacket : m_list) {
359 bufferedPacket.time += dtime;
360 bufferedPacket.totaltime += dtime;
364 std::list<BufferedPacket> ReliablePacketBuffer::getTimedOuts(float timeout,
365 unsigned int max_packets)
367 MutexAutoLock listlock(m_list_mutex);
368 std::list<BufferedPacket> timed_outs;
369 for (BufferedPacket &bufferedPacket : m_list) {
370 if (bufferedPacket.time >= timeout) {
371 timed_outs.push_back(bufferedPacket);
373 //this packet will be sent right afterwards reset timeout here
374 bufferedPacket.time = 0.0f;
375 if (timed_outs.size() >= max_packets)
386 bool IncomingSplitPacket::insert(u32 chunk_num, SharedBuffer<u8> &chunkdata)
388 sanity_check(chunk_num < chunk_count);
390 // If chunk already exists, ignore it.
391 // Sometimes two identical packets may arrive when there is network
392 // lag and the server re-sends stuff.
393 if (chunks.find(chunk_num) != chunks.end())
396 // Set chunk data in buffer
397 chunks[chunk_num] = chunkdata;
402 SharedBuffer<u8> IncomingSplitPacket::reassemble()
404 sanity_check(allReceived());
406 // Calculate total size
408 for (const auto &chunk : chunks)
409 totalsize += chunk.second.getSize();
411 SharedBuffer<u8> fulldata(totalsize);
413 // Copy chunks to data buffer
415 for (u32 chunk_i = 0; chunk_i < chunk_count; chunk_i++) {
416 const SharedBuffer<u8> &buf = chunks[chunk_i];
417 memcpy(&fulldata[start], *buf, buf.getSize());
418 start += buf.getSize();
428 IncomingSplitBuffer::~IncomingSplitBuffer()
430 MutexAutoLock listlock(m_map_mutex);
431 for (auto &i : m_buf) {
436 SharedBuffer<u8> IncomingSplitBuffer::insert(const BufferedPacket &p, bool reliable)
438 MutexAutoLock listlock(m_map_mutex);
439 u32 headersize = BASE_HEADER_SIZE + 7;
440 if (p.data.getSize() < headersize) {
441 errorstream << "Invalid data size for split packet" << std::endl;
442 return SharedBuffer<u8>();
444 u8 type = readU8(&p.data[BASE_HEADER_SIZE+0]);
445 u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]);
446 u16 chunk_count = readU16(&p.data[BASE_HEADER_SIZE+3]);
447 u16 chunk_num = readU16(&p.data[BASE_HEADER_SIZE+5]);
449 if (type != PACKET_TYPE_SPLIT) {
450 errorstream << "IncomingSplitBuffer::insert(): type is not split"
452 return SharedBuffer<u8>();
454 if (chunk_num >= chunk_count) {
455 errorstream << "IncomingSplitBuffer::insert(): chunk_num=" << chunk_num
456 << " >= chunk_count=" << chunk_count << std::endl;
457 return SharedBuffer<u8>();
460 // Add if doesn't exist
461 IncomingSplitPacket *sp;
462 if (m_buf.find(seqnum) == m_buf.end()) {
463 sp = new IncomingSplitPacket(chunk_count, reliable);
469 if (chunk_count != sp->chunk_count) {
470 errorstream << "IncomingSplitBuffer::insert(): chunk_count="
471 << chunk_count << " != sp->chunk_count=" << sp->chunk_count
473 return SharedBuffer<u8>();
475 if (reliable != sp->reliable)
476 LOG(derr_con<<"Connection: WARNING: reliable="<<reliable
477 <<" != sp->reliable="<<sp->reliable
480 // Cut chunk data out of packet
481 u32 chunkdatasize = p.data.getSize() - headersize;
482 SharedBuffer<u8> chunkdata(chunkdatasize);
483 memcpy(*chunkdata, &(p.data[headersize]), chunkdatasize);
485 if (!sp->insert(chunk_num, chunkdata))
486 return SharedBuffer<u8>();
488 // If not all chunks are received, return empty buffer
489 if (!sp->allReceived())
490 return SharedBuffer<u8>();
492 SharedBuffer<u8> fulldata = sp->reassemble();
494 // Remove sp from buffer
501 void IncomingSplitBuffer::removeUnreliableTimedOuts(float dtime, float timeout)
503 std::deque<u16> remove_queue;
505 MutexAutoLock listlock(m_map_mutex);
506 for (auto &i : m_buf) {
507 IncomingSplitPacket *p = i.second;
508 // Reliable ones are not removed by timeout
512 if (p->time >= timeout)
513 remove_queue.push_back(i.first);
516 for (u16 j : remove_queue) {
517 MutexAutoLock listlock(m_map_mutex);
518 LOG(dout_con<<"NOTE: Removing timed out unreliable split packet"<<std::endl);
528 void ConnectionCommand::send(session_t peer_id_, u8 channelnum_, NetworkPacket *pkt,
533 channelnum = channelnum_;
534 data = pkt->oldForgePacket();
535 reliable = reliable_;
542 u16 Channel::readNextIncomingSeqNum()
544 MutexAutoLock internal(m_internal_mutex);
545 return next_incoming_seqnum;
548 u16 Channel::incNextIncomingSeqNum()
550 MutexAutoLock internal(m_internal_mutex);
551 u16 retval = next_incoming_seqnum;
552 next_incoming_seqnum++;
556 u16 Channel::readNextSplitSeqNum()
558 MutexAutoLock internal(m_internal_mutex);
559 return next_outgoing_split_seqnum;
561 void Channel::setNextSplitSeqNum(u16 seqnum)
563 MutexAutoLock internal(m_internal_mutex);
564 next_outgoing_split_seqnum = seqnum;
567 u16 Channel::getOutgoingSequenceNumber(bool& successful)
569 MutexAutoLock internal(m_internal_mutex);
570 u16 retval = next_outgoing_seqnum;
571 u16 lowest_unacked_seqnumber;
573 /* shortcut if there ain't any packet in outgoing list */
574 if (outgoing_reliables_sent.empty())
576 next_outgoing_seqnum++;
580 if (outgoing_reliables_sent.getFirstSeqnum(lowest_unacked_seqnumber))
582 if (lowest_unacked_seqnumber < next_outgoing_seqnum) {
583 // ugly cast but this one is required in order to tell compiler we
584 // know about difference of two unsigned may be negative in general
585 // but we already made sure it won't happen in this case
586 if (((u16)(next_outgoing_seqnum - lowest_unacked_seqnumber)) > window_size) {
592 // ugly cast but this one is required in order to tell compiler we
593 // know about difference of two unsigned may be negative in general
594 // but we already made sure it won't happen in this case
595 if ((next_outgoing_seqnum + (u16)(SEQNUM_MAX - lowest_unacked_seqnumber)) >
603 next_outgoing_seqnum++;
607 u16 Channel::readOutgoingSequenceNumber()
609 MutexAutoLock internal(m_internal_mutex);
610 return next_outgoing_seqnum;
613 bool Channel::putBackSequenceNumber(u16 seqnum)
615 if (((seqnum + 1) % (SEQNUM_MAX+1)) == next_outgoing_seqnum) {
617 next_outgoing_seqnum = seqnum;
623 void Channel::UpdateBytesSent(unsigned int bytes, unsigned int packets)
625 MutexAutoLock internal(m_internal_mutex);
626 current_bytes_transfered += bytes;
627 current_packet_successful += packets;
630 void Channel::UpdateBytesReceived(unsigned int bytes) {
631 MutexAutoLock internal(m_internal_mutex);
632 current_bytes_received += bytes;
635 void Channel::UpdateBytesLost(unsigned int bytes)
637 MutexAutoLock internal(m_internal_mutex);
638 current_bytes_lost += bytes;
642 void Channel::UpdatePacketLossCounter(unsigned int count)
644 MutexAutoLock internal(m_internal_mutex);
645 current_packet_loss += count;
648 void Channel::UpdatePacketTooLateCounter()
650 MutexAutoLock internal(m_internal_mutex);
651 current_packet_too_late++;
654 void Channel::UpdateTimers(float dtime)
656 bpm_counter += dtime;
657 packet_loss_counter += dtime;
659 if (packet_loss_counter > 1.0f) {
660 packet_loss_counter -= 1.0f;
662 unsigned int packet_loss = 11; /* use a neutral value for initialization */
663 unsigned int packets_successful = 0;
664 //unsigned int packet_too_late = 0;
666 bool reasonable_amount_of_data_transmitted = false;
669 MutexAutoLock internal(m_internal_mutex);
670 packet_loss = current_packet_loss;
671 //packet_too_late = current_packet_too_late;
672 packets_successful = current_packet_successful;
674 if (current_bytes_transfered > (unsigned int) (window_size*512/2)) {
675 reasonable_amount_of_data_transmitted = true;
677 current_packet_loss = 0;
678 current_packet_too_late = 0;
679 current_packet_successful = 0;
682 /* dynamic window size */
683 float successful_to_lost_ratio = 0.0f;
686 if (packets_successful > 0) {
687 successful_to_lost_ratio = packet_loss/packets_successful;
688 } else if (packet_loss > 0) {
689 window_size = std::max(
691 MIN_RELIABLE_WINDOW_SIZE);
696 if ((successful_to_lost_ratio < 0.01f) &&
697 (window_size < MAX_RELIABLE_WINDOW_SIZE)) {
698 /* don't even think about increasing if we didn't even
699 * use major parts of our window */
700 if (reasonable_amount_of_data_transmitted)
701 window_size = std::min(
703 MAX_RELIABLE_WINDOW_SIZE);
704 } else if ((successful_to_lost_ratio < 0.05f) &&
705 (window_size < MAX_RELIABLE_WINDOW_SIZE)) {
706 /* don't even think about increasing if we didn't even
707 * use major parts of our window */
708 if (reasonable_amount_of_data_transmitted)
709 window_size = std::min(
711 MAX_RELIABLE_WINDOW_SIZE);
712 } else if (successful_to_lost_ratio > 0.15f) {
713 window_size = std::max(
715 MIN_RELIABLE_WINDOW_SIZE);
716 } else if (successful_to_lost_ratio > 0.1f) {
717 window_size = std::max(
719 MIN_RELIABLE_WINDOW_SIZE);
724 if (bpm_counter > 10.0f) {
726 MutexAutoLock internal(m_internal_mutex);
728 (((float) current_bytes_transfered)/bpm_counter)/1024.0f;
729 current_bytes_transfered = 0;
731 (((float) current_bytes_lost)/bpm_counter)/1024.0f;
732 current_bytes_lost = 0;
734 (((float) current_bytes_received)/bpm_counter)/1024.0f;
735 current_bytes_received = 0;
739 if (cur_kbps > max_kbps) {
743 if (cur_kbps_lost > max_kbps_lost) {
744 max_kbps_lost = cur_kbps_lost;
747 if (cur_incoming_kbps > max_incoming_kbps) {
748 max_incoming_kbps = cur_incoming_kbps;
751 rate_samples = MYMIN(rate_samples+1,10);
752 float old_fraction = ((float) (rate_samples-1) )/( (float) rate_samples);
753 avg_kbps = avg_kbps * old_fraction +
754 cur_kbps * (1.0 - old_fraction);
755 avg_kbps_lost = avg_kbps_lost * old_fraction +
756 cur_kbps_lost * (1.0 - old_fraction);
757 avg_incoming_kbps = avg_incoming_kbps * old_fraction +
758 cur_incoming_kbps * (1.0 - old_fraction);
767 PeerHelper::PeerHelper(Peer* peer) :
770 if (peer && !peer->IncUseCount())
774 PeerHelper::~PeerHelper()
777 m_peer->DecUseCount();
782 PeerHelper& PeerHelper::operator=(Peer* peer)
785 if (peer && !peer->IncUseCount())
790 Peer* PeerHelper::operator->() const
795 Peer* PeerHelper::operator&() const
800 bool PeerHelper::operator!()
805 bool PeerHelper::operator!=(void* ptr)
807 return ((void*) m_peer != ptr);
810 bool Peer::IncUseCount()
812 MutexAutoLock lock(m_exclusive_access_mutex);
814 if (!m_pending_deletion) {
822 void Peer::DecUseCount()
825 MutexAutoLock lock(m_exclusive_access_mutex);
826 sanity_check(m_usage > 0);
829 if (!((m_pending_deletion) && (m_usage == 0)))
835 void Peer::RTTStatistics(float rtt, const std::string &profiler_id,
836 unsigned int num_samples) {
838 if (m_last_rtt > 0) {
839 /* set min max values */
840 if (rtt < m_rtt.min_rtt)
842 if (rtt >= m_rtt.max_rtt)
845 /* do average calculation */
846 if (m_rtt.avg_rtt < 0.0)
849 m_rtt.avg_rtt = m_rtt.avg_rtt * (num_samples/(num_samples-1)) +
850 rtt * (1/num_samples);
852 /* do jitter calculation */
854 //just use some neutral value at beginning
855 float jitter = m_rtt.jitter_min;
857 if (rtt > m_last_rtt)
858 jitter = rtt-m_last_rtt;
860 if (rtt <= m_last_rtt)
861 jitter = m_last_rtt - rtt;
863 if (jitter < m_rtt.jitter_min)
864 m_rtt.jitter_min = jitter;
865 if (jitter >= m_rtt.jitter_max)
866 m_rtt.jitter_max = jitter;
868 if (m_rtt.jitter_avg < 0.0)
869 m_rtt.jitter_avg = jitter;
871 m_rtt.jitter_avg = m_rtt.jitter_avg * (num_samples/(num_samples-1)) +
872 jitter * (1/num_samples);
874 if (!profiler_id.empty()) {
875 g_profiler->graphAdd(profiler_id + " RTT [ms]", rtt * 1000.f);
876 g_profiler->graphAdd(profiler_id + " jitter [ms]", jitter * 1000.f);
879 /* save values required for next loop */
883 bool Peer::isTimedOut(float timeout)
885 MutexAutoLock lock(m_exclusive_access_mutex);
886 u64 current_time = porting::getTimeMs();
888 float dtime = CALC_DTIME(m_last_timeout_check,current_time);
889 m_last_timeout_check = current_time;
891 m_timeout_counter += dtime;
893 return m_timeout_counter > timeout;
899 MutexAutoLock usage_lock(m_exclusive_access_mutex);
900 m_pending_deletion = true;
905 PROFILE(std::stringstream peerIdentifier1);
906 PROFILE(peerIdentifier1 << "runTimeouts[" << m_connection->getDesc()
907 << ";" << id << ";RELIABLE]");
908 PROFILE(g_profiler->remove(peerIdentifier1.str()));
909 PROFILE(std::stringstream peerIdentifier2);
910 PROFILE(peerIdentifier2 << "sendPackets[" << m_connection->getDesc()
911 << ";" << id << ";RELIABLE]");
912 PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier2.str(), SPT_AVG));
917 UDPPeer::UDPPeer(u16 a_id, Address a_address, Connection* connection) :
918 Peer(a_address,a_id,connection)
920 for (Channel &channel : channels)
921 channel.setWindowSize(g_settings->getU16("max_packets_per_iteration"));
924 bool UDPPeer::getAddress(MTProtocols type,Address& toset)
926 if ((type == MTP_UDP) || (type == MTP_MINETEST_RELIABLE_UDP) || (type == MTP_PRIMARY))
935 void UDPPeer::reportRTT(float rtt)
940 RTTStatistics(rtt,"rudp",MAX_RELIABLE_WINDOW_SIZE*10);
942 float timeout = getStat(AVG_RTT) * RESEND_TIMEOUT_FACTOR;
943 if (timeout < RESEND_TIMEOUT_MIN)
944 timeout = RESEND_TIMEOUT_MIN;
945 if (timeout > RESEND_TIMEOUT_MAX)
946 timeout = RESEND_TIMEOUT_MAX;
948 MutexAutoLock usage_lock(m_exclusive_access_mutex);
949 resend_timeout = timeout;
952 bool UDPPeer::Ping(float dtime,SharedBuffer<u8>& data)
954 m_ping_timer += dtime;
955 if (m_ping_timer >= PING_TIMEOUT)
957 // Create and send PING packet
958 writeU8(&data[0], PACKET_TYPE_CONTROL);
959 writeU8(&data[1], CONTROLTYPE_PING);
966 void UDPPeer::PutReliableSendCommand(ConnectionCommand &c,
967 unsigned int max_packet_size)
969 if (m_pending_disconnect)
972 if ( channels[c.channelnum].queued_commands.empty() &&
973 /* don't queue more packets then window size */
974 (channels[c.channelnum].queued_reliables.size()
975 < (channels[c.channelnum].getWindowSize()/2))) {
976 LOG(dout_con<<m_connection->getDesc()
977 <<" processing reliable command for peer id: " << c.peer_id
978 <<" data size: " << c.data.getSize() << std::endl);
979 if (!processReliableSendCommand(c,max_packet_size)) {
980 channels[c.channelnum].queued_commands.push_back(c);
984 LOG(dout_con<<m_connection->getDesc()
985 <<" Queueing reliable command for peer id: " << c.peer_id
986 <<" data size: " << c.data.getSize() <<std::endl);
987 channels[c.channelnum].queued_commands.push_back(c);
991 bool UDPPeer::processReliableSendCommand(
992 ConnectionCommand &c,
993 unsigned int max_packet_size)
995 if (m_pending_disconnect)
998 u32 chunksize_max = max_packet_size
1000 - RELIABLE_HEADER_SIZE;
1002 sanity_check(c.data.getSize() < MAX_RELIABLE_WINDOW_SIZE*512);
1004 std::list<SharedBuffer<u8>> originals;
1005 u16 split_sequence_number = channels[c.channelnum].readNextSplitSeqNum();
1008 originals.emplace_back(c.data);
1010 makeAutoSplitPacket(c.data, chunksize_max,split_sequence_number, &originals);
1011 channels[c.channelnum].setNextSplitSeqNum(split_sequence_number);
1014 bool have_sequence_number = true;
1015 bool have_initial_sequence_number = false;
1016 std::queue<BufferedPacket> toadd;
1017 volatile u16 initial_sequence_number = 0;
1019 for (SharedBuffer<u8> &original : originals) {
1020 u16 seqnum = channels[c.channelnum].getOutgoingSequenceNumber(have_sequence_number);
1022 /* oops, we don't have enough sequence numbers to send this packet */
1023 if (!have_sequence_number)
1026 if (!have_initial_sequence_number)
1028 initial_sequence_number = seqnum;
1029 have_initial_sequence_number = true;
1032 SharedBuffer<u8> reliable = makeReliablePacket(original, seqnum);
1034 // Add base headers and make a packet
1035 BufferedPacket p = con::makePacket(address, reliable,
1036 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1042 if (have_sequence_number) {
1043 volatile u16 pcount = 0;
1044 while (!toadd.empty()) {
1045 BufferedPacket p = toadd.front();
1047 // LOG(dout_con<<connection->getDesc()
1048 // << " queuing reliable packet for peer_id: " << c.peer_id
1049 // << " channel: " << (c.channelnum&0xFF)
1050 // << " seqnum: " << readU16(&p.data[BASE_HEADER_SIZE+1])
1052 channels[c.channelnum].queued_reliables.push(p);
1055 sanity_check(channels[c.channelnum].queued_reliables.size() < 0xFFFF);
1059 volatile u16 packets_available = toadd.size();
1060 /* we didn't get a single sequence number no need to fill queue */
1061 if (!have_initial_sequence_number) {
1065 while (!toadd.empty()) {
1069 bool successfully_put_back_sequence_number
1070 = channels[c.channelnum].putBackSequenceNumber(
1071 (initial_sequence_number+toadd.size() % (SEQNUM_MAX+1)));
1073 FATAL_ERROR_IF(!successfully_put_back_sequence_number, "error");
1076 LOG(dout_con<<m_connection->getDesc()
1077 << " Windowsize exceeded on reliable sending "
1078 << c.data.getSize() << " bytes"
1079 << std::endl << "\t\tinitial_sequence_number: "
1080 << initial_sequence_number
1081 << std::endl << "\t\tgot at most : "
1082 << packets_available << " packets"
1083 << std::endl << "\t\tpackets queued : "
1084 << channels[c.channelnum].outgoing_reliables_sent.size()
1090 void UDPPeer::RunCommandQueues(
1091 unsigned int max_packet_size,
1092 unsigned int maxcommands,
1093 unsigned int maxtransfer)
1096 for (Channel &channel : channels) {
1097 unsigned int commands_processed = 0;
1099 if ((!channel.queued_commands.empty()) &&
1100 (channel.queued_reliables.size() < maxtransfer) &&
1101 (commands_processed < maxcommands)) {
1103 ConnectionCommand c = channel.queued_commands.front();
1105 LOG(dout_con << m_connection->getDesc()
1106 << " processing queued reliable command " << std::endl);
1108 // Packet is processed, remove it from queue
1109 if (processReliableSendCommand(c,max_packet_size)) {
1110 channel.queued_commands.pop_front();
1112 LOG(dout_con << m_connection->getDesc()
1113 << " Failed to queue packets for peer_id: " << c.peer_id
1114 << ", delaying sending of " << c.data.getSize()
1115 << " bytes" << std::endl);
1118 catch (ItemNotFoundException &e) {
1119 // intentionally empty
1125 u16 UDPPeer::getNextSplitSequenceNumber(u8 channel)
1127 assert(channel < CHANNEL_COUNT); // Pre-condition
1128 return channels[channel].readNextSplitSeqNum();
1131 void UDPPeer::setNextSplitSequenceNumber(u8 channel, u16 seqnum)
1133 assert(channel < CHANNEL_COUNT); // Pre-condition
1134 channels[channel].setNextSplitSeqNum(seqnum);
1137 SharedBuffer<u8> UDPPeer::addSplitPacket(u8 channel, const BufferedPacket &toadd,
1140 assert(channel < CHANNEL_COUNT); // Pre-condition
1141 return channels[channel].incoming_splits.insert(toadd, reliable);
1148 Connection::Connection(u32 protocol_id, u32 max_packet_size, float timeout,
1149 bool ipv6, PeerHandler *peerhandler) :
1151 m_protocol_id(protocol_id),
1152 m_sendThread(new ConnectionSendThread(max_packet_size, timeout)),
1153 m_receiveThread(new ConnectionReceiveThread(max_packet_size)),
1154 m_bc_peerhandler(peerhandler)
1157 m_udpSocket.setTimeoutMs(5);
1159 m_sendThread->setParent(this);
1160 m_receiveThread->setParent(this);
1162 m_sendThread->start();
1163 m_receiveThread->start();
1167 Connection::~Connection()
1169 m_shutting_down = true;
1170 // request threads to stop
1171 m_sendThread->stop();
1172 m_receiveThread->stop();
1174 //TODO for some unkonwn reason send/receive threads do not exit as they're
1175 // supposed to be but wait on peer timeout. To speed up shutdown we reduce
1176 // timeout to half a second.
1177 m_sendThread->setPeerTimeout(0.5);
1179 // wait for threads to finish
1180 m_sendThread->wait();
1181 m_receiveThread->wait();
1184 for (auto &peer : m_peers) {
1189 /* Internal stuff */
1190 void Connection::putEvent(ConnectionEvent &e)
1192 assert(e.type != CONNEVENT_NONE); // Pre-condition
1193 m_event_queue.push_back(e);
1196 void Connection::TriggerSend()
1198 m_sendThread->Trigger();
1201 PeerHelper Connection::getPeerNoEx(session_t peer_id)
1203 MutexAutoLock peerlock(m_peers_mutex);
1204 std::map<session_t, Peer *>::iterator node = m_peers.find(peer_id);
1206 if (node == m_peers.end()) {
1207 return PeerHelper(NULL);
1211 FATAL_ERROR_IF(node->second->id != peer_id, "Invalid peer id");
1213 return PeerHelper(node->second);
1216 /* find peer_id for address */
1217 u16 Connection::lookupPeer(Address& sender)
1219 MutexAutoLock peerlock(m_peers_mutex);
1220 std::map<u16, Peer*>::iterator j;
1221 j = m_peers.begin();
1222 for(; j != m_peers.end(); ++j)
1224 Peer *peer = j->second;
1225 if (peer->isPendingDeletion())
1230 if ((peer->getAddress(MTP_MINETEST_RELIABLE_UDP, tocheck)) && (tocheck == sender))
1233 if ((peer->getAddress(MTP_UDP, tocheck)) && (tocheck == sender))
1237 return PEER_ID_INEXISTENT;
1240 bool Connection::deletePeer(session_t peer_id, bool timeout)
1244 /* lock list as short as possible */
1246 MutexAutoLock peerlock(m_peers_mutex);
1247 if (m_peers.find(peer_id) == m_peers.end())
1249 peer = m_peers[peer_id];
1250 m_peers.erase(peer_id);
1251 m_peer_ids.remove(peer_id);
1254 Address peer_address;
1255 //any peer has a primary address this never fails!
1256 peer->getAddress(MTP_PRIMARY, peer_address);
1259 e.peerRemoved(peer_id, timeout, peer_address);
1269 ConnectionEvent Connection::waitEvent(u32 timeout_ms)
1272 return m_event_queue.pop_front(timeout_ms);
1273 } catch(ItemNotFoundException &ex) {
1275 e.type = CONNEVENT_NONE;
1280 void Connection::putCommand(ConnectionCommand &c)
1282 if (!m_shutting_down) {
1283 m_command_queue.push_back(c);
1284 m_sendThread->Trigger();
1288 void Connection::Serve(Address bind_addr)
1290 ConnectionCommand c;
1295 void Connection::Connect(Address address)
1297 ConnectionCommand c;
1302 bool Connection::Connected()
1304 MutexAutoLock peerlock(m_peers_mutex);
1306 if (m_peers.size() != 1)
1309 std::map<session_t, Peer *>::iterator node = m_peers.find(PEER_ID_SERVER);
1310 if (node == m_peers.end())
1313 if (m_peer_id == PEER_ID_INEXISTENT)
1319 void Connection::Disconnect()
1321 ConnectionCommand c;
1326 bool Connection::Receive(NetworkPacket *pkt, u32 timeout)
1329 Note that this function can potentially wait infinitely if non-data
1330 events keep happening before the timeout expires.
1331 This is not considered to be a problem (is it?)
1334 ConnectionEvent e = waitEvent(timeout);
1335 if (e.type != CONNEVENT_NONE)
1336 LOG(dout_con << getDesc() << ": Receive: got event: "
1337 << e.describe() << std::endl);
1339 case CONNEVENT_NONE:
1341 case CONNEVENT_DATA_RECEIVED:
1342 // Data size is lesser than command size, ignoring packet
1343 if (e.data.getSize() < 2) {
1347 pkt->putRawPacket(*e.data, e.data.getSize(), e.peer_id);
1349 case CONNEVENT_PEER_ADDED: {
1350 UDPPeer tmp(e.peer_id, e.address, this);
1351 if (m_bc_peerhandler)
1352 m_bc_peerhandler->peerAdded(&tmp);
1355 case CONNEVENT_PEER_REMOVED: {
1356 UDPPeer tmp(e.peer_id, e.address, this);
1357 if (m_bc_peerhandler)
1358 m_bc_peerhandler->deletingPeer(&tmp, e.timeout);
1361 case CONNEVENT_BIND_FAILED:
1362 throw ConnectionBindFailed("Failed to bind socket "
1363 "(port already in use?)");
1369 void Connection::Receive(NetworkPacket *pkt)
1371 bool any = Receive(pkt, m_bc_receive_timeout);
1373 throw NoIncomingDataException("No incoming data");
1376 bool Connection::TryReceive(NetworkPacket *pkt)
1378 return Receive(pkt, 0);
1381 void Connection::Send(session_t peer_id, u8 channelnum,
1382 NetworkPacket *pkt, bool reliable)
1384 assert(channelnum < CHANNEL_COUNT); // Pre-condition
1386 ConnectionCommand c;
1388 c.send(peer_id, channelnum, pkt, reliable);
1392 Address Connection::GetPeerAddress(session_t peer_id)
1394 PeerHelper peer = getPeerNoEx(peer_id);
1397 throw PeerNotFoundException("No address for peer found!");
1398 Address peer_address;
1399 peer->getAddress(MTP_PRIMARY, peer_address);
1400 return peer_address;
1403 float Connection::getPeerStat(session_t peer_id, rtt_stat_type type)
1405 PeerHelper peer = getPeerNoEx(peer_id);
1406 if (!peer) return -1;
1407 return peer->getStat(type);
1410 float Connection::getLocalStat(rate_stat_type type)
1412 PeerHelper peer = getPeerNoEx(PEER_ID_SERVER);
1414 FATAL_ERROR_IF(!peer, "Connection::getLocalStat we couldn't get our own peer? are you serious???");
1418 for (Channel &channel : dynamic_cast<UDPPeer *>(&peer)->channels) {
1421 retval += channel.getCurrentDownloadRateKB();
1424 retval += channel.getAvgDownloadRateKB();
1427 retval += channel.getCurrentIncomingRateKB();
1430 retval += channel.getAvgIncomingRateKB();
1433 retval += channel.getAvgLossRateKB();
1436 retval += channel.getCurrentLossRateKB();
1439 FATAL_ERROR("Connection::getLocalStat Invalid stat type");
1445 u16 Connection::createPeer(Address& sender, MTProtocols protocol, int fd)
1447 // Somebody wants to make a new connection
1449 // Get a unique peer id (2 or higher)
1450 session_t peer_id_new = m_next_remote_peer_id;
1451 u16 overflow = MAX_UDP_PEERS;
1454 Find an unused peer id
1456 MutexAutoLock lock(m_peers_mutex);
1457 bool out_of_ids = false;
1460 if (m_peers.find(peer_id_new) == m_peers.end())
1463 // Check for overflow
1464 if (peer_id_new == overflow) {
1472 errorstream << getDesc() << " ran out of peer ids" << std::endl;
1473 return PEER_ID_INEXISTENT;
1478 peer = new UDPPeer(peer_id_new, sender, this);
1480 m_peers[peer->id] = peer;
1481 m_peer_ids.push_back(peer->id);
1483 m_next_remote_peer_id = (peer_id_new +1 ) % MAX_UDP_PEERS;
1485 LOG(dout_con << getDesc()
1486 << "createPeer(): giving peer_id=" << peer_id_new << std::endl);
1488 ConnectionCommand cmd;
1489 SharedBuffer<u8> reply(4);
1490 writeU8(&reply[0], PACKET_TYPE_CONTROL);
1491 writeU8(&reply[1], CONTROLTYPE_SET_PEER_ID);
1492 writeU16(&reply[2], peer_id_new);
1493 cmd.createPeer(peer_id_new,reply);
1496 // Create peer addition event
1498 e.peerAdded(peer_id_new, sender);
1501 // We're now talking to a valid peer_id
1505 void Connection::PrintInfo(std::ostream &out)
1507 m_info_mutex.lock();
1508 out<<getDesc()<<": ";
1509 m_info_mutex.unlock();
1512 const std::string Connection::getDesc()
1514 return std::string("con(")+
1515 itos(m_udpSocket.GetHandle())+"/"+itos(m_peer_id)+")";
1518 void Connection::DisconnectPeer(session_t peer_id)
1520 ConnectionCommand discon;
1521 discon.disconnect_peer(peer_id);
1525 void Connection::sendAck(session_t peer_id, u8 channelnum, u16 seqnum)
1527 assert(channelnum < CHANNEL_COUNT); // Pre-condition
1529 LOG(dout_con<<getDesc()
1530 <<" Queuing ACK command to peer_id: " << peer_id <<
1531 " channel: " << (channelnum & 0xFF) <<
1532 " seqnum: " << seqnum << std::endl);
1534 ConnectionCommand c;
1535 SharedBuffer<u8> ack(4);
1536 writeU8(&ack[0], PACKET_TYPE_CONTROL);
1537 writeU8(&ack[1], CONTROLTYPE_ACK);
1538 writeU16(&ack[2], seqnum);
1540 c.ack(peer_id, channelnum, ack);
1542 m_sendThread->Trigger();
1545 UDPPeer* Connection::createServerPeer(Address& address)
1547 if (getPeerNoEx(PEER_ID_SERVER) != 0)
1549 throw ConnectionException("Already connected to a server");
1552 UDPPeer *peer = new UDPPeer(PEER_ID_SERVER, address, this);
1555 MutexAutoLock lock(m_peers_mutex);
1556 m_peers[peer->id] = peer;
1557 m_peer_ids.push_back(peer->id);