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.
23 #include "connection.h"
24 #include "serialization.h"
27 #include "network/connectionthreads.h"
28 #include "network/networkpacket.h"
29 #include "network/peerhandler.h"
30 #include "util/serialize.h"
31 #include "util/numeric.h"
32 #include "util/string.h"
39 /******************************************************************************/
40 /* defines used for debugging and profiling */
41 /******************************************************************************/
46 /* this mutex is used to achieve log message consistency */
47 std::mutex log_message_mutex;
50 MutexAutoLock loglock(log_message_mutex); \
56 #define PING_TIMEOUT 5.0
58 BufferedPacket makePacket(Address &address, const SharedBuffer<u8> &data,
59 u32 protocol_id, u16 sender_peer_id, u8 channel)
61 u32 packet_size = data.getSize() + BASE_HEADER_SIZE;
62 BufferedPacket p(packet_size);
65 writeU32(&p.data[0], protocol_id);
66 writeU16(&p.data[4], sender_peer_id);
67 writeU8(&p.data[6], channel);
69 memcpy(&p.data[BASE_HEADER_SIZE], *data, data.getSize());
74 SharedBuffer<u8> makeOriginalPacket(const SharedBuffer<u8> &data)
77 u32 packet_size = data.getSize() + header_size;
78 SharedBuffer<u8> b(packet_size);
80 writeU8(&(b[0]), PACKET_TYPE_ORIGINAL);
81 if (data.getSize() > 0) {
82 memcpy(&(b[header_size]), *data, data.getSize());
87 // Split data in chunks and add TYPE_SPLIT headers to them
88 void makeSplitPacket(const SharedBuffer<u8> &data, u32 chunksize_max, u16 seqnum,
89 std::list<SharedBuffer<u8>> *chunks)
91 // Chunk packets, containing the TYPE_SPLIT header
92 u32 chunk_header_size = 7;
93 u32 maximum_data_size = chunksize_max - chunk_header_size;
99 end = start + maximum_data_size - 1;
100 if (end > data.getSize() - 1)
101 end = data.getSize() - 1;
103 u32 payload_size = end - start + 1;
104 u32 packet_size = chunk_header_size + payload_size;
106 SharedBuffer<u8> chunk(packet_size);
108 writeU8(&chunk[0], PACKET_TYPE_SPLIT);
109 writeU16(&chunk[1], seqnum);
110 // [3] u16 chunk_count is written at next stage
111 writeU16(&chunk[5], chunk_num);
112 memcpy(&chunk[chunk_header_size], &data[start], payload_size);
114 chunks->push_back(chunk);
120 while (end != data.getSize() - 1);
122 for (SharedBuffer<u8> &chunk : *chunks) {
124 writeU16(&(chunk[3]), chunk_count);
128 void makeAutoSplitPacket(const SharedBuffer<u8> &data, u32 chunksize_max,
129 u16 &split_seqnum, std::list<SharedBuffer<u8>> *list)
131 u32 original_header_size = 1;
133 if (data.getSize() + original_header_size > chunksize_max) {
134 makeSplitPacket(data, chunksize_max, split_seqnum, list);
139 list->push_back(makeOriginalPacket(data));
142 SharedBuffer<u8> makeReliablePacket(
143 const SharedBuffer<u8> &data,
147 u32 packet_size = data.getSize() + header_size;
148 SharedBuffer<u8> b(packet_size);
150 writeU8(&b[0], PACKET_TYPE_RELIABLE);
151 writeU16(&b[1], seqnum);
153 memcpy(&b[header_size], *data, data.getSize());
162 void ReliablePacketBuffer::print()
164 MutexAutoLock listlock(m_list_mutex);
165 LOG(dout_con<<"Dump of ReliablePacketBuffer:" << std::endl);
166 unsigned int index = 0;
167 for (BufferedPacket &bufferedPacket : m_list) {
168 u16 s = readU16(&(bufferedPacket.data[BASE_HEADER_SIZE+1]));
169 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()
184 bool ReliablePacketBuffer::containsPacket(u16 seqnum)
186 return !(findPacket(seqnum) == m_list.end());
189 RPBSearchResult ReliablePacketBuffer::findPacket(u16 seqnum)
191 std::list<BufferedPacket>::iterator i = m_list.begin();
192 for(; i != m_list.end(); ++i)
194 u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
195 /*dout_con<<"findPacket(): finding seqnum="<<seqnum
196 <<", comparing to s="<<s<<std::endl;*/
202 RPBSearchResult ReliablePacketBuffer::notFound()
206 bool ReliablePacketBuffer::getFirstSeqnum(u16& result)
208 MutexAutoLock listlock(m_list_mutex);
211 BufferedPacket p = *m_list.begin();
212 result = readU16(&p.data[BASE_HEADER_SIZE+1]);
216 BufferedPacket ReliablePacketBuffer::popFirst()
218 MutexAutoLock listlock(m_list_mutex);
220 throw NotFoundException("Buffer is empty");
221 BufferedPacket p = *m_list.begin();
222 m_list.erase(m_list.begin());
225 if (m_list_size == 0) {
226 m_oldest_non_answered_ack = 0;
228 m_oldest_non_answered_ack =
229 readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]);
233 BufferedPacket ReliablePacketBuffer::popSeqnum(u16 seqnum)
235 MutexAutoLock listlock(m_list_mutex);
236 RPBSearchResult r = findPacket(seqnum);
237 if (r == notFound()) {
238 LOG(dout_con<<"Sequence number: " << seqnum
239 << " not found in reliable buffer"<<std::endl);
240 throw NotFoundException("seqnum not found in buffer");
242 BufferedPacket p = *r;
245 RPBSearchResult next = r;
247 if (next != notFound()) {
248 u16 s = readU16(&(next->data[BASE_HEADER_SIZE+1]));
249 m_oldest_non_answered_ack = s;
255 if (m_list_size == 0)
256 { m_oldest_non_answered_ack = 0; }
258 { m_oldest_non_answered_ack = readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]); }
261 void ReliablePacketBuffer::insert(BufferedPacket &p,u16 next_expected)
263 MutexAutoLock listlock(m_list_mutex);
264 if (p.data.getSize() < BASE_HEADER_SIZE + 3) {
265 errorstream << "ReliablePacketBuffer::insert(): Invalid data size for "
266 "reliable packet" << std::endl;
269 u8 type = readU8(&p.data[BASE_HEADER_SIZE + 0]);
270 if (type != PACKET_TYPE_RELIABLE) {
271 errorstream << "ReliablePacketBuffer::insert(): type is not reliable"
275 u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE + 1]);
277 if (!seqnum_in_window(seqnum, next_expected, MAX_RELIABLE_WINDOW_SIZE)) {
278 errorstream << "ReliablePacketBuffer::insert(): seqnum is outside of "
279 "expected window " << std::endl;
282 if (seqnum == next_expected) {
283 errorstream << "ReliablePacketBuffer::insert(): seqnum is next expected"
289 sanity_check(m_list_size <= SEQNUM_MAX+1); // FIXME: Handle the error?
291 // Find the right place for the packet and insert it there
292 // If list is empty, just add it
296 m_oldest_non_answered_ack = seqnum;
301 // Otherwise find the right place
302 std::list<BufferedPacket>::iterator i = m_list.begin();
303 // Find the first packet in the list which has a higher seqnum
304 u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
306 /* case seqnum is smaller then next_expected seqnum */
307 /* this is true e.g. on wrap around */
308 if (seqnum < next_expected) {
309 while(((s < seqnum) || (s >= next_expected)) && (i != m_list.end())) {
311 if (i != m_list.end())
312 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
315 /* non wrap around case (at least for incoming and next_expected */
318 while(((s < seqnum) && (s >= next_expected)) && (i != m_list.end())) {
320 if (i != m_list.end())
321 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
327 (readU16(&(i->data[BASE_HEADER_SIZE+1])) != seqnum) ||
328 (i->data.getSize() != p.data.getSize()) ||
329 (i->address != p.address)
332 /* if this happens your maximum transfer window may be to big */
334 "Duplicated seqnum %d non matching packet detected:\n",
336 fprintf(stderr, "Old: seqnum: %05d size: %04d, address: %s\n",
337 readU16(&(i->data[BASE_HEADER_SIZE+1])),i->data.getSize(),
338 i->address.serializeString().c_str());
339 fprintf(stderr, "New: seqnum: %05d size: %04u, address: %s\n",
340 readU16(&(p.data[BASE_HEADER_SIZE+1])),p.data.getSize(),
341 p.address.serializeString().c_str());
342 throw IncomingDataCorruption("duplicated packet isn't same as original one");
345 /* nothing to do this seems to be a resent packet */
346 /* for paranoia reason data should be compared */
349 /* insert or push back */
350 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 IncomingSplitBuffer::~IncomingSplitBuffer()
394 MutexAutoLock listlock(m_map_mutex);
395 for (auto &i : m_buf) {
400 This will throw a GotSplitPacketException when a full
401 split packet is constructed.
403 SharedBuffer<u8> IncomingSplitBuffer::insert(const BufferedPacket &p, bool reliable)
405 MutexAutoLock listlock(m_map_mutex);
406 u32 headersize = BASE_HEADER_SIZE + 7;
407 if (p.data.getSize() < headersize) {
408 errorstream << "Invalid data size for split packet" << std::endl;
409 return SharedBuffer<u8>();
411 u8 type = readU8(&p.data[BASE_HEADER_SIZE+0]);
412 u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]);
413 u16 chunk_count = readU16(&p.data[BASE_HEADER_SIZE+3]);
414 u16 chunk_num = readU16(&p.data[BASE_HEADER_SIZE+5]);
416 if (type != PACKET_TYPE_SPLIT) {
417 errorstream << "IncomingSplitBuffer::insert(): type is not split"
419 return SharedBuffer<u8>();
422 // Add if doesn't exist
423 if (m_buf.find(seqnum) == m_buf.end()) {
424 m_buf[seqnum] = new IncomingSplitPacket(chunk_count, reliable);
427 IncomingSplitPacket *sp = m_buf[seqnum];
429 if (chunk_count != sp->chunk_count)
430 LOG(derr_con<<"Connection: WARNING: chunk_count="<<chunk_count
431 <<" != sp->chunk_count="<<sp->chunk_count
433 if (reliable != sp->reliable)
434 LOG(derr_con<<"Connection: WARNING: reliable="<<reliable
435 <<" != sp->reliable="<<sp->reliable
438 // If chunk already exists, ignore it.
439 // Sometimes two identical packets may arrive when there is network
440 // lag and the server re-sends stuff.
441 if (sp->chunks.find(chunk_num) != sp->chunks.end())
442 return SharedBuffer<u8>();
444 // Cut chunk data out of packet
445 u32 chunkdatasize = p.data.getSize() - headersize;
446 SharedBuffer<u8> chunkdata(chunkdatasize);
447 memcpy(*chunkdata, &(p.data[headersize]), chunkdatasize);
449 // Set chunk data in buffer
450 sp->chunks[chunk_num] = chunkdata;
452 // If not all chunks are received, return empty buffer
453 if (!sp->allReceived())
454 return SharedBuffer<u8>();
456 // Calculate total size
458 for (const auto &chunk : sp->chunks) {
459 totalsize += chunk.second.getSize();
462 SharedBuffer<u8> fulldata(totalsize);
464 // Copy chunks to data buffer
466 for (u32 chunk_i=0; chunk_i<sp->chunk_count; chunk_i++) {
467 const SharedBuffer<u8> &buf = sp->chunks[chunk_i];
468 u16 buf_chunkdatasize = buf.getSize();
469 memcpy(&fulldata[start], *buf, buf_chunkdatasize);
470 start += buf_chunkdatasize;
473 // Remove sp from buffer
479 void IncomingSplitBuffer::removeUnreliableTimedOuts(float dtime, float timeout)
481 std::deque<u16> remove_queue;
483 MutexAutoLock listlock(m_map_mutex);
484 for (auto &i : m_buf) {
485 IncomingSplitPacket *p = i.second;
486 // Reliable ones are not removed by timeout
490 if (p->time >= timeout)
491 remove_queue.push_back(i.first);
494 for (u16 j : remove_queue) {
495 MutexAutoLock listlock(m_map_mutex);
496 LOG(dout_con<<"NOTE: Removing timed out unreliable split packet"<<std::endl);
506 void ConnectionCommand::send(u16 peer_id_, u8 channelnum_, NetworkPacket *pkt,
511 channelnum = channelnum_;
512 data = pkt->oldForgePacket();
513 reliable = reliable_;
520 u16 Channel::readNextIncomingSeqNum()
522 MutexAutoLock internal(m_internal_mutex);
523 return next_incoming_seqnum;
526 u16 Channel::incNextIncomingSeqNum()
528 MutexAutoLock internal(m_internal_mutex);
529 u16 retval = next_incoming_seqnum;
530 next_incoming_seqnum++;
534 u16 Channel::readNextSplitSeqNum()
536 MutexAutoLock internal(m_internal_mutex);
537 return next_outgoing_split_seqnum;
539 void Channel::setNextSplitSeqNum(u16 seqnum)
541 MutexAutoLock internal(m_internal_mutex);
542 next_outgoing_split_seqnum = seqnum;
545 u16 Channel::getOutgoingSequenceNumber(bool& successful)
547 MutexAutoLock internal(m_internal_mutex);
548 u16 retval = next_outgoing_seqnum;
549 u16 lowest_unacked_seqnumber;
551 /* shortcut if there ain't any packet in outgoing list */
552 if (outgoing_reliables_sent.empty())
554 next_outgoing_seqnum++;
558 if (outgoing_reliables_sent.getFirstSeqnum(lowest_unacked_seqnumber))
560 if (lowest_unacked_seqnumber < next_outgoing_seqnum) {
561 // ugly cast but this one is required in order to tell compiler we
562 // know about difference of two unsigned may be negative in general
563 // but we already made sure it won't happen in this case
564 if (((u16)(next_outgoing_seqnum - lowest_unacked_seqnumber)) > window_size) {
570 // ugly cast but this one is required in order to tell compiler we
571 // know about difference of two unsigned may be negative in general
572 // but we already made sure it won't happen in this case
573 if ((next_outgoing_seqnum + (u16)(SEQNUM_MAX - lowest_unacked_seqnumber)) >
581 next_outgoing_seqnum++;
585 u16 Channel::readOutgoingSequenceNumber()
587 MutexAutoLock internal(m_internal_mutex);
588 return next_outgoing_seqnum;
591 bool Channel::putBackSequenceNumber(u16 seqnum)
593 if (((seqnum + 1) % (SEQNUM_MAX+1)) == next_outgoing_seqnum) {
595 next_outgoing_seqnum = seqnum;
601 void Channel::UpdateBytesSent(unsigned int bytes, unsigned int packets)
603 MutexAutoLock internal(m_internal_mutex);
604 current_bytes_transfered += bytes;
605 current_packet_successfull += packets;
608 void Channel::UpdateBytesReceived(unsigned int bytes) {
609 MutexAutoLock internal(m_internal_mutex);
610 current_bytes_received += bytes;
613 void Channel::UpdateBytesLost(unsigned int bytes)
615 MutexAutoLock internal(m_internal_mutex);
616 current_bytes_lost += bytes;
620 void Channel::UpdatePacketLossCounter(unsigned int count)
622 MutexAutoLock internal(m_internal_mutex);
623 current_packet_loss += count;
626 void Channel::UpdatePacketTooLateCounter()
628 MutexAutoLock internal(m_internal_mutex);
629 current_packet_too_late++;
632 void Channel::UpdateTimers(float dtime,bool legacy_peer)
634 bpm_counter += dtime;
635 packet_loss_counter += dtime;
637 if (packet_loss_counter > 1.0)
639 packet_loss_counter -= 1.0;
641 unsigned int packet_loss = 11; /* use a neutral value for initialization */
642 unsigned int packets_successfull = 0;
643 //unsigned int packet_too_late = 0;
645 bool reasonable_amount_of_data_transmitted = false;
648 MutexAutoLock internal(m_internal_mutex);
649 packet_loss = current_packet_loss;
650 //packet_too_late = current_packet_too_late;
651 packets_successfull = current_packet_successfull;
653 if (current_bytes_transfered > (unsigned int) (window_size*512/2))
655 reasonable_amount_of_data_transmitted = true;
657 current_packet_loss = 0;
658 current_packet_too_late = 0;
659 current_packet_successfull = 0;
662 /* dynamic window size is only available for non legacy peers */
664 float successfull_to_lost_ratio = 0.0;
667 if (packets_successfull > 0) {
668 successfull_to_lost_ratio = packet_loss/packets_successfull;
670 else if (packet_loss > 0)
674 MIN_RELIABLE_WINDOW_SIZE);
680 if ((successfull_to_lost_ratio < 0.01) &&
681 (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)
688 MAX_RELIABLE_WINDOW_SIZE);
690 else if ((successfull_to_lost_ratio < 0.05) &&
691 (window_size < MAX_RELIABLE_WINDOW_SIZE))
693 /* don't even think about increasing if we didn't even
694 * use major parts of our window */
695 if (reasonable_amount_of_data_transmitted)
698 MAX_RELIABLE_WINDOW_SIZE);
700 else if (successfull_to_lost_ratio > 0.15)
704 MIN_RELIABLE_WINDOW_SIZE);
706 else if (successfull_to_lost_ratio > 0.1)
710 MIN_RELIABLE_WINDOW_SIZE);
716 if (bpm_counter > 10.0)
719 MutexAutoLock internal(m_internal_mutex);
721 (((float) current_bytes_transfered)/bpm_counter)/1024.0;
722 current_bytes_transfered = 0;
724 (((float) current_bytes_lost)/bpm_counter)/1024.0;
725 current_bytes_lost = 0;
727 (((float) current_bytes_received)/bpm_counter)/1024.0;
728 current_bytes_received = 0;
732 if (cur_kbps > max_kbps)
737 if (cur_kbps_lost > max_kbps_lost)
739 max_kbps_lost = cur_kbps_lost;
742 if (cur_incoming_kbps > max_incoming_kbps) {
743 max_incoming_kbps = cur_incoming_kbps;
746 rate_samples = MYMIN(rate_samples+1,10);
747 float old_fraction = ((float) (rate_samples-1) )/( (float) rate_samples);
748 avg_kbps = avg_kbps * old_fraction +
749 cur_kbps * (1.0 - old_fraction);
750 avg_kbps_lost = avg_kbps_lost * old_fraction +
751 cur_kbps_lost * (1.0 - old_fraction);
752 avg_incoming_kbps = avg_incoming_kbps * old_fraction +
753 cur_incoming_kbps * (1.0 - old_fraction);
762 PeerHelper::PeerHelper(Peer* peer) :
765 if (peer && !peer->IncUseCount())
769 PeerHelper::~PeerHelper()
772 m_peer->DecUseCount();
777 PeerHelper& PeerHelper::operator=(Peer* peer)
780 if (peer && !peer->IncUseCount())
785 Peer* PeerHelper::operator->() const
790 Peer* PeerHelper::operator&() const
795 bool PeerHelper::operator!()
800 bool PeerHelper::operator!=(void* ptr)
802 return ((void*) m_peer != ptr);
805 bool Peer::IncUseCount()
807 MutexAutoLock lock(m_exclusive_access_mutex);
809 if (!m_pending_deletion) {
817 void Peer::DecUseCount()
820 MutexAutoLock lock(m_exclusive_access_mutex);
821 sanity_check(m_usage > 0);
824 if (!((m_pending_deletion) && (m_usage == 0)))
830 void Peer::RTTStatistics(float rtt, const std::string &profiler_id,
831 unsigned int num_samples) {
833 if (m_last_rtt > 0) {
834 /* set min max values */
835 if (rtt < m_rtt.min_rtt)
837 if (rtt >= m_rtt.max_rtt)
840 /* do average calculation */
841 if (m_rtt.avg_rtt < 0.0)
844 m_rtt.avg_rtt = m_rtt.avg_rtt * (num_samples/(num_samples-1)) +
845 rtt * (1/num_samples);
847 /* do jitter calculation */
849 //just use some neutral value at beginning
850 float jitter = m_rtt.jitter_min;
852 if (rtt > m_last_rtt)
853 jitter = rtt-m_last_rtt;
855 if (rtt <= m_last_rtt)
856 jitter = m_last_rtt - rtt;
858 if (jitter < m_rtt.jitter_min)
859 m_rtt.jitter_min = jitter;
860 if (jitter >= m_rtt.jitter_max)
861 m_rtt.jitter_max = jitter;
863 if (m_rtt.jitter_avg < 0.0)
864 m_rtt.jitter_avg = jitter;
866 m_rtt.jitter_avg = m_rtt.jitter_avg * (num_samples/(num_samples-1)) +
867 jitter * (1/num_samples);
869 if (!profiler_id.empty()) {
870 g_profiler->graphAdd(profiler_id + "_rtt", rtt);
871 g_profiler->graphAdd(profiler_id + "_jitter", jitter);
874 /* save values required for next loop */
878 bool Peer::isTimedOut(float timeout)
880 MutexAutoLock lock(m_exclusive_access_mutex);
881 u64 current_time = porting::getTimeMs();
883 float dtime = CALC_DTIME(m_last_timeout_check,current_time);
884 m_last_timeout_check = current_time;
886 m_timeout_counter += dtime;
888 return m_timeout_counter > timeout;
894 MutexAutoLock usage_lock(m_exclusive_access_mutex);
895 m_pending_deletion = true;
900 PROFILE(std::stringstream peerIdentifier1);
901 PROFILE(peerIdentifier1 << "runTimeouts[" << m_connection->getDesc()
902 << ";" << id << ";RELIABLE]");
903 PROFILE(g_profiler->remove(peerIdentifier1.str()));
904 PROFILE(std::stringstream peerIdentifier2);
905 PROFILE(peerIdentifier2 << "sendPackets[" << m_connection->getDesc()
906 << ";" << id << ";RELIABLE]");
907 PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier2.str(), SPT_AVG));
912 UDPPeer::UDPPeer(u16 a_id, Address a_address, Connection* connection) :
913 Peer(a_address,a_id,connection)
917 bool UDPPeer::getAddress(MTProtocols type,Address& toset)
919 if ((type == MTP_UDP) || (type == MTP_MINETEST_RELIABLE_UDP) || (type == MTP_PRIMARY))
928 void UDPPeer::setNonLegacyPeer()
930 m_legacy_peer = false;
931 for(unsigned int i=0; i< CHANNEL_COUNT; i++)
933 channels->setWindowSize(g_settings->getU16("max_packets_per_iteration"));
937 void UDPPeer::reportRTT(float rtt)
942 RTTStatistics(rtt,"rudp",MAX_RELIABLE_WINDOW_SIZE*10);
944 float timeout = getStat(AVG_RTT) * RESEND_TIMEOUT_FACTOR;
945 if (timeout < RESEND_TIMEOUT_MIN)
946 timeout = RESEND_TIMEOUT_MIN;
947 if (timeout > RESEND_TIMEOUT_MAX)
948 timeout = RESEND_TIMEOUT_MAX;
950 MutexAutoLock usage_lock(m_exclusive_access_mutex);
951 resend_timeout = timeout;
954 bool UDPPeer::Ping(float dtime,SharedBuffer<u8>& data)
956 m_ping_timer += dtime;
957 if (m_ping_timer >= PING_TIMEOUT)
959 // Create and send PING packet
960 writeU8(&data[0], PACKET_TYPE_CONTROL);
961 writeU8(&data[1], CONTROLTYPE_PING);
968 void UDPPeer::PutReliableSendCommand(ConnectionCommand &c,
969 unsigned int max_packet_size)
971 if (m_pending_disconnect)
974 if ( channels[c.channelnum].queued_commands.empty() &&
975 /* don't queue more packets then window size */
976 (channels[c.channelnum].queued_reliables.size()
977 < (channels[c.channelnum].getWindowSize()/2))) {
978 LOG(dout_con<<m_connection->getDesc()
979 <<" processing reliable command for peer id: " << c.peer_id
980 <<" data size: " << c.data.getSize() << std::endl);
981 if (!processReliableSendCommand(c,max_packet_size)) {
982 channels[c.channelnum].queued_commands.push_back(c);
986 LOG(dout_con<<m_connection->getDesc()
987 <<" Queueing reliable command for peer id: " << c.peer_id
988 <<" data size: " << c.data.getSize() <<std::endl);
989 channels[c.channelnum].queued_commands.push_back(c);
993 bool UDPPeer::processReliableSendCommand(
994 ConnectionCommand &c,
995 unsigned int max_packet_size)
997 if (m_pending_disconnect)
1000 u32 chunksize_max = max_packet_size
1002 - RELIABLE_HEADER_SIZE;
1004 sanity_check(c.data.getSize() < MAX_RELIABLE_WINDOW_SIZE*512);
1006 std::list<SharedBuffer<u8>> originals;
1007 u16 split_sequence_number = channels[c.channelnum].readNextSplitSeqNum();
1010 originals.emplace_back(c.data);
1012 makeAutoSplitPacket(c.data, chunksize_max,split_sequence_number, &originals);
1013 channels[c.channelnum].setNextSplitSeqNum(split_sequence_number);
1016 bool have_sequence_number = true;
1017 bool have_initial_sequence_number = false;
1018 std::queue<BufferedPacket> toadd;
1019 volatile u16 initial_sequence_number = 0;
1021 for (SharedBuffer<u8> &original : originals) {
1022 u16 seqnum = channels[c.channelnum].getOutgoingSequenceNumber(have_sequence_number);
1024 /* oops, we don't have enough sequence numbers to send this packet */
1025 if (!have_sequence_number)
1028 if (!have_initial_sequence_number)
1030 initial_sequence_number = seqnum;
1031 have_initial_sequence_number = true;
1034 SharedBuffer<u8> reliable = makeReliablePacket(original, seqnum);
1036 // Add base headers and make a packet
1037 BufferedPacket p = con::makePacket(address, reliable,
1038 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1044 if (have_sequence_number) {
1045 volatile u16 pcount = 0;
1046 while (!toadd.empty()) {
1047 BufferedPacket p = toadd.front();
1049 // LOG(dout_con<<connection->getDesc()
1050 // << " queuing reliable packet for peer_id: " << c.peer_id
1051 // << " channel: " << (c.channelnum&0xFF)
1052 // << " seqnum: " << readU16(&p.data[BASE_HEADER_SIZE+1])
1054 channels[c.channelnum].queued_reliables.push(p);
1057 sanity_check(channels[c.channelnum].queued_reliables.size() < 0xFFFF);
1061 volatile u16 packets_available = toadd.size();
1062 /* we didn't get a single sequence number no need to fill queue */
1063 if (!have_initial_sequence_number) {
1067 while (!toadd.empty()) {
1071 bool successfully_put_back_sequence_number
1072 = channels[c.channelnum].putBackSequenceNumber(
1073 (initial_sequence_number+toadd.size() % (SEQNUM_MAX+1)));
1075 FATAL_ERROR_IF(!successfully_put_back_sequence_number, "error");
1078 LOG(dout_con<<m_connection->getDesc()
1079 << " Windowsize exceeded on reliable sending "
1080 << c.data.getSize() << " bytes"
1081 << std::endl << "\t\tinitial_sequence_number: "
1082 << initial_sequence_number
1083 << std::endl << "\t\tgot at most : "
1084 << packets_available << " packets"
1085 << std::endl << "\t\tpackets queued : "
1086 << channels[c.channelnum].outgoing_reliables_sent.size()
1092 void UDPPeer::RunCommandQueues(
1093 unsigned int max_packet_size,
1094 unsigned int maxcommands,
1095 unsigned int maxtransfer)
1098 for (Channel &channel : channels) {
1099 unsigned int commands_processed = 0;
1101 if ((!channel.queued_commands.empty()) &&
1102 (channel.queued_reliables.size() < maxtransfer) &&
1103 (commands_processed < maxcommands)) {
1105 ConnectionCommand c = channel.queued_commands.front();
1107 LOG(dout_con << m_connection->getDesc()
1108 << " processing queued reliable command " << std::endl);
1110 // Packet is processed, remove it from queue
1111 if (processReliableSendCommand(c,max_packet_size)) {
1112 channel.queued_commands.pop_front();
1114 LOG(dout_con << m_connection->getDesc()
1115 << " Failed to queue packets for peer_id: " << c.peer_id
1116 << ", delaying sending of " << c.data.getSize()
1117 << " bytes" << std::endl);
1120 catch (ItemNotFoundException &e) {
1121 // intentionally empty
1127 u16 UDPPeer::getNextSplitSequenceNumber(u8 channel)
1129 assert(channel < CHANNEL_COUNT); // Pre-condition
1130 return channels[channel].readNextSplitSeqNum();
1133 void UDPPeer::setNextSplitSequenceNumber(u8 channel, u16 seqnum)
1135 assert(channel < CHANNEL_COUNT); // Pre-condition
1136 channels[channel].setNextSplitSeqNum(seqnum);
1139 SharedBuffer<u8> UDPPeer::addSplitPacket(u8 channel, const BufferedPacket &toadd,
1142 assert(channel < CHANNEL_COUNT); // Pre-condition
1143 return channels[channel].incoming_splits.insert(toadd, reliable);
1150 Connection::Connection(u32 protocol_id, u32 max_packet_size, float timeout,
1151 bool ipv6, PeerHandler *peerhandler) :
1153 m_protocol_id(protocol_id),
1154 m_sendThread(new ConnectionSendThread(max_packet_size, timeout)),
1155 m_receiveThread(new ConnectionReceiveThread(max_packet_size)),
1156 m_bc_peerhandler(peerhandler)
1159 m_udpSocket.setTimeoutMs(5);
1161 m_sendThread->setParent(this);
1162 m_receiveThread->setParent(this);
1164 m_sendThread->start();
1165 m_receiveThread->start();
1169 Connection::~Connection()
1171 m_shutting_down = true;
1172 // request threads to stop
1173 m_sendThread->stop();
1174 m_receiveThread->stop();
1176 //TODO for some unkonwn reason send/receive threads do not exit as they're
1177 // supposed to be but wait on peer timeout. To speed up shutdown we reduce
1178 // timeout to half a second.
1179 m_sendThread->setPeerTimeout(0.5);
1181 // wait for threads to finish
1182 m_sendThread->wait();
1183 m_receiveThread->wait();
1186 for (auto &peer : m_peers) {
1191 /* Internal stuff */
1192 void Connection::putEvent(ConnectionEvent &e)
1194 assert(e.type != CONNEVENT_NONE); // Pre-condition
1195 m_event_queue.push_back(e);
1198 void Connection::TriggerSend()
1200 m_sendThread->Trigger();
1203 PeerHelper Connection::getPeerNoEx(u16 peer_id)
1205 MutexAutoLock peerlock(m_peers_mutex);
1206 std::map<u16, Peer*>::iterator node = m_peers.find(peer_id);
1208 if (node == m_peers.end()) {
1209 return PeerHelper(NULL);
1213 FATAL_ERROR_IF(node->second->id != peer_id, "Invalid peer id");
1215 return PeerHelper(node->second);
1218 /* find peer_id for address */
1219 u16 Connection::lookupPeer(Address& sender)
1221 MutexAutoLock peerlock(m_peers_mutex);
1222 std::map<u16, Peer*>::iterator j;
1223 j = m_peers.begin();
1224 for(; j != m_peers.end(); ++j)
1226 Peer *peer = j->second;
1227 if (peer->isPendingDeletion())
1232 if ((peer->getAddress(MTP_MINETEST_RELIABLE_UDP, tocheck)) && (tocheck == sender))
1235 if ((peer->getAddress(MTP_UDP, tocheck)) && (tocheck == sender))
1239 return PEER_ID_INEXISTENT;
1242 std::list<Peer*> Connection::getPeers()
1244 std::list<Peer*> list;
1245 for (auto &p : m_peers) {
1246 Peer *peer = p.second;
1247 list.push_back(peer);
1252 bool Connection::deletePeer(u16 peer_id, bool timeout)
1256 /* lock list as short as possible */
1258 MutexAutoLock peerlock(m_peers_mutex);
1259 if (m_peers.find(peer_id) == m_peers.end())
1261 peer = m_peers[peer_id];
1262 m_peers.erase(peer_id);
1263 m_peer_ids.remove(peer_id);
1266 Address peer_address;
1267 //any peer has a primary address this never fails!
1268 peer->getAddress(MTP_PRIMARY, peer_address);
1271 e.peerRemoved(peer_id, timeout, peer_address);
1281 ConnectionEvent Connection::waitEvent(u32 timeout_ms)
1284 return m_event_queue.pop_front(timeout_ms);
1285 } catch(ItemNotFoundException &ex) {
1287 e.type = CONNEVENT_NONE;
1292 void Connection::putCommand(ConnectionCommand &c)
1294 if (!m_shutting_down) {
1295 m_command_queue.push_back(c);
1296 m_sendThread->Trigger();
1300 void Connection::Serve(Address bind_addr)
1302 ConnectionCommand c;
1307 void Connection::Connect(Address address)
1309 ConnectionCommand c;
1314 bool Connection::Connected()
1316 MutexAutoLock peerlock(m_peers_mutex);
1318 if (m_peers.size() != 1)
1321 std::map<u16, Peer*>::iterator node = m_peers.find(PEER_ID_SERVER);
1322 if (node == m_peers.end())
1325 if (m_peer_id == PEER_ID_INEXISTENT)
1331 void Connection::Disconnect()
1333 ConnectionCommand c;
1338 void Connection::Receive(NetworkPacket* pkt)
1341 ConnectionEvent e = waitEvent(m_bc_receive_timeout);
1342 if (e.type != CONNEVENT_NONE)
1343 LOG(dout_con << getDesc() << ": Receive: got event: "
1344 << e.describe() << std::endl);
1346 case CONNEVENT_NONE:
1347 throw NoIncomingDataException("No incoming data");
1348 case CONNEVENT_DATA_RECEIVED:
1349 // Data size is lesser than command size, ignoring packet
1350 if (e.data.getSize() < 2) {
1354 pkt->putRawPacket(*e.data, e.data.getSize(), e.peer_id);
1356 case CONNEVENT_PEER_ADDED: {
1357 UDPPeer tmp(e.peer_id, e.address, this);
1358 if (m_bc_peerhandler)
1359 m_bc_peerhandler->peerAdded(&tmp);
1362 case CONNEVENT_PEER_REMOVED: {
1363 UDPPeer tmp(e.peer_id, e.address, this);
1364 if (m_bc_peerhandler)
1365 m_bc_peerhandler->deletingPeer(&tmp, e.timeout);
1368 case CONNEVENT_BIND_FAILED:
1369 throw ConnectionBindFailed("Failed to bind socket "
1370 "(port already in use?)");
1373 throw NoIncomingDataException("No incoming data");
1376 void Connection::Send(u16 peer_id, u8 channelnum,
1377 NetworkPacket* pkt, bool reliable)
1379 assert(channelnum < CHANNEL_COUNT); // Pre-condition
1381 ConnectionCommand c;
1383 c.send(peer_id, channelnum, pkt, reliable);
1387 Address Connection::GetPeerAddress(u16 peer_id)
1389 PeerHelper peer = getPeerNoEx(peer_id);
1392 throw PeerNotFoundException("No address for peer found!");
1393 Address peer_address;
1394 peer->getAddress(MTP_PRIMARY, peer_address);
1395 return peer_address;
1398 float Connection::getPeerStat(u16 peer_id, rtt_stat_type type)
1400 PeerHelper peer = getPeerNoEx(peer_id);
1401 if (!peer) return -1;
1402 return peer->getStat(type);
1405 float Connection::getLocalStat(rate_stat_type type)
1407 PeerHelper peer = getPeerNoEx(PEER_ID_SERVER);
1409 FATAL_ERROR_IF(!peer, "Connection::getLocalStat we couldn't get our own peer? are you serious???");
1413 for (Channel &channel : dynamic_cast<UDPPeer *>(&peer)->channels) {
1416 retval += channel.getCurrentDownloadRateKB();
1419 retval += channel.getAvgDownloadRateKB();
1422 retval += channel.getCurrentIncomingRateKB();
1425 retval += channel.getAvgIncomingRateKB();
1428 retval += channel.getAvgLossRateKB();
1431 retval += channel.getCurrentLossRateKB();
1434 FATAL_ERROR("Connection::getLocalStat Invalid stat type");
1440 u16 Connection::createPeer(Address& sender, MTProtocols protocol, int fd)
1442 // Somebody wants to make a new connection
1444 // Get a unique peer id (2 or higher)
1445 u16 peer_id_new = m_next_remote_peer_id;
1446 u16 overflow = MAX_UDP_PEERS;
1449 Find an unused peer id
1451 MutexAutoLock lock(m_peers_mutex);
1452 bool out_of_ids = false;
1455 if (m_peers.find(peer_id_new) == m_peers.end())
1458 // Check for overflow
1459 if (peer_id_new == overflow) {
1467 errorstream << getDesc() << " ran out of peer ids" << std::endl;
1468 return PEER_ID_INEXISTENT;
1473 peer = new UDPPeer(peer_id_new, sender, this);
1475 m_peers[peer->id] = peer;
1476 m_peer_ids.push_back(peer->id);
1478 m_next_remote_peer_id = (peer_id_new +1 ) % MAX_UDP_PEERS;
1480 LOG(dout_con << getDesc()
1481 << "createPeer(): giving peer_id=" << peer_id_new << std::endl);
1483 ConnectionCommand cmd;
1484 SharedBuffer<u8> reply(4);
1485 writeU8(&reply[0], PACKET_TYPE_CONTROL);
1486 writeU8(&reply[1], CONTROLTYPE_SET_PEER_ID);
1487 writeU16(&reply[2], peer_id_new);
1488 cmd.createPeer(peer_id_new,reply);
1491 // Create peer addition event
1493 e.peerAdded(peer_id_new, sender);
1496 // We're now talking to a valid peer_id
1500 void Connection::PrintInfo(std::ostream &out)
1502 m_info_mutex.lock();
1503 out<<getDesc()<<": ";
1504 m_info_mutex.unlock();
1507 const std::string Connection::getDesc()
1509 return std::string("con(")+
1510 itos(m_udpSocket.GetHandle())+"/"+itos(m_peer_id)+")";
1513 void Connection::DisconnectPeer(u16 peer_id)
1515 ConnectionCommand discon;
1516 discon.disconnect_peer(peer_id);
1520 void Connection::sendAck(u16 peer_id, u8 channelnum, u16 seqnum)
1522 assert(channelnum < CHANNEL_COUNT); // Pre-condition
1524 LOG(dout_con<<getDesc()
1525 <<" Queuing ACK command to peer_id: " << peer_id <<
1526 " channel: " << (channelnum & 0xFF) <<
1527 " seqnum: " << seqnum << std::endl);
1529 ConnectionCommand c;
1530 SharedBuffer<u8> ack(4);
1531 writeU8(&ack[0], PACKET_TYPE_CONTROL);
1532 writeU8(&ack[1], CONTROLTYPE_ACK);
1533 writeU16(&ack[2], seqnum);
1535 c.ack(peer_id, channelnum, ack);
1537 m_sendThread->Trigger();
1540 UDPPeer* Connection::createServerPeer(Address& address)
1542 if (getPeerNoEx(PEER_ID_SERVER) != 0)
1544 throw ConnectionException("Already connected to a server");
1547 UDPPeer *peer = new UDPPeer(PEER_ID_SERVER, address, this);
1550 MutexAutoLock lock(m_peers_mutex);
1551 m_peers[peer->id] = peer;
1552 m_peer_ids.push_back(peer->id);