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 /******************************************************************************/
48 /* this mutex is used to achieve log message consistency */
49 std::mutex log_message_mutex;
52 MutexAutoLock loglock(log_message_mutex); \
56 // Prevent deadlocks until a solution is found after 5.2.0 (TODO)
63 #define PING_TIMEOUT 5.0
65 BufferedPacket makePacket(Address &address, const SharedBuffer<u8> &data,
66 u32 protocol_id, session_t sender_peer_id, u8 channel)
68 u32 packet_size = data.getSize() + BASE_HEADER_SIZE;
69 BufferedPacket p(packet_size);
72 writeU32(&p.data[0], protocol_id);
73 writeU16(&p.data[4], sender_peer_id);
74 writeU8(&p.data[6], channel);
76 memcpy(&p.data[BASE_HEADER_SIZE], *data, data.getSize());
81 SharedBuffer<u8> makeOriginalPacket(const SharedBuffer<u8> &data)
84 u32 packet_size = data.getSize() + header_size;
85 SharedBuffer<u8> b(packet_size);
87 writeU8(&(b[0]), PACKET_TYPE_ORIGINAL);
88 if (data.getSize() > 0) {
89 memcpy(&(b[header_size]), *data, data.getSize());
94 // Split data in chunks and add TYPE_SPLIT headers to them
95 void makeSplitPacket(const SharedBuffer<u8> &data, u32 chunksize_max, u16 seqnum,
96 std::list<SharedBuffer<u8>> *chunks)
98 // Chunk packets, containing the TYPE_SPLIT header
99 u32 chunk_header_size = 7;
100 u32 maximum_data_size = chunksize_max - chunk_header_size;
106 end = start + maximum_data_size - 1;
107 if (end > data.getSize() - 1)
108 end = data.getSize() - 1;
110 u32 payload_size = end - start + 1;
111 u32 packet_size = chunk_header_size + payload_size;
113 SharedBuffer<u8> chunk(packet_size);
115 writeU8(&chunk[0], PACKET_TYPE_SPLIT);
116 writeU16(&chunk[1], seqnum);
117 // [3] u16 chunk_count is written at next stage
118 writeU16(&chunk[5], chunk_num);
119 memcpy(&chunk[chunk_header_size], &data[start], payload_size);
121 chunks->push_back(chunk);
127 while (end != data.getSize() - 1);
129 for (SharedBuffer<u8> &chunk : *chunks) {
131 writeU16(&(chunk[3]), chunk_count);
135 void makeAutoSplitPacket(const SharedBuffer<u8> &data, u32 chunksize_max,
136 u16 &split_seqnum, std::list<SharedBuffer<u8>> *list)
138 u32 original_header_size = 1;
140 if (data.getSize() + original_header_size > chunksize_max) {
141 makeSplitPacket(data, chunksize_max, split_seqnum, list);
146 list->push_back(makeOriginalPacket(data));
149 SharedBuffer<u8> makeReliablePacket(const SharedBuffer<u8> &data, u16 seqnum)
152 u32 packet_size = data.getSize() + header_size;
153 SharedBuffer<u8> b(packet_size);
155 writeU8(&b[0], PACKET_TYPE_RELIABLE);
156 writeU16(&b[1], seqnum);
158 memcpy(&b[header_size], *data, data.getSize());
167 void ReliablePacketBuffer::print()
169 MutexAutoLock listlock(m_list_mutex);
170 LOG(dout_con<<"Dump of ReliablePacketBuffer:" << std::endl);
171 unsigned int index = 0;
172 for (BufferedPacket &bufferedPacket : m_list) {
173 u16 s = readU16(&(bufferedPacket.data[BASE_HEADER_SIZE+1]));
174 LOG(dout_con<<index<< ":" << s << std::endl);
179 bool ReliablePacketBuffer::empty()
181 MutexAutoLock listlock(m_list_mutex);
182 return m_list.empty();
185 u32 ReliablePacketBuffer::size()
187 MutexAutoLock listlock(m_list_mutex);
188 return m_list.size();
191 RPBSearchResult ReliablePacketBuffer::findPacket(u16 seqnum)
193 std::list<BufferedPacket>::iterator i = m_list.begin();
194 for(; i != m_list.end(); ++i)
196 u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
203 RPBSearchResult ReliablePacketBuffer::notFound()
208 bool ReliablePacketBuffer::getFirstSeqnum(u16& result)
210 MutexAutoLock listlock(m_list_mutex);
213 const BufferedPacket &p = *m_list.begin();
214 result = readU16(&p.data[BASE_HEADER_SIZE + 1]);
218 BufferedPacket ReliablePacketBuffer::popFirst()
220 MutexAutoLock listlock(m_list_mutex);
222 throw NotFoundException("Buffer is empty");
223 BufferedPacket p = *m_list.begin();
224 m_list.erase(m_list.begin());
226 if (m_list.empty()) {
227 m_oldest_non_answered_ack = 0;
229 m_oldest_non_answered_ack =
230 readU16(&m_list.begin()->data[BASE_HEADER_SIZE + 1]);
235 BufferedPacket ReliablePacketBuffer::popSeqnum(u16 seqnum)
237 MutexAutoLock listlock(m_list_mutex);
238 RPBSearchResult r = findPacket(seqnum);
239 if (r == notFound()) {
240 LOG(dout_con<<"Sequence number: " << seqnum
241 << " not found in reliable buffer"<<std::endl);
242 throw NotFoundException("seqnum not found in buffer");
244 BufferedPacket p = *r;
247 RPBSearchResult next = r;
249 if (next != notFound()) {
250 u16 s = readU16(&(next->data[BASE_HEADER_SIZE+1]));
251 m_oldest_non_answered_ack = s;
256 if (m_list.empty()) {
257 m_oldest_non_answered_ack = 0;
259 m_oldest_non_answered_ack =
260 readU16(&m_list.begin()->data[BASE_HEADER_SIZE + 1]);
265 void ReliablePacketBuffer::insert(BufferedPacket &p, u16 next_expected)
267 MutexAutoLock listlock(m_list_mutex);
268 if (p.data.getSize() < BASE_HEADER_SIZE + 3) {
269 errorstream << "ReliablePacketBuffer::insert(): Invalid data size for "
270 "reliable packet" << std::endl;
273 u8 type = readU8(&p.data[BASE_HEADER_SIZE + 0]);
274 if (type != PACKET_TYPE_RELIABLE) {
275 errorstream << "ReliablePacketBuffer::insert(): type is not reliable"
279 u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE + 1]);
281 if (!seqnum_in_window(seqnum, next_expected, MAX_RELIABLE_WINDOW_SIZE)) {
282 errorstream << "ReliablePacketBuffer::insert(): seqnum is outside of "
283 "expected window " << std::endl;
286 if (seqnum == next_expected) {
287 errorstream << "ReliablePacketBuffer::insert(): seqnum is next expected"
292 sanity_check(m_list.size() <= SEQNUM_MAX); // FIXME: Handle the error?
294 // Find the right place for the packet and insert it there
295 // If list is empty, just add it
299 m_oldest_non_answered_ack = seqnum;
304 // Otherwise find the right place
305 std::list<BufferedPacket>::iterator i = m_list.begin();
306 // Find the first packet in the list which has a higher seqnum
307 u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
309 /* case seqnum is smaller then next_expected seqnum */
310 /* this is true e.g. on wrap around */
311 if (seqnum < next_expected) {
312 while(((s < seqnum) || (s >= next_expected)) && (i != m_list.end())) {
314 if (i != m_list.end())
315 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
318 /* non wrap around case (at least for incoming and next_expected */
321 while(((s < seqnum) && (s >= next_expected)) && (i != m_list.end())) {
323 if (i != m_list.end())
324 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
329 /* nothing to do this seems to be a resent packet */
330 /* for paranoia reason data should be compared */
332 (readU16(&(i->data[BASE_HEADER_SIZE+1])) != seqnum) ||
333 (i->data.getSize() != p.data.getSize()) ||
334 (i->address != p.address)
337 /* if this happens your maximum transfer window may be to big */
339 "Duplicated seqnum %d non matching packet detected:\n",
341 fprintf(stderr, "Old: seqnum: %05d size: %04d, address: %s\n",
342 readU16(&(i->data[BASE_HEADER_SIZE+1])),i->data.getSize(),
343 i->address.serializeString().c_str());
344 fprintf(stderr, "New: seqnum: %05d size: %04u, address: %s\n",
345 readU16(&(p.data[BASE_HEADER_SIZE+1])),p.data.getSize(),
346 p.address.serializeString().c_str());
347 throw IncomingDataCorruption("duplicated packet isn't same as original one");
350 /* insert or push back */
351 else if (i != m_list.end()) {
357 /* update last packet number */
358 m_oldest_non_answered_ack = readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]);
361 void ReliablePacketBuffer::incrementTimeouts(float dtime)
363 MutexAutoLock listlock(m_list_mutex);
364 for (BufferedPacket &bufferedPacket : m_list) {
365 bufferedPacket.time += dtime;
366 bufferedPacket.totaltime += dtime;
370 std::list<BufferedPacket> ReliablePacketBuffer::getTimedOuts(float timeout,
371 unsigned int max_packets)
373 MutexAutoLock listlock(m_list_mutex);
374 std::list<BufferedPacket> timed_outs;
375 for (BufferedPacket &bufferedPacket : m_list) {
376 if (bufferedPacket.time >= timeout) {
377 timed_outs.push_back(bufferedPacket);
379 //this packet will be sent right afterwards reset timeout here
380 bufferedPacket.time = 0.0f;
381 if (timed_outs.size() >= max_packets)
392 bool IncomingSplitPacket::insert(u32 chunk_num, SharedBuffer<u8> &chunkdata)
394 sanity_check(chunk_num < chunk_count);
396 // If chunk already exists, ignore it.
397 // Sometimes two identical packets may arrive when there is network
398 // lag and the server re-sends stuff.
399 if (chunks.find(chunk_num) != chunks.end())
402 // Set chunk data in buffer
403 chunks[chunk_num] = chunkdata;
408 SharedBuffer<u8> IncomingSplitPacket::reassemble()
410 sanity_check(allReceived());
412 // Calculate total size
414 for (const auto &chunk : chunks)
415 totalsize += chunk.second.getSize();
417 SharedBuffer<u8> fulldata(totalsize);
419 // Copy chunks to data buffer
421 for (u32 chunk_i = 0; chunk_i < chunk_count; chunk_i++) {
422 const SharedBuffer<u8> &buf = chunks[chunk_i];
423 memcpy(&fulldata[start], *buf, buf.getSize());
424 start += buf.getSize();
434 IncomingSplitBuffer::~IncomingSplitBuffer()
436 MutexAutoLock listlock(m_map_mutex);
437 for (auto &i : m_buf) {
442 SharedBuffer<u8> IncomingSplitBuffer::insert(const BufferedPacket &p, bool reliable)
444 MutexAutoLock listlock(m_map_mutex);
445 u32 headersize = BASE_HEADER_SIZE + 7;
446 if (p.data.getSize() < headersize) {
447 errorstream << "Invalid data size for split packet" << std::endl;
448 return SharedBuffer<u8>();
450 u8 type = readU8(&p.data[BASE_HEADER_SIZE+0]);
451 u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]);
452 u16 chunk_count = readU16(&p.data[BASE_HEADER_SIZE+3]);
453 u16 chunk_num = readU16(&p.data[BASE_HEADER_SIZE+5]);
455 if (type != PACKET_TYPE_SPLIT) {
456 errorstream << "IncomingSplitBuffer::insert(): type is not split"
458 return SharedBuffer<u8>();
460 if (chunk_num >= chunk_count) {
461 errorstream << "IncomingSplitBuffer::insert(): chunk_num=" << chunk_num
462 << " >= chunk_count=" << chunk_count << std::endl;
463 return SharedBuffer<u8>();
466 // Add if doesn't exist
467 IncomingSplitPacket *sp;
468 if (m_buf.find(seqnum) == m_buf.end()) {
469 sp = new IncomingSplitPacket(chunk_count, reliable);
475 if (chunk_count != sp->chunk_count) {
476 errorstream << "IncomingSplitBuffer::insert(): chunk_count="
477 << chunk_count << " != sp->chunk_count=" << sp->chunk_count
479 return SharedBuffer<u8>();
481 if (reliable != sp->reliable)
482 LOG(derr_con<<"Connection: WARNING: reliable="<<reliable
483 <<" != sp->reliable="<<sp->reliable
486 // Cut chunk data out of packet
487 u32 chunkdatasize = p.data.getSize() - headersize;
488 SharedBuffer<u8> chunkdata(chunkdatasize);
489 memcpy(*chunkdata, &(p.data[headersize]), chunkdatasize);
491 if (!sp->insert(chunk_num, chunkdata))
492 return SharedBuffer<u8>();
494 // If not all chunks are received, return empty buffer
495 if (!sp->allReceived())
496 return SharedBuffer<u8>();
498 SharedBuffer<u8> fulldata = sp->reassemble();
500 // Remove sp from buffer
507 void IncomingSplitBuffer::removeUnreliableTimedOuts(float dtime, float timeout)
509 std::deque<u16> remove_queue;
511 MutexAutoLock listlock(m_map_mutex);
512 for (auto &i : m_buf) {
513 IncomingSplitPacket *p = i.second;
514 // Reliable ones are not removed by timeout
518 if (p->time >= timeout)
519 remove_queue.push_back(i.first);
522 for (u16 j : remove_queue) {
523 MutexAutoLock listlock(m_map_mutex);
524 LOG(dout_con<<"NOTE: Removing timed out unreliable split packet"<<std::endl);
534 void ConnectionCommand::send(session_t peer_id_, u8 channelnum_, NetworkPacket *pkt,
539 channelnum = channelnum_;
540 data = pkt->oldForgePacket();
541 reliable = reliable_;
548 u16 Channel::readNextIncomingSeqNum()
550 MutexAutoLock internal(m_internal_mutex);
551 return next_incoming_seqnum;
554 u16 Channel::incNextIncomingSeqNum()
556 MutexAutoLock internal(m_internal_mutex);
557 u16 retval = next_incoming_seqnum;
558 next_incoming_seqnum++;
562 u16 Channel::readNextSplitSeqNum()
564 MutexAutoLock internal(m_internal_mutex);
565 return next_outgoing_split_seqnum;
567 void Channel::setNextSplitSeqNum(u16 seqnum)
569 MutexAutoLock internal(m_internal_mutex);
570 next_outgoing_split_seqnum = seqnum;
573 u16 Channel::getOutgoingSequenceNumber(bool& successful)
575 MutexAutoLock internal(m_internal_mutex);
576 u16 retval = next_outgoing_seqnum;
577 u16 lowest_unacked_seqnumber;
579 /* shortcut if there ain't any packet in outgoing list */
580 if (outgoing_reliables_sent.empty())
582 next_outgoing_seqnum++;
586 if (outgoing_reliables_sent.getFirstSeqnum(lowest_unacked_seqnumber))
588 if (lowest_unacked_seqnumber < next_outgoing_seqnum) {
589 // ugly cast but this one is required in order to tell compiler we
590 // know about difference of two unsigned may be negative in general
591 // but we already made sure it won't happen in this case
592 if (((u16)(next_outgoing_seqnum - lowest_unacked_seqnumber)) > window_size) {
598 // ugly cast but this one is required in order to tell compiler we
599 // know about difference of two unsigned may be negative in general
600 // but we already made sure it won't happen in this case
601 if ((next_outgoing_seqnum + (u16)(SEQNUM_MAX - lowest_unacked_seqnumber)) >
609 next_outgoing_seqnum++;
613 u16 Channel::readOutgoingSequenceNumber()
615 MutexAutoLock internal(m_internal_mutex);
616 return next_outgoing_seqnum;
619 bool Channel::putBackSequenceNumber(u16 seqnum)
621 if (((seqnum + 1) % (SEQNUM_MAX+1)) == next_outgoing_seqnum) {
623 next_outgoing_seqnum = seqnum;
629 void Channel::UpdateBytesSent(unsigned int bytes, unsigned int packets)
631 MutexAutoLock internal(m_internal_mutex);
632 current_bytes_transfered += bytes;
633 current_packet_successful += packets;
636 void Channel::UpdateBytesReceived(unsigned int bytes) {
637 MutexAutoLock internal(m_internal_mutex);
638 current_bytes_received += bytes;
641 void Channel::UpdateBytesLost(unsigned int bytes)
643 MutexAutoLock internal(m_internal_mutex);
644 current_bytes_lost += bytes;
648 void Channel::UpdatePacketLossCounter(unsigned int count)
650 MutexAutoLock internal(m_internal_mutex);
651 current_packet_loss += count;
654 void Channel::UpdatePacketTooLateCounter()
656 MutexAutoLock internal(m_internal_mutex);
657 current_packet_too_late++;
660 void Channel::UpdateTimers(float dtime)
662 bpm_counter += dtime;
663 packet_loss_counter += dtime;
665 if (packet_loss_counter > 1.0f) {
666 packet_loss_counter -= 1.0f;
668 unsigned int packet_loss = 11; /* use a neutral value for initialization */
669 unsigned int packets_successful = 0;
670 //unsigned int packet_too_late = 0;
672 bool reasonable_amount_of_data_transmitted = false;
675 MutexAutoLock internal(m_internal_mutex);
676 packet_loss = current_packet_loss;
677 //packet_too_late = current_packet_too_late;
678 packets_successful = current_packet_successful;
680 if (current_bytes_transfered > (unsigned int) (window_size*512/2)) {
681 reasonable_amount_of_data_transmitted = true;
683 current_packet_loss = 0;
684 current_packet_too_late = 0;
685 current_packet_successful = 0;
688 /* dynamic window size */
689 float successful_to_lost_ratio = 0.0f;
692 if (packets_successful > 0) {
693 successful_to_lost_ratio = packet_loss/packets_successful;
694 } else if (packet_loss > 0) {
695 window_size = std::max(
697 MIN_RELIABLE_WINDOW_SIZE);
702 if ((successful_to_lost_ratio < 0.01f) &&
703 (window_size < MAX_RELIABLE_WINDOW_SIZE)) {
704 /* don't even think about increasing if we didn't even
705 * use major parts of our window */
706 if (reasonable_amount_of_data_transmitted)
707 window_size = std::min(
709 MAX_RELIABLE_WINDOW_SIZE);
710 } else if ((successful_to_lost_ratio < 0.05f) &&
711 (window_size < MAX_RELIABLE_WINDOW_SIZE)) {
712 /* don't even think about increasing if we didn't even
713 * use major parts of our window */
714 if (reasonable_amount_of_data_transmitted)
715 window_size = std::min(
717 MAX_RELIABLE_WINDOW_SIZE);
718 } else if (successful_to_lost_ratio > 0.15f) {
719 window_size = std::max(
721 MIN_RELIABLE_WINDOW_SIZE);
722 } else if (successful_to_lost_ratio > 0.1f) {
723 window_size = std::max(
725 MIN_RELIABLE_WINDOW_SIZE);
730 if (bpm_counter > 10.0f) {
732 MutexAutoLock internal(m_internal_mutex);
734 (((float) current_bytes_transfered)/bpm_counter)/1024.0f;
735 current_bytes_transfered = 0;
737 (((float) current_bytes_lost)/bpm_counter)/1024.0f;
738 current_bytes_lost = 0;
740 (((float) current_bytes_received)/bpm_counter)/1024.0f;
741 current_bytes_received = 0;
745 if (cur_kbps > max_kbps) {
749 if (cur_kbps_lost > max_kbps_lost) {
750 max_kbps_lost = cur_kbps_lost;
753 if (cur_incoming_kbps > max_incoming_kbps) {
754 max_incoming_kbps = cur_incoming_kbps;
757 rate_samples = MYMIN(rate_samples+1,10);
758 float old_fraction = ((float) (rate_samples-1) )/( (float) rate_samples);
759 avg_kbps = avg_kbps * old_fraction +
760 cur_kbps * (1.0 - old_fraction);
761 avg_kbps_lost = avg_kbps_lost * old_fraction +
762 cur_kbps_lost * (1.0 - old_fraction);
763 avg_incoming_kbps = avg_incoming_kbps * old_fraction +
764 cur_incoming_kbps * (1.0 - old_fraction);
773 PeerHelper::PeerHelper(Peer* peer) :
776 if (peer && !peer->IncUseCount())
780 PeerHelper::~PeerHelper()
783 m_peer->DecUseCount();
788 PeerHelper& PeerHelper::operator=(Peer* peer)
791 if (peer && !peer->IncUseCount())
796 Peer* PeerHelper::operator->() const
801 Peer* PeerHelper::operator&() const
806 bool PeerHelper::operator!()
811 bool PeerHelper::operator!=(void* ptr)
813 return ((void*) m_peer != ptr);
816 bool Peer::IncUseCount()
818 MutexAutoLock lock(m_exclusive_access_mutex);
820 if (!m_pending_deletion) {
828 void Peer::DecUseCount()
831 MutexAutoLock lock(m_exclusive_access_mutex);
832 sanity_check(m_usage > 0);
835 if (!((m_pending_deletion) && (m_usage == 0)))
841 void Peer::RTTStatistics(float rtt, const std::string &profiler_id,
842 unsigned int num_samples) {
844 if (m_last_rtt > 0) {
845 /* set min max values */
846 if (rtt < m_rtt.min_rtt)
848 if (rtt >= m_rtt.max_rtt)
851 /* do average calculation */
852 if (m_rtt.avg_rtt < 0.0)
855 m_rtt.avg_rtt = m_rtt.avg_rtt * (num_samples/(num_samples-1)) +
856 rtt * (1/num_samples);
858 /* do jitter calculation */
860 //just use some neutral value at beginning
861 float jitter = m_rtt.jitter_min;
863 if (rtt > m_last_rtt)
864 jitter = rtt-m_last_rtt;
866 if (rtt <= m_last_rtt)
867 jitter = m_last_rtt - rtt;
869 if (jitter < m_rtt.jitter_min)
870 m_rtt.jitter_min = jitter;
871 if (jitter >= m_rtt.jitter_max)
872 m_rtt.jitter_max = jitter;
874 if (m_rtt.jitter_avg < 0.0)
875 m_rtt.jitter_avg = jitter;
877 m_rtt.jitter_avg = m_rtt.jitter_avg * (num_samples/(num_samples-1)) +
878 jitter * (1/num_samples);
880 if (!profiler_id.empty()) {
881 g_profiler->graphAdd(profiler_id + " RTT [ms]", rtt * 1000.f);
882 g_profiler->graphAdd(profiler_id + " jitter [ms]", jitter * 1000.f);
885 /* save values required for next loop */
889 bool Peer::isTimedOut(float timeout)
891 MutexAutoLock lock(m_exclusive_access_mutex);
892 u64 current_time = porting::getTimeMs();
894 float dtime = CALC_DTIME(m_last_timeout_check,current_time);
895 m_last_timeout_check = current_time;
897 m_timeout_counter += dtime;
899 return m_timeout_counter > timeout;
905 MutexAutoLock usage_lock(m_exclusive_access_mutex);
906 m_pending_deletion = true;
911 PROFILE(std::stringstream peerIdentifier1);
912 PROFILE(peerIdentifier1 << "runTimeouts[" << m_connection->getDesc()
913 << ";" << id << ";RELIABLE]");
914 PROFILE(g_profiler->remove(peerIdentifier1.str()));
915 PROFILE(std::stringstream peerIdentifier2);
916 PROFILE(peerIdentifier2 << "sendPackets[" << m_connection->getDesc()
917 << ";" << id << ";RELIABLE]");
918 PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier2.str(), SPT_AVG));
923 UDPPeer::UDPPeer(u16 a_id, Address a_address, Connection* connection) :
924 Peer(a_address,a_id,connection)
926 for (Channel &channel : channels)
927 channel.setWindowSize(START_RELIABLE_WINDOW_SIZE);
930 bool UDPPeer::getAddress(MTProtocols type,Address& toset)
932 if ((type == MTP_UDP) || (type == MTP_MINETEST_RELIABLE_UDP) || (type == MTP_PRIMARY))
941 void UDPPeer::reportRTT(float rtt)
946 RTTStatistics(rtt,"rudp",MAX_RELIABLE_WINDOW_SIZE*10);
948 float timeout = getStat(AVG_RTT) * RESEND_TIMEOUT_FACTOR;
949 if (timeout < RESEND_TIMEOUT_MIN)
950 timeout = RESEND_TIMEOUT_MIN;
951 if (timeout > RESEND_TIMEOUT_MAX)
952 timeout = RESEND_TIMEOUT_MAX;
954 MutexAutoLock usage_lock(m_exclusive_access_mutex);
955 resend_timeout = timeout;
958 bool UDPPeer::Ping(float dtime,SharedBuffer<u8>& data)
960 m_ping_timer += dtime;
961 if (m_ping_timer >= PING_TIMEOUT)
963 // Create and send PING packet
964 writeU8(&data[0], PACKET_TYPE_CONTROL);
965 writeU8(&data[1], CONTROLTYPE_PING);
972 void UDPPeer::PutReliableSendCommand(ConnectionCommand &c,
973 unsigned int max_packet_size)
975 if (m_pending_disconnect)
978 Channel &chan = channels[c.channelnum];
980 if (chan.queued_commands.empty() &&
981 /* don't queue more packets then window size */
982 (chan.queued_reliables.size() < chan.getWindowSize() / 2)) {
983 LOG(dout_con<<m_connection->getDesc()
984 <<" processing reliable command for peer id: " << c.peer_id
985 <<" data size: " << c.data.getSize() << std::endl);
986 if (!processReliableSendCommand(c,max_packet_size)) {
987 chan.queued_commands.push_back(c);
991 LOG(dout_con<<m_connection->getDesc()
992 <<" Queueing reliable command for peer id: " << c.peer_id
993 <<" data size: " << c.data.getSize() <<std::endl);
994 chan.queued_commands.push_back(c);
995 if (chan.queued_commands.size() >= chan.getWindowSize() / 2) {
996 LOG(derr_con << m_connection->getDesc()
997 << "Possible packet stall to peer id: " << c.peer_id
998 << " queued_commands=" << chan.queued_commands.size()
1004 bool UDPPeer::processReliableSendCommand(
1005 ConnectionCommand &c,
1006 unsigned int max_packet_size)
1008 if (m_pending_disconnect)
1011 Channel &chan = channels[c.channelnum];
1013 u32 chunksize_max = max_packet_size
1015 - RELIABLE_HEADER_SIZE;
1017 sanity_check(c.data.getSize() < MAX_RELIABLE_WINDOW_SIZE*512);
1019 std::list<SharedBuffer<u8>> originals;
1020 u16 split_sequence_number = chan.readNextSplitSeqNum();
1023 originals.emplace_back(c.data);
1025 makeAutoSplitPacket(c.data, chunksize_max,split_sequence_number, &originals);
1026 chan.setNextSplitSeqNum(split_sequence_number);
1029 bool have_sequence_number = true;
1030 bool have_initial_sequence_number = false;
1031 std::queue<BufferedPacket> toadd;
1032 volatile u16 initial_sequence_number = 0;
1034 for (SharedBuffer<u8> &original : originals) {
1035 u16 seqnum = chan.getOutgoingSequenceNumber(have_sequence_number);
1037 /* oops, we don't have enough sequence numbers to send this packet */
1038 if (!have_sequence_number)
1041 if (!have_initial_sequence_number)
1043 initial_sequence_number = seqnum;
1044 have_initial_sequence_number = true;
1047 SharedBuffer<u8> reliable = makeReliablePacket(original, seqnum);
1049 // Add base headers and make a packet
1050 BufferedPacket p = con::makePacket(address, reliable,
1051 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1057 if (have_sequence_number) {
1058 volatile u16 pcount = 0;
1059 while (!toadd.empty()) {
1060 BufferedPacket p = toadd.front();
1062 // LOG(dout_con<<connection->getDesc()
1063 // << " queuing reliable packet for peer_id: " << c.peer_id
1064 // << " channel: " << (c.channelnum&0xFF)
1065 // << " seqnum: " << readU16(&p.data[BASE_HEADER_SIZE+1])
1067 chan.queued_reliables.push(p);
1070 sanity_check(chan.queued_reliables.size() < 0xFFFF);
1074 volatile u16 packets_available = toadd.size();
1075 /* we didn't get a single sequence number no need to fill queue */
1076 if (!have_initial_sequence_number) {
1080 while (!toadd.empty()) {
1084 bool successfully_put_back_sequence_number
1085 = chan.putBackSequenceNumber(
1086 (initial_sequence_number+toadd.size() % (SEQNUM_MAX+1)));
1088 FATAL_ERROR_IF(!successfully_put_back_sequence_number, "error");
1091 // DO NOT REMOVE n_queued! It avoids a deadlock of async locked
1092 // 'log_message_mutex' and 'm_list_mutex'.
1093 u32 n_queued = chan.outgoing_reliables_sent.size();
1095 LOG(dout_con<<m_connection->getDesc()
1096 << " Windowsize exceeded on reliable sending "
1097 << c.data.getSize() << " bytes"
1098 << std::endl << "\t\tinitial_sequence_number: "
1099 << initial_sequence_number
1100 << std::endl << "\t\tgot at most : "
1101 << packets_available << " packets"
1102 << std::endl << "\t\tpackets queued : "
1109 void UDPPeer::RunCommandQueues(
1110 unsigned int max_packet_size,
1111 unsigned int maxcommands,
1112 unsigned int maxtransfer)
1115 for (Channel &channel : channels) {
1116 unsigned int commands_processed = 0;
1118 if ((!channel.queued_commands.empty()) &&
1119 (channel.queued_reliables.size() < maxtransfer) &&
1120 (commands_processed < maxcommands)) {
1122 ConnectionCommand c = channel.queued_commands.front();
1124 LOG(dout_con << m_connection->getDesc()
1125 << " processing queued reliable command " << std::endl);
1127 // Packet is processed, remove it from queue
1128 if (processReliableSendCommand(c,max_packet_size)) {
1129 channel.queued_commands.pop_front();
1131 LOG(dout_con << m_connection->getDesc()
1132 << " Failed to queue packets for peer_id: " << c.peer_id
1133 << ", delaying sending of " << c.data.getSize()
1134 << " bytes" << std::endl);
1137 catch (ItemNotFoundException &e) {
1138 // intentionally empty
1144 u16 UDPPeer::getNextSplitSequenceNumber(u8 channel)
1146 assert(channel < CHANNEL_COUNT); // Pre-condition
1147 return channels[channel].readNextSplitSeqNum();
1150 void UDPPeer::setNextSplitSequenceNumber(u8 channel, u16 seqnum)
1152 assert(channel < CHANNEL_COUNT); // Pre-condition
1153 channels[channel].setNextSplitSeqNum(seqnum);
1156 SharedBuffer<u8> UDPPeer::addSplitPacket(u8 channel, const BufferedPacket &toadd,
1159 assert(channel < CHANNEL_COUNT); // Pre-condition
1160 return channels[channel].incoming_splits.insert(toadd, reliable);
1167 Connection::Connection(u32 protocol_id, u32 max_packet_size, float timeout,
1168 bool ipv6, PeerHandler *peerhandler) :
1170 m_protocol_id(protocol_id),
1171 m_sendThread(new ConnectionSendThread(max_packet_size, timeout)),
1172 m_receiveThread(new ConnectionReceiveThread(max_packet_size)),
1173 m_bc_peerhandler(peerhandler)
1176 /* Amount of time Receive() will wait for data, this is entirely different
1177 * from the connection timeout */
1178 m_udpSocket.setTimeoutMs(500);
1180 m_sendThread->setParent(this);
1181 m_receiveThread->setParent(this);
1183 m_sendThread->start();
1184 m_receiveThread->start();
1188 Connection::~Connection()
1190 m_shutting_down = true;
1191 // request threads to stop
1192 m_sendThread->stop();
1193 m_receiveThread->stop();
1195 //TODO for some unkonwn reason send/receive threads do not exit as they're
1196 // supposed to be but wait on peer timeout. To speed up shutdown we reduce
1197 // timeout to half a second.
1198 m_sendThread->setPeerTimeout(0.5);
1200 // wait for threads to finish
1201 m_sendThread->wait();
1202 m_receiveThread->wait();
1205 for (auto &peer : m_peers) {
1210 /* Internal stuff */
1211 void Connection::putEvent(ConnectionEvent &e)
1213 assert(e.type != CONNEVENT_NONE); // Pre-condition
1214 m_event_queue.push_back(e);
1217 void Connection::TriggerSend()
1219 m_sendThread->Trigger();
1222 PeerHelper Connection::getPeerNoEx(session_t peer_id)
1224 MutexAutoLock peerlock(m_peers_mutex);
1225 std::map<session_t, Peer *>::iterator node = m_peers.find(peer_id);
1227 if (node == m_peers.end()) {
1228 return PeerHelper(NULL);
1232 FATAL_ERROR_IF(node->second->id != peer_id, "Invalid peer id");
1234 return PeerHelper(node->second);
1237 /* find peer_id for address */
1238 u16 Connection::lookupPeer(Address& sender)
1240 MutexAutoLock peerlock(m_peers_mutex);
1241 std::map<u16, Peer*>::iterator j;
1242 j = m_peers.begin();
1243 for(; j != m_peers.end(); ++j)
1245 Peer *peer = j->second;
1246 if (peer->isPendingDeletion())
1251 if ((peer->getAddress(MTP_MINETEST_RELIABLE_UDP, tocheck)) && (tocheck == sender))
1254 if ((peer->getAddress(MTP_UDP, tocheck)) && (tocheck == sender))
1258 return PEER_ID_INEXISTENT;
1261 bool Connection::deletePeer(session_t peer_id, bool timeout)
1265 /* lock list as short as possible */
1267 MutexAutoLock peerlock(m_peers_mutex);
1268 if (m_peers.find(peer_id) == m_peers.end())
1270 peer = m_peers[peer_id];
1271 m_peers.erase(peer_id);
1272 m_peer_ids.remove(peer_id);
1275 Address peer_address;
1276 //any peer has a primary address this never fails!
1277 peer->getAddress(MTP_PRIMARY, peer_address);
1280 e.peerRemoved(peer_id, timeout, peer_address);
1290 ConnectionEvent Connection::waitEvent(u32 timeout_ms)
1293 return m_event_queue.pop_front(timeout_ms);
1294 } catch(ItemNotFoundException &ex) {
1296 e.type = CONNEVENT_NONE;
1301 void Connection::putCommand(ConnectionCommand &c)
1303 if (!m_shutting_down) {
1304 m_command_queue.push_back(c);
1305 m_sendThread->Trigger();
1309 void Connection::Serve(Address bind_addr)
1311 ConnectionCommand c;
1316 void Connection::Connect(Address address)
1318 ConnectionCommand c;
1323 bool Connection::Connected()
1325 MutexAutoLock peerlock(m_peers_mutex);
1327 if (m_peers.size() != 1)
1330 std::map<session_t, Peer *>::iterator node = m_peers.find(PEER_ID_SERVER);
1331 if (node == m_peers.end())
1334 if (m_peer_id == PEER_ID_INEXISTENT)
1340 void Connection::Disconnect()
1342 ConnectionCommand c;
1347 bool Connection::Receive(NetworkPacket *pkt, u32 timeout)
1350 Note that this function can potentially wait infinitely if non-data
1351 events keep happening before the timeout expires.
1352 This is not considered to be a problem (is it?)
1355 ConnectionEvent e = waitEvent(timeout);
1356 if (e.type != CONNEVENT_NONE)
1357 LOG(dout_con << getDesc() << ": Receive: got event: "
1358 << e.describe() << std::endl);
1360 case CONNEVENT_NONE:
1362 case CONNEVENT_DATA_RECEIVED:
1363 // Data size is lesser than command size, ignoring packet
1364 if (e.data.getSize() < 2) {
1368 pkt->putRawPacket(*e.data, e.data.getSize(), e.peer_id);
1370 case CONNEVENT_PEER_ADDED: {
1371 UDPPeer tmp(e.peer_id, e.address, this);
1372 if (m_bc_peerhandler)
1373 m_bc_peerhandler->peerAdded(&tmp);
1376 case CONNEVENT_PEER_REMOVED: {
1377 UDPPeer tmp(e.peer_id, e.address, this);
1378 if (m_bc_peerhandler)
1379 m_bc_peerhandler->deletingPeer(&tmp, e.timeout);
1382 case CONNEVENT_BIND_FAILED:
1383 throw ConnectionBindFailed("Failed to bind socket "
1384 "(port already in use?)");
1390 void Connection::Receive(NetworkPacket *pkt)
1392 bool any = Receive(pkt, m_bc_receive_timeout);
1394 throw NoIncomingDataException("No incoming data");
1397 bool Connection::TryReceive(NetworkPacket *pkt)
1399 return Receive(pkt, 0);
1402 void Connection::Send(session_t peer_id, u8 channelnum,
1403 NetworkPacket *pkt, bool reliable)
1405 assert(channelnum < CHANNEL_COUNT); // Pre-condition
1407 ConnectionCommand c;
1409 c.send(peer_id, channelnum, pkt, reliable);
1413 Address Connection::GetPeerAddress(session_t peer_id)
1415 PeerHelper peer = getPeerNoEx(peer_id);
1418 throw PeerNotFoundException("No address for peer found!");
1419 Address peer_address;
1420 peer->getAddress(MTP_PRIMARY, peer_address);
1421 return peer_address;
1424 float Connection::getPeerStat(session_t peer_id, rtt_stat_type type)
1426 PeerHelper peer = getPeerNoEx(peer_id);
1427 if (!peer) return -1;
1428 return peer->getStat(type);
1431 float Connection::getLocalStat(rate_stat_type type)
1433 PeerHelper peer = getPeerNoEx(PEER_ID_SERVER);
1435 FATAL_ERROR_IF(!peer, "Connection::getLocalStat we couldn't get our own peer? are you serious???");
1439 for (Channel &channel : dynamic_cast<UDPPeer *>(&peer)->channels) {
1442 retval += channel.getCurrentDownloadRateKB();
1445 retval += channel.getAvgDownloadRateKB();
1448 retval += channel.getCurrentIncomingRateKB();
1451 retval += channel.getAvgIncomingRateKB();
1454 retval += channel.getAvgLossRateKB();
1457 retval += channel.getCurrentLossRateKB();
1460 FATAL_ERROR("Connection::getLocalStat Invalid stat type");
1466 u16 Connection::createPeer(Address& sender, MTProtocols protocol, int fd)
1468 // Somebody wants to make a new connection
1470 // Get a unique peer id (2 or higher)
1471 session_t peer_id_new = m_next_remote_peer_id;
1472 u16 overflow = MAX_UDP_PEERS;
1475 Find an unused peer id
1477 MutexAutoLock lock(m_peers_mutex);
1478 bool out_of_ids = false;
1481 if (m_peers.find(peer_id_new) == m_peers.end())
1484 // Check for overflow
1485 if (peer_id_new == overflow) {
1493 errorstream << getDesc() << " ran out of peer ids" << std::endl;
1494 return PEER_ID_INEXISTENT;
1499 peer = new UDPPeer(peer_id_new, sender, this);
1501 m_peers[peer->id] = peer;
1502 m_peer_ids.push_back(peer->id);
1504 m_next_remote_peer_id = (peer_id_new +1 ) % MAX_UDP_PEERS;
1506 LOG(dout_con << getDesc()
1507 << "createPeer(): giving peer_id=" << peer_id_new << std::endl);
1509 ConnectionCommand cmd;
1510 SharedBuffer<u8> reply(4);
1511 writeU8(&reply[0], PACKET_TYPE_CONTROL);
1512 writeU8(&reply[1], CONTROLTYPE_SET_PEER_ID);
1513 writeU16(&reply[2], peer_id_new);
1514 cmd.createPeer(peer_id_new,reply);
1517 // Create peer addition event
1519 e.peerAdded(peer_id_new, sender);
1522 // We're now talking to a valid peer_id
1526 void Connection::PrintInfo(std::ostream &out)
1528 m_info_mutex.lock();
1529 out<<getDesc()<<": ";
1530 m_info_mutex.unlock();
1533 const std::string Connection::getDesc()
1535 return std::string("con(")+
1536 itos(m_udpSocket.GetHandle())+"/"+itos(m_peer_id)+")";
1539 void Connection::DisconnectPeer(session_t peer_id)
1541 ConnectionCommand discon;
1542 discon.disconnect_peer(peer_id);
1546 void Connection::sendAck(session_t peer_id, u8 channelnum, u16 seqnum)
1548 assert(channelnum < CHANNEL_COUNT); // Pre-condition
1550 LOG(dout_con<<getDesc()
1551 <<" Queuing ACK command to peer_id: " << peer_id <<
1552 " channel: " << (channelnum & 0xFF) <<
1553 " seqnum: " << seqnum << std::endl);
1555 ConnectionCommand c;
1556 SharedBuffer<u8> ack(4);
1557 writeU8(&ack[0], PACKET_TYPE_CONTROL);
1558 writeU8(&ack[1], CONTROLTYPE_ACK);
1559 writeU16(&ack[2], seqnum);
1561 c.ack(peer_id, channelnum, ack);
1563 m_sendThread->Trigger();
1566 UDPPeer* Connection::createServerPeer(Address& address)
1568 if (getPeerNoEx(PEER_ID_SERVER) != 0)
1570 throw ConnectionException("Already connected to a server");
1573 UDPPeer *peer = new UDPPeer(PEER_ID_SERVER, address, this);
1576 MutexAutoLock lock(m_peers_mutex);
1577 m_peers[peer->id] = peer;
1578 m_peer_ids.push_back(peer->id);