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, 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(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(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);
172 bool ReliablePacketBuffer::empty()
174 MutexAutoLock listlock(m_list_mutex);
175 return m_list.empty();
178 u32 ReliablePacketBuffer::size()
183 bool ReliablePacketBuffer::containsPacket(u16 seqnum)
185 return !(findPacket(seqnum) == m_list.end());
188 RPBSearchResult ReliablePacketBuffer::findPacket(u16 seqnum)
190 std::list<BufferedPacket>::iterator i = m_list.begin();
191 for(; i != m_list.end(); ++i)
193 u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
194 /*dout_con<<"findPacket(): finding seqnum="<<seqnum
195 <<", comparing to s="<<s<<std::endl;*/
201 RPBSearchResult ReliablePacketBuffer::notFound()
205 bool ReliablePacketBuffer::getFirstSeqnum(u16& result)
207 MutexAutoLock listlock(m_list_mutex);
210 BufferedPacket p = *m_list.begin();
211 result = readU16(&p.data[BASE_HEADER_SIZE+1]);
215 BufferedPacket ReliablePacketBuffer::popFirst()
217 MutexAutoLock listlock(m_list_mutex);
219 throw NotFoundException("Buffer is empty");
220 BufferedPacket p = *m_list.begin();
221 m_list.erase(m_list.begin());
224 if (m_list_size == 0) {
225 m_oldest_non_answered_ack = 0;
227 m_oldest_non_answered_ack =
228 readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]);
232 BufferedPacket ReliablePacketBuffer::popSeqnum(u16 seqnum)
234 MutexAutoLock listlock(m_list_mutex);
235 RPBSearchResult r = findPacket(seqnum);
236 if (r == notFound()) {
237 LOG(dout_con<<"Sequence number: " << seqnum
238 << " not found in reliable buffer"<<std::endl);
239 throw NotFoundException("seqnum not found in buffer");
241 BufferedPacket p = *r;
244 RPBSearchResult next = r;
246 if (next != notFound()) {
247 u16 s = readU16(&(next->data[BASE_HEADER_SIZE+1]));
248 m_oldest_non_answered_ack = s;
254 if (m_list_size == 0)
255 { m_oldest_non_answered_ack = 0; }
257 { m_oldest_non_answered_ack = readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]); }
260 void ReliablePacketBuffer::insert(BufferedPacket &p,u16 next_expected)
262 MutexAutoLock listlock(m_list_mutex);
263 if (p.data.getSize() < BASE_HEADER_SIZE + 3) {
264 errorstream << "ReliablePacketBuffer::insert(): Invalid data size for "
265 "reliable packet" << std::endl;
268 u8 type = readU8(&p.data[BASE_HEADER_SIZE + 0]);
269 if (type != PACKET_TYPE_RELIABLE) {
270 errorstream << "ReliablePacketBuffer::insert(): type is not reliable"
274 u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE + 1]);
276 if (!seqnum_in_window(seqnum, next_expected, MAX_RELIABLE_WINDOW_SIZE)) {
277 errorstream << "ReliablePacketBuffer::insert(): seqnum is outside of "
278 "expected window " << std::endl;
281 if (seqnum == next_expected) {
282 errorstream << "ReliablePacketBuffer::insert(): seqnum is next expected"
288 sanity_check(m_list_size <= SEQNUM_MAX+1); // FIXME: Handle the error?
290 // Find the right place for the packet and insert it there
291 // If list is empty, just add it
295 m_oldest_non_answered_ack = seqnum;
300 // Otherwise find the right place
301 std::list<BufferedPacket>::iterator i = m_list.begin();
302 // Find the first packet in the list which has a higher seqnum
303 u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
305 /* case seqnum is smaller then next_expected seqnum */
306 /* this is true e.g. on wrap around */
307 if (seqnum < next_expected) {
308 while(((s < seqnum) || (s >= next_expected)) && (i != m_list.end())) {
310 if (i != m_list.end())
311 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
314 /* non wrap around case (at least for incoming and next_expected */
317 while(((s < seqnum) && (s >= next_expected)) && (i != m_list.end())) {
319 if (i != m_list.end())
320 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
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 /* nothing to do this seems to be a resent packet */
345 /* for paranoia reason data should be compared */
348 /* insert or push back */
349 else if (i != m_list.end()) {
356 /* update last packet number */
357 m_oldest_non_answered_ack = readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]);
360 void ReliablePacketBuffer::incrementTimeouts(float dtime)
362 MutexAutoLock listlock(m_list_mutex);
363 for (BufferedPacket &bufferedPacket : m_list) {
364 bufferedPacket.time += dtime;
365 bufferedPacket.totaltime += dtime;
369 std::list<BufferedPacket> ReliablePacketBuffer::getTimedOuts(float timeout,
370 unsigned int max_packets)
372 MutexAutoLock listlock(m_list_mutex);
373 std::list<BufferedPacket> timed_outs;
374 for (BufferedPacket &bufferedPacket : m_list) {
375 if (bufferedPacket.time >= timeout) {
376 timed_outs.push_back(bufferedPacket);
378 //this packet will be sent right afterwards reset timeout here
379 bufferedPacket.time = 0.0f;
380 if (timed_outs.size() >= max_packets)
391 IncomingSplitBuffer::~IncomingSplitBuffer()
393 MutexAutoLock listlock(m_map_mutex);
394 for (auto &i : m_buf) {
399 This will throw a GotSplitPacketException when a full
400 split packet is constructed.
402 SharedBuffer<u8> IncomingSplitBuffer::insert(const BufferedPacket &p, bool reliable)
404 MutexAutoLock listlock(m_map_mutex);
405 u32 headersize = BASE_HEADER_SIZE + 7;
406 if (p.data.getSize() < headersize) {
407 errorstream << "Invalid data size for split packet" << std::endl;
408 return SharedBuffer<u8>();
410 u8 type = readU8(&p.data[BASE_HEADER_SIZE+0]);
411 u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]);
412 u16 chunk_count = readU16(&p.data[BASE_HEADER_SIZE+3]);
413 u16 chunk_num = readU16(&p.data[BASE_HEADER_SIZE+5]);
415 if (type != PACKET_TYPE_SPLIT) {
416 errorstream << "IncomingSplitBuffer::insert(): type is not split"
418 return SharedBuffer<u8>();
421 // Add if doesn't exist
422 if (m_buf.find(seqnum) == m_buf.end()) {
423 m_buf[seqnum] = new IncomingSplitPacket(chunk_count, reliable);
426 IncomingSplitPacket *sp = m_buf[seqnum];
428 if (chunk_count != sp->chunk_count)
429 LOG(derr_con<<"Connection: WARNING: chunk_count="<<chunk_count
430 <<" != sp->chunk_count="<<sp->chunk_count
432 if (reliable != sp->reliable)
433 LOG(derr_con<<"Connection: WARNING: reliable="<<reliable
434 <<" != sp->reliable="<<sp->reliable
437 // If chunk already exists, ignore it.
438 // Sometimes two identical packets may arrive when there is network
439 // lag and the server re-sends stuff.
440 if (sp->chunks.find(chunk_num) != sp->chunks.end())
441 return SharedBuffer<u8>();
443 // Cut chunk data out of packet
444 u32 chunkdatasize = p.data.getSize() - headersize;
445 SharedBuffer<u8> chunkdata(chunkdatasize);
446 memcpy(*chunkdata, &(p.data[headersize]), chunkdatasize);
448 // Set chunk data in buffer
449 sp->chunks[chunk_num] = chunkdata;
451 // If not all chunks are received, return empty buffer
452 if (!sp->allReceived())
453 return SharedBuffer<u8>();
455 // Calculate total size
457 for (const auto &chunk : sp->chunks) {
458 totalsize += chunk.second.getSize();
461 SharedBuffer<u8> fulldata(totalsize);
463 // Copy chunks to data buffer
465 for (u32 chunk_i=0; chunk_i<sp->chunk_count; chunk_i++) {
466 const SharedBuffer<u8> &buf = sp->chunks[chunk_i];
467 u16 buf_chunkdatasize = buf.getSize();
468 memcpy(&fulldata[start], *buf, buf_chunkdatasize);
469 start += buf_chunkdatasize;
472 // Remove sp from buffer
478 void IncomingSplitBuffer::removeUnreliableTimedOuts(float dtime, float timeout)
480 std::deque<u16> remove_queue;
482 MutexAutoLock listlock(m_map_mutex);
483 for (auto &i : m_buf) {
484 IncomingSplitPacket *p = i.second;
485 // Reliable ones are not removed by timeout
489 if (p->time >= timeout)
490 remove_queue.push_back(i.first);
493 for (u16 j : remove_queue) {
494 MutexAutoLock listlock(m_map_mutex);
495 LOG(dout_con<<"NOTE: Removing timed out unreliable split packet"<<std::endl);
505 void ConnectionCommand::send(session_t peer_id_, u8 channelnum_, NetworkPacket *pkt,
510 channelnum = channelnum_;
511 data = pkt->oldForgePacket();
512 reliable = reliable_;
519 u16 Channel::readNextIncomingSeqNum()
521 MutexAutoLock internal(m_internal_mutex);
522 return next_incoming_seqnum;
525 u16 Channel::incNextIncomingSeqNum()
527 MutexAutoLock internal(m_internal_mutex);
528 u16 retval = next_incoming_seqnum;
529 next_incoming_seqnum++;
533 u16 Channel::readNextSplitSeqNum()
535 MutexAutoLock internal(m_internal_mutex);
536 return next_outgoing_split_seqnum;
538 void Channel::setNextSplitSeqNum(u16 seqnum)
540 MutexAutoLock internal(m_internal_mutex);
541 next_outgoing_split_seqnum = seqnum;
544 u16 Channel::getOutgoingSequenceNumber(bool& successful)
546 MutexAutoLock internal(m_internal_mutex);
547 u16 retval = next_outgoing_seqnum;
548 u16 lowest_unacked_seqnumber;
550 /* shortcut if there ain't any packet in outgoing list */
551 if (outgoing_reliables_sent.empty())
553 next_outgoing_seqnum++;
557 if (outgoing_reliables_sent.getFirstSeqnum(lowest_unacked_seqnumber))
559 if (lowest_unacked_seqnumber < next_outgoing_seqnum) {
560 // ugly cast but this one is required in order to tell compiler we
561 // know about difference of two unsigned may be negative in general
562 // but we already made sure it won't happen in this case
563 if (((u16)(next_outgoing_seqnum - lowest_unacked_seqnumber)) > window_size) {
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 ((next_outgoing_seqnum + (u16)(SEQNUM_MAX - lowest_unacked_seqnumber)) >
580 next_outgoing_seqnum++;
584 u16 Channel::readOutgoingSequenceNumber()
586 MutexAutoLock internal(m_internal_mutex);
587 return next_outgoing_seqnum;
590 bool Channel::putBackSequenceNumber(u16 seqnum)
592 if (((seqnum + 1) % (SEQNUM_MAX+1)) == next_outgoing_seqnum) {
594 next_outgoing_seqnum = seqnum;
600 void Channel::UpdateBytesSent(unsigned int bytes, unsigned int packets)
602 MutexAutoLock internal(m_internal_mutex);
603 current_bytes_transfered += bytes;
604 current_packet_successful += packets;
607 void Channel::UpdateBytesReceived(unsigned int bytes) {
608 MutexAutoLock internal(m_internal_mutex);
609 current_bytes_received += bytes;
612 void Channel::UpdateBytesLost(unsigned int bytes)
614 MutexAutoLock internal(m_internal_mutex);
615 current_bytes_lost += bytes;
619 void Channel::UpdatePacketLossCounter(unsigned int count)
621 MutexAutoLock internal(m_internal_mutex);
622 current_packet_loss += count;
625 void Channel::UpdatePacketTooLateCounter()
627 MutexAutoLock internal(m_internal_mutex);
628 current_packet_too_late++;
631 void Channel::UpdateTimers(float dtime)
633 bpm_counter += dtime;
634 packet_loss_counter += dtime;
636 if (packet_loss_counter > 1.0f) {
637 packet_loss_counter -= 1.0f;
639 unsigned int packet_loss = 11; /* use a neutral value for initialization */
640 unsigned int packets_successful = 0;
641 //unsigned int packet_too_late = 0;
643 bool reasonable_amount_of_data_transmitted = false;
646 MutexAutoLock internal(m_internal_mutex);
647 packet_loss = current_packet_loss;
648 //packet_too_late = current_packet_too_late;
649 packets_successful = current_packet_successful;
651 if (current_bytes_transfered > (unsigned int) (window_size*512/2)) {
652 reasonable_amount_of_data_transmitted = true;
654 current_packet_loss = 0;
655 current_packet_too_late = 0;
656 current_packet_successful = 0;
659 /* dynamic window size */
660 float successful_to_lost_ratio = 0.0f;
663 if (packets_successful > 0) {
664 successful_to_lost_ratio = packet_loss/packets_successful;
665 } else if (packet_loss > 0) {
666 window_size = std::max(
668 MIN_RELIABLE_WINDOW_SIZE);
673 if ((successful_to_lost_ratio < 0.01f) &&
674 (window_size < MAX_RELIABLE_WINDOW_SIZE)) {
675 /* don't even think about increasing if we didn't even
676 * use major parts of our window */
677 if (reasonable_amount_of_data_transmitted)
678 window_size = std::min(
680 MAX_RELIABLE_WINDOW_SIZE);
681 } else if ((successful_to_lost_ratio < 0.05f) &&
682 (window_size < MAX_RELIABLE_WINDOW_SIZE)) {
683 /* don't even think about increasing if we didn't even
684 * use major parts of our window */
685 if (reasonable_amount_of_data_transmitted)
686 window_size = std::min(
688 MAX_RELIABLE_WINDOW_SIZE);
689 } else if (successful_to_lost_ratio > 0.15f) {
690 window_size = std::max(
692 MIN_RELIABLE_WINDOW_SIZE);
693 } else if (successful_to_lost_ratio > 0.1f) {
694 window_size = std::max(
696 MIN_RELIABLE_WINDOW_SIZE);
701 if (bpm_counter > 10.0f) {
703 MutexAutoLock internal(m_internal_mutex);
705 (((float) current_bytes_transfered)/bpm_counter)/1024.0f;
706 current_bytes_transfered = 0;
708 (((float) current_bytes_lost)/bpm_counter)/1024.0f;
709 current_bytes_lost = 0;
711 (((float) current_bytes_received)/bpm_counter)/1024.0f;
712 current_bytes_received = 0;
716 if (cur_kbps > max_kbps) {
720 if (cur_kbps_lost > max_kbps_lost) {
721 max_kbps_lost = cur_kbps_lost;
724 if (cur_incoming_kbps > max_incoming_kbps) {
725 max_incoming_kbps = cur_incoming_kbps;
728 rate_samples = MYMIN(rate_samples+1,10);
729 float old_fraction = ((float) (rate_samples-1) )/( (float) rate_samples);
730 avg_kbps = avg_kbps * old_fraction +
731 cur_kbps * (1.0 - old_fraction);
732 avg_kbps_lost = avg_kbps_lost * old_fraction +
733 cur_kbps_lost * (1.0 - old_fraction);
734 avg_incoming_kbps = avg_incoming_kbps * old_fraction +
735 cur_incoming_kbps * (1.0 - old_fraction);
744 PeerHelper::PeerHelper(Peer* peer) :
747 if (peer && !peer->IncUseCount())
751 PeerHelper::~PeerHelper()
754 m_peer->DecUseCount();
759 PeerHelper& PeerHelper::operator=(Peer* peer)
762 if (peer && !peer->IncUseCount())
767 Peer* PeerHelper::operator->() const
772 Peer* PeerHelper::operator&() const
777 bool PeerHelper::operator!()
782 bool PeerHelper::operator!=(void* ptr)
784 return ((void*) m_peer != ptr);
787 bool Peer::IncUseCount()
789 MutexAutoLock lock(m_exclusive_access_mutex);
791 if (!m_pending_deletion) {
799 void Peer::DecUseCount()
802 MutexAutoLock lock(m_exclusive_access_mutex);
803 sanity_check(m_usage > 0);
806 if (!((m_pending_deletion) && (m_usage == 0)))
812 void Peer::RTTStatistics(float rtt, const std::string &profiler_id)
814 static const float avg_factor = 100.0f / MAX_RELIABLE_WINDOW_SIZE;
816 if (m_last_rtt > 0) {
817 /* set min max values */
818 if (rtt < m_rtt.min_rtt)
820 if (rtt >= m_rtt.max_rtt)
823 /* do average calculation */
824 if (m_rtt.avg_rtt < 0.0)
827 m_rtt.avg_rtt += (rtt - m_rtt.avg_rtt) * avg_factor;
829 /* do jitter calculation */
831 //just use some neutral value at beginning
832 float jitter = std::fabs(rtt - m_last_rtt);
834 if (jitter < m_rtt.jitter_min)
835 m_rtt.jitter_min = jitter;
836 if (jitter >= m_rtt.jitter_max)
837 m_rtt.jitter_max = jitter;
839 if (m_rtt.jitter_avg < 0.0)
840 m_rtt.jitter_avg = jitter;
842 m_rtt.jitter_avg += (jitter - m_rtt.jitter_avg) * avg_factor;
844 if (!profiler_id.empty()) {
845 g_profiler->graphAdd(profiler_id + "_rtt", rtt);
846 g_profiler->graphAdd(profiler_id + "_jitter", jitter);
849 /* save values required for next loop */
853 bool Peer::isTimedOut(float timeout)
855 MutexAutoLock lock(m_exclusive_access_mutex);
856 u64 current_time = porting::getTimeMs();
858 float dtime = CALC_DTIME(m_last_timeout_check,current_time);
859 m_last_timeout_check = current_time;
861 m_timeout_counter += dtime;
863 return m_timeout_counter > timeout;
869 MutexAutoLock usage_lock(m_exclusive_access_mutex);
870 m_pending_deletion = true;
875 PROFILE(std::stringstream peerIdentifier1);
876 PROFILE(peerIdentifier1 << "runTimeouts[" << m_connection->getDesc()
877 << ";" << id << ";RELIABLE]");
878 PROFILE(g_profiler->remove(peerIdentifier1.str()));
879 PROFILE(std::stringstream peerIdentifier2);
880 PROFILE(peerIdentifier2 << "sendPackets[" << m_connection->getDesc()
881 << ";" << id << ";RELIABLE]");
882 PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier2.str(), SPT_AVG));
887 UDPPeer::UDPPeer(u16 a_id, Address a_address, Connection* connection) :
888 Peer(a_address,a_id,connection)
890 for (Channel &channel : channels)
891 channel.setWindowSize(g_settings->getU16("max_packets_per_iteration"));
894 bool UDPPeer::getAddress(MTProtocols type,Address& toset)
896 if ((type == MTP_UDP) || (type == MTP_MINETEST_RELIABLE_UDP) || (type == MTP_PRIMARY))
905 void UDPPeer::reportRTT(float rtt)
909 RTTStatistics(rtt, "rudp");
911 float timeout = getStat(AVG_RTT) * RESEND_TIMEOUT_FACTOR;
912 timeout = rangelim(timeout, RESEND_TIMEOUT_MIN, RESEND_TIMEOUT_MAX);
914 MutexAutoLock usage_lock(m_exclusive_access_mutex);
915 resend_timeout = timeout;
918 bool UDPPeer::Ping(float dtime,SharedBuffer<u8>& data)
920 m_ping_timer += dtime;
921 if (m_ping_timer >= PING_TIMEOUT)
923 // Create and send PING packet
924 writeU8(&data[0], PACKET_TYPE_CONTROL);
925 writeU8(&data[1], CONTROLTYPE_PING);
932 void UDPPeer::PutReliableSendCommand(ConnectionCommand &c,
933 unsigned int max_packet_size)
935 if (m_pending_disconnect)
938 if ( channels[c.channelnum].queued_commands.empty() &&
939 /* don't queue more packets then window size */
940 (channels[c.channelnum].queued_reliables.size()
941 < (channels[c.channelnum].getWindowSize()/2))) {
942 LOG(dout_con<<m_connection->getDesc()
943 <<" processing reliable command for peer id: " << c.peer_id
944 <<" data size: " << c.data.getSize() << std::endl);
945 if (!processReliableSendCommand(c,max_packet_size)) {
946 channels[c.channelnum].queued_commands.push_back(c);
950 LOG(dout_con<<m_connection->getDesc()
951 <<" Queueing reliable command for peer id: " << c.peer_id
952 <<" data size: " << c.data.getSize() <<std::endl);
953 channels[c.channelnum].queued_commands.push_back(c);
957 bool UDPPeer::processReliableSendCommand(
958 ConnectionCommand &c,
959 unsigned int max_packet_size)
961 if (m_pending_disconnect)
964 u32 chunksize_max = max_packet_size
966 - RELIABLE_HEADER_SIZE;
968 sanity_check(c.data.getSize() < MAX_RELIABLE_WINDOW_SIZE*512);
970 std::list<SharedBuffer<u8>> originals;
971 u16 split_sequence_number = channels[c.channelnum].readNextSplitSeqNum();
974 originals.emplace_back(c.data);
976 makeAutoSplitPacket(c.data, chunksize_max,split_sequence_number, &originals);
977 channels[c.channelnum].setNextSplitSeqNum(split_sequence_number);
980 bool have_sequence_number = true;
981 bool have_initial_sequence_number = false;
982 std::queue<BufferedPacket> toadd;
983 volatile u16 initial_sequence_number = 0;
985 for (SharedBuffer<u8> &original : originals) {
986 u16 seqnum = channels[c.channelnum].getOutgoingSequenceNumber(have_sequence_number);
988 /* oops, we don't have enough sequence numbers to send this packet */
989 if (!have_sequence_number)
992 if (!have_initial_sequence_number)
994 initial_sequence_number = seqnum;
995 have_initial_sequence_number = true;
998 SharedBuffer<u8> reliable = makeReliablePacket(original, seqnum);
1000 // Add base headers and make a packet
1001 BufferedPacket p = con::makePacket(address, reliable,
1002 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1008 if (have_sequence_number) {
1009 volatile u16 pcount = 0;
1010 while (!toadd.empty()) {
1011 BufferedPacket p = toadd.front();
1013 // LOG(dout_con<<connection->getDesc()
1014 // << " queuing reliable packet for peer_id: " << c.peer_id
1015 // << " channel: " << (c.channelnum&0xFF)
1016 // << " seqnum: " << readU16(&p.data[BASE_HEADER_SIZE+1])
1018 channels[c.channelnum].queued_reliables.push(p);
1021 sanity_check(channels[c.channelnum].queued_reliables.size() < 0xFFFF);
1025 volatile u16 packets_available = toadd.size();
1026 /* we didn't get a single sequence number no need to fill queue */
1027 if (!have_initial_sequence_number) {
1031 while (!toadd.empty()) {
1035 bool successfully_put_back_sequence_number
1036 = channels[c.channelnum].putBackSequenceNumber(
1037 (initial_sequence_number+toadd.size() % (SEQNUM_MAX+1)));
1039 FATAL_ERROR_IF(!successfully_put_back_sequence_number, "error");
1042 LOG(dout_con<<m_connection->getDesc()
1043 << " Windowsize exceeded on reliable sending "
1044 << c.data.getSize() << " bytes"
1045 << std::endl << "\t\tinitial_sequence_number: "
1046 << initial_sequence_number
1047 << std::endl << "\t\tgot at most : "
1048 << packets_available << " packets"
1049 << std::endl << "\t\tpackets queued : "
1050 << channels[c.channelnum].outgoing_reliables_sent.size()
1056 void UDPPeer::RunCommandQueues(
1057 unsigned int max_packet_size,
1058 unsigned int maxcommands,
1059 unsigned int maxtransfer)
1062 for (Channel &channel : channels) {
1063 unsigned int commands_processed = 0;
1065 if ((!channel.queued_commands.empty()) &&
1066 (channel.queued_reliables.size() < maxtransfer) &&
1067 (commands_processed < maxcommands)) {
1069 ConnectionCommand c = channel.queued_commands.front();
1071 LOG(dout_con << m_connection->getDesc()
1072 << " processing queued reliable command " << std::endl);
1074 // Packet is processed, remove it from queue
1075 if (processReliableSendCommand(c,max_packet_size)) {
1076 channel.queued_commands.pop_front();
1078 LOG(dout_con << m_connection->getDesc()
1079 << " Failed to queue packets for peer_id: " << c.peer_id
1080 << ", delaying sending of " << c.data.getSize()
1081 << " bytes" << std::endl);
1084 catch (ItemNotFoundException &e) {
1085 // intentionally empty
1091 u16 UDPPeer::getNextSplitSequenceNumber(u8 channel)
1093 assert(channel < CHANNEL_COUNT); // Pre-condition
1094 return channels[channel].readNextSplitSeqNum();
1097 void UDPPeer::setNextSplitSequenceNumber(u8 channel, u16 seqnum)
1099 assert(channel < CHANNEL_COUNT); // Pre-condition
1100 channels[channel].setNextSplitSeqNum(seqnum);
1103 SharedBuffer<u8> UDPPeer::addSplitPacket(u8 channel, const BufferedPacket &toadd,
1106 assert(channel < CHANNEL_COUNT); // Pre-condition
1107 return channels[channel].incoming_splits.insert(toadd, reliable);
1114 Connection::Connection(u32 protocol_id, u32 max_packet_size, float timeout,
1115 bool ipv6, PeerHandler *peerhandler) :
1117 m_protocol_id(protocol_id),
1118 m_sendThread(new ConnectionSendThread(max_packet_size, timeout)),
1119 m_receiveThread(new ConnectionReceiveThread(max_packet_size)),
1120 m_bc_peerhandler(peerhandler)
1123 m_udpSocket.setTimeoutMs(5);
1125 m_sendThread->setParent(this);
1126 m_receiveThread->setParent(this);
1128 m_sendThread->start();
1129 m_receiveThread->start();
1133 Connection::~Connection()
1135 m_shutting_down = true;
1136 // request threads to stop
1137 m_sendThread->stop();
1138 m_receiveThread->stop();
1140 //TODO for some unkonwn reason send/receive threads do not exit as they're
1141 // supposed to be but wait on peer timeout. To speed up shutdown we reduce
1142 // timeout to half a second.
1143 m_sendThread->setPeerTimeout(0.5);
1145 // wait for threads to finish
1146 m_sendThread->wait();
1147 m_receiveThread->wait();
1150 for (auto &peer : m_peers) {
1155 /* Internal stuff */
1156 void Connection::putEvent(ConnectionEvent &e)
1158 assert(e.type != CONNEVENT_NONE); // Pre-condition
1159 m_event_queue.push_back(e);
1162 void Connection::TriggerSend()
1164 m_sendThread->Trigger();
1167 PeerHelper Connection::getPeerNoEx(session_t peer_id)
1169 MutexAutoLock peerlock(m_peers_mutex);
1170 std::map<session_t, Peer *>::iterator node = m_peers.find(peer_id);
1172 if (node == m_peers.end()) {
1173 return PeerHelper(NULL);
1177 FATAL_ERROR_IF(node->second->id != peer_id, "Invalid peer id");
1179 return PeerHelper(node->second);
1182 /* find peer_id for address */
1183 u16 Connection::lookupPeer(Address& sender)
1185 MutexAutoLock peerlock(m_peers_mutex);
1186 std::map<u16, Peer*>::iterator j;
1187 j = m_peers.begin();
1188 for(; j != m_peers.end(); ++j)
1190 Peer *peer = j->second;
1191 if (peer->isPendingDeletion())
1196 if ((peer->getAddress(MTP_MINETEST_RELIABLE_UDP, tocheck)) && (tocheck == sender))
1199 if ((peer->getAddress(MTP_UDP, tocheck)) && (tocheck == sender))
1203 return PEER_ID_INEXISTENT;
1206 bool Connection::deletePeer(session_t peer_id, bool timeout)
1210 /* lock list as short as possible */
1212 MutexAutoLock peerlock(m_peers_mutex);
1213 if (m_peers.find(peer_id) == m_peers.end())
1215 peer = m_peers[peer_id];
1216 m_peers.erase(peer_id);
1217 m_peer_ids.remove(peer_id);
1220 Address peer_address;
1221 //any peer has a primary address this never fails!
1222 peer->getAddress(MTP_PRIMARY, peer_address);
1225 e.peerRemoved(peer_id, timeout, peer_address);
1235 ConnectionEvent Connection::waitEvent(u32 timeout_ms)
1238 return m_event_queue.pop_front(timeout_ms);
1239 } catch(ItemNotFoundException &ex) {
1241 e.type = CONNEVENT_NONE;
1246 void Connection::putCommand(ConnectionCommand &c)
1248 if (!m_shutting_down) {
1249 m_command_queue.push_back(c);
1250 m_sendThread->Trigger();
1254 void Connection::Serve(Address bind_addr)
1256 ConnectionCommand c;
1261 void Connection::Connect(Address address)
1263 ConnectionCommand c;
1268 bool Connection::Connected()
1270 MutexAutoLock peerlock(m_peers_mutex);
1272 if (m_peers.size() != 1)
1275 std::map<session_t, Peer *>::iterator node = m_peers.find(PEER_ID_SERVER);
1276 if (node == m_peers.end())
1279 if (m_peer_id == PEER_ID_INEXISTENT)
1285 void Connection::Disconnect()
1287 ConnectionCommand c;
1292 void Connection::Receive(NetworkPacket* pkt)
1295 ConnectionEvent e = waitEvent(m_bc_receive_timeout);
1296 if (e.type != CONNEVENT_NONE)
1297 LOG(dout_con << getDesc() << ": Receive: got event: "
1298 << e.describe() << std::endl);
1300 case CONNEVENT_NONE:
1301 throw NoIncomingDataException("No incoming data");
1302 case CONNEVENT_DATA_RECEIVED:
1303 // Data size is lesser than command size, ignoring packet
1304 if (e.data.getSize() < 2) {
1308 pkt->putRawPacket(*e.data, e.data.getSize(), e.peer_id);
1310 case CONNEVENT_PEER_ADDED: {
1311 UDPPeer tmp(e.peer_id, e.address, this);
1312 if (m_bc_peerhandler)
1313 m_bc_peerhandler->peerAdded(&tmp);
1316 case CONNEVENT_PEER_REMOVED: {
1317 UDPPeer tmp(e.peer_id, e.address, this);
1318 if (m_bc_peerhandler)
1319 m_bc_peerhandler->deletingPeer(&tmp, e.timeout);
1322 case CONNEVENT_BIND_FAILED:
1323 throw ConnectionBindFailed("Failed to bind socket "
1324 "(port already in use?)");
1327 throw NoIncomingDataException("No incoming data");
1330 void Connection::Send(session_t peer_id, u8 channelnum,
1331 NetworkPacket *pkt, bool reliable)
1333 assert(channelnum < CHANNEL_COUNT); // Pre-condition
1335 ConnectionCommand c;
1337 c.send(peer_id, channelnum, pkt, reliable);
1341 Address Connection::GetPeerAddress(session_t peer_id)
1343 PeerHelper peer = getPeerNoEx(peer_id);
1346 throw PeerNotFoundException("No address for peer found!");
1347 Address peer_address;
1348 peer->getAddress(MTP_PRIMARY, peer_address);
1349 return peer_address;
1352 float Connection::getPeerStat(session_t peer_id, rtt_stat_type type)
1354 PeerHelper peer = getPeerNoEx(peer_id);
1355 if (!peer) return -1;
1356 return peer->getStat(type);
1359 float Connection::getLocalStat(rate_stat_type type)
1361 PeerHelper peer = getPeerNoEx(PEER_ID_SERVER);
1363 FATAL_ERROR_IF(!peer, "Connection::getLocalStat we couldn't get our own peer? are you serious???");
1367 for (Channel &channel : dynamic_cast<UDPPeer *>(&peer)->channels) {
1370 retval += channel.getCurrentDownloadRateKB();
1373 retval += channel.getAvgDownloadRateKB();
1376 retval += channel.getCurrentIncomingRateKB();
1379 retval += channel.getAvgIncomingRateKB();
1382 retval += channel.getAvgLossRateKB();
1385 retval += channel.getCurrentLossRateKB();
1388 FATAL_ERROR("Connection::getLocalStat Invalid stat type");
1394 u16 Connection::createPeer(Address& sender, MTProtocols protocol, int fd)
1396 // Somebody wants to make a new connection
1398 // Get a unique peer id (2 or higher)
1399 session_t peer_id_new = m_next_remote_peer_id;
1400 u16 overflow = MAX_UDP_PEERS;
1403 Find an unused peer id
1405 MutexAutoLock lock(m_peers_mutex);
1406 bool out_of_ids = false;
1409 if (m_peers.find(peer_id_new) == m_peers.end())
1412 // Check for overflow
1413 if (peer_id_new == overflow) {
1421 errorstream << getDesc() << " ran out of peer ids" << std::endl;
1422 return PEER_ID_INEXISTENT;
1427 peer = new UDPPeer(peer_id_new, sender, this);
1429 m_peers[peer->id] = peer;
1430 m_peer_ids.push_back(peer->id);
1432 m_next_remote_peer_id = (peer_id_new +1 ) % MAX_UDP_PEERS;
1434 LOG(dout_con << getDesc()
1435 << "createPeer(): giving peer_id=" << peer_id_new << std::endl);
1437 ConnectionCommand cmd;
1438 SharedBuffer<u8> reply(4);
1439 writeU8(&reply[0], PACKET_TYPE_CONTROL);
1440 writeU8(&reply[1], CONTROLTYPE_SET_PEER_ID);
1441 writeU16(&reply[2], peer_id_new);
1442 cmd.createPeer(peer_id_new,reply);
1445 // Create peer addition event
1447 e.peerAdded(peer_id_new, sender);
1450 // We're now talking to a valid peer_id
1454 void Connection::PrintInfo(std::ostream &out)
1456 m_info_mutex.lock();
1457 out<<getDesc()<<": ";
1458 m_info_mutex.unlock();
1461 const std::string Connection::getDesc()
1463 return std::string("con(")+
1464 itos(m_udpSocket.GetHandle())+"/"+itos(m_peer_id)+")";
1467 void Connection::DisconnectPeer(session_t peer_id)
1469 ConnectionCommand discon;
1470 discon.disconnect_peer(peer_id);
1474 void Connection::sendAck(session_t peer_id, u8 channelnum, u16 seqnum)
1476 assert(channelnum < CHANNEL_COUNT); // Pre-condition
1478 LOG(dout_con<<getDesc()
1479 <<" Queuing ACK command to peer_id: " << peer_id <<
1480 " channel: " << (channelnum & 0xFF) <<
1481 " seqnum: " << seqnum << std::endl);
1483 ConnectionCommand c;
1484 SharedBuffer<u8> ack(4);
1485 writeU8(&ack[0], PACKET_TYPE_CONTROL);
1486 writeU8(&ack[1], CONTROLTYPE_ACK);
1487 writeU16(&ack[2], seqnum);
1489 c.ack(peer_id, channelnum, ack);
1491 m_sendThread->Trigger();
1494 UDPPeer* Connection::createServerPeer(Address& address)
1496 if (getPeerNoEx(PEER_ID_SERVER) != 0)
1498 throw ConnectionException("Already connected to a server");
1501 UDPPeer *peer = new UDPPeer(PEER_ID_SERVER, address, this);
1504 MutexAutoLock lock(m_peers_mutex);
1505 m_peers[peer->id] = peer;
1506 m_peer_ids.push_back(peer->id);