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, SharedBuffer<u8> data,
59 u32 protocol_id, session_t 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(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(SharedBuffer<u8> data, u16 seqnum)
145 u32 packet_size = data.getSize() + header_size;
146 SharedBuffer<u8> b(packet_size);
148 writeU8(&b[0], PACKET_TYPE_RELIABLE);
149 writeU16(&b[1], seqnum);
151 memcpy(&b[header_size], *data, data.getSize());
160 void ReliablePacketBuffer::print()
162 MutexAutoLock listlock(m_list_mutex);
163 LOG(dout_con<<"Dump of ReliablePacketBuffer:" << std::endl);
164 unsigned int index = 0;
165 for (BufferedPacket &bufferedPacket : m_list) {
166 u16 s = readU16(&(bufferedPacket.data[BASE_HEADER_SIZE+1]));
167 LOG(dout_con<<index<< ":" << s << std::endl);
171 bool ReliablePacketBuffer::empty()
173 MutexAutoLock listlock(m_list_mutex);
174 return m_list.empty();
177 u32 ReliablePacketBuffer::size()
182 bool ReliablePacketBuffer::containsPacket(u16 seqnum)
184 return !(findPacket(seqnum) == m_list.end());
187 RPBSearchResult ReliablePacketBuffer::findPacket(u16 seqnum)
189 std::list<BufferedPacket>::iterator i = m_list.begin();
190 for(; i != m_list.end(); ++i)
192 u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
193 /*dout_con<<"findPacket(): finding seqnum="<<seqnum
194 <<", comparing to s="<<s<<std::endl;*/
200 RPBSearchResult ReliablePacketBuffer::notFound()
204 bool ReliablePacketBuffer::getFirstSeqnum(u16& result)
206 MutexAutoLock listlock(m_list_mutex);
209 BufferedPacket p = *m_list.begin();
210 result = readU16(&p.data[BASE_HEADER_SIZE+1]);
214 BufferedPacket ReliablePacketBuffer::popFirst()
216 MutexAutoLock listlock(m_list_mutex);
218 throw NotFoundException("Buffer is empty");
219 BufferedPacket p = *m_list.begin();
220 m_list.erase(m_list.begin());
223 if (m_list_size == 0) {
224 m_oldest_non_answered_ack = 0;
226 m_oldest_non_answered_ack =
227 readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]);
231 BufferedPacket ReliablePacketBuffer::popSeqnum(u16 seqnum)
233 MutexAutoLock listlock(m_list_mutex);
234 RPBSearchResult r = findPacket(seqnum);
235 if (r == notFound()) {
236 LOG(dout_con<<"Sequence number: " << seqnum
237 << " not found in reliable buffer"<<std::endl);
238 throw NotFoundException("seqnum not found in buffer");
240 BufferedPacket p = *r;
243 RPBSearchResult next = r;
245 if (next != notFound()) {
246 u16 s = readU16(&(next->data[BASE_HEADER_SIZE+1]));
247 m_oldest_non_answered_ack = s;
253 if (m_list_size == 0)
254 { m_oldest_non_answered_ack = 0; }
256 { m_oldest_non_answered_ack = readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]); }
259 void ReliablePacketBuffer::insert(BufferedPacket &p,u16 next_expected)
261 MutexAutoLock listlock(m_list_mutex);
262 if (p.data.getSize() < BASE_HEADER_SIZE + 3) {
263 errorstream << "ReliablePacketBuffer::insert(): Invalid data size for "
264 "reliable packet" << std::endl;
267 u8 type = readU8(&p.data[BASE_HEADER_SIZE + 0]);
268 if (type != PACKET_TYPE_RELIABLE) {
269 errorstream << "ReliablePacketBuffer::insert(): type is not reliable"
273 u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE + 1]);
275 if (!seqnum_in_window(seqnum, next_expected, MAX_RELIABLE_WINDOW_SIZE)) {
276 errorstream << "ReliablePacketBuffer::insert(): seqnum is outside of "
277 "expected window " << std::endl;
280 if (seqnum == next_expected) {
281 errorstream << "ReliablePacketBuffer::insert(): seqnum is next expected"
287 sanity_check(m_list_size <= SEQNUM_MAX+1); // FIXME: Handle the error?
289 // Find the right place for the packet and insert it there
290 // If list is empty, just add it
294 m_oldest_non_answered_ack = seqnum;
299 // Otherwise find the right place
300 std::list<BufferedPacket>::iterator i = m_list.begin();
301 // Find the first packet in the list which has a higher seqnum
302 u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
304 /* case seqnum is smaller then next_expected seqnum */
305 /* this is true e.g. on wrap around */
306 if (seqnum < next_expected) {
307 while(((s < seqnum) || (s >= next_expected)) && (i != m_list.end())) {
309 if (i != m_list.end())
310 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
313 /* non wrap around case (at least for incoming and next_expected */
316 while(((s < seqnum) && (s >= next_expected)) && (i != m_list.end())) {
318 if (i != m_list.end())
319 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
325 (readU16(&(i->data[BASE_HEADER_SIZE+1])) != seqnum) ||
326 (i->data.getSize() != p.data.getSize()) ||
327 (i->address != p.address)
330 /* if this happens your maximum transfer window may be to big */
332 "Duplicated seqnum %d non matching packet detected:\n",
334 fprintf(stderr, "Old: seqnum: %05d size: %04d, address: %s\n",
335 readU16(&(i->data[BASE_HEADER_SIZE+1])),i->data.getSize(),
336 i->address.serializeString().c_str());
337 fprintf(stderr, "New: seqnum: %05d size: %04u, address: %s\n",
338 readU16(&(p.data[BASE_HEADER_SIZE+1])),p.data.getSize(),
339 p.address.serializeString().c_str());
340 throw IncomingDataCorruption("duplicated packet isn't same as original one");
343 /* nothing to do this seems to be a resent packet */
344 /* for paranoia reason data should be compared */
347 /* insert or push back */
348 else if (i != m_list.end()) {
355 /* update last packet number */
356 m_oldest_non_answered_ack = readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]);
359 void ReliablePacketBuffer::incrementTimeouts(float dtime)
361 MutexAutoLock listlock(m_list_mutex);
362 for (BufferedPacket &bufferedPacket : m_list) {
363 bufferedPacket.time += dtime;
364 bufferedPacket.totaltime += dtime;
368 std::list<BufferedPacket> ReliablePacketBuffer::getTimedOuts(float timeout,
369 unsigned int max_packets)
371 MutexAutoLock listlock(m_list_mutex);
372 std::list<BufferedPacket> timed_outs;
373 for (BufferedPacket &bufferedPacket : m_list) {
374 if (bufferedPacket.time >= timeout) {
375 timed_outs.push_back(bufferedPacket);
377 //this packet will be sent right afterwards reset timeout here
378 bufferedPacket.time = 0.0f;
379 if (timed_outs.size() >= max_packets)
390 IncomingSplitBuffer::~IncomingSplitBuffer()
392 MutexAutoLock listlock(m_map_mutex);
393 for (auto &i : m_buf) {
398 This will throw a GotSplitPacketException when a full
399 split packet is constructed.
401 SharedBuffer<u8> IncomingSplitBuffer::insert(const BufferedPacket &p, bool reliable)
403 MutexAutoLock listlock(m_map_mutex);
404 u32 headersize = BASE_HEADER_SIZE + 7;
405 if (p.data.getSize() < headersize) {
406 errorstream << "Invalid data size for split packet" << std::endl;
407 return SharedBuffer<u8>();
409 u8 type = readU8(&p.data[BASE_HEADER_SIZE+0]);
410 u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]);
411 u16 chunk_count = readU16(&p.data[BASE_HEADER_SIZE+3]);
412 u16 chunk_num = readU16(&p.data[BASE_HEADER_SIZE+5]);
414 if (type != PACKET_TYPE_SPLIT) {
415 errorstream << "IncomingSplitBuffer::insert(): type is not split"
417 return SharedBuffer<u8>();
420 // Add if doesn't exist
421 if (m_buf.find(seqnum) == m_buf.end()) {
422 m_buf[seqnum] = new IncomingSplitPacket(chunk_count, reliable);
425 IncomingSplitPacket *sp = m_buf[seqnum];
427 if (chunk_count != sp->chunk_count)
428 LOG(derr_con<<"Connection: WARNING: chunk_count="<<chunk_count
429 <<" != sp->chunk_count="<<sp->chunk_count
431 if (reliable != sp->reliable)
432 LOG(derr_con<<"Connection: WARNING: reliable="<<reliable
433 <<" != sp->reliable="<<sp->reliable
436 // If chunk already exists, ignore it.
437 // Sometimes two identical packets may arrive when there is network
438 // lag and the server re-sends stuff.
439 if (sp->chunks.find(chunk_num) != sp->chunks.end())
440 return SharedBuffer<u8>();
442 // Cut chunk data out of packet
443 u32 chunkdatasize = p.data.getSize() - headersize;
444 SharedBuffer<u8> chunkdata(chunkdatasize);
445 memcpy(*chunkdata, &(p.data[headersize]), chunkdatasize);
447 // Set chunk data in buffer
448 sp->chunks[chunk_num] = chunkdata;
450 // If not all chunks are received, return empty buffer
451 if (!sp->allReceived())
452 return SharedBuffer<u8>();
454 // Calculate total size
456 for (const auto &chunk : sp->chunks) {
457 totalsize += chunk.second.getSize();
460 SharedBuffer<u8> fulldata(totalsize);
462 // Copy chunks to data buffer
464 for (u32 chunk_i=0; chunk_i<sp->chunk_count; chunk_i++) {
465 const SharedBuffer<u8> &buf = sp->chunks[chunk_i];
466 u16 buf_chunkdatasize = buf.getSize();
467 memcpy(&fulldata[start], *buf, buf_chunkdatasize);
468 start += buf_chunkdatasize;
471 // Remove sp from buffer
477 void IncomingSplitBuffer::removeUnreliableTimedOuts(float dtime, float timeout)
479 std::deque<u16> remove_queue;
481 MutexAutoLock listlock(m_map_mutex);
482 for (auto &i : m_buf) {
483 IncomingSplitPacket *p = i.second;
484 // Reliable ones are not removed by timeout
488 if (p->time >= timeout)
489 remove_queue.push_back(i.first);
492 for (u16 j : remove_queue) {
493 MutexAutoLock listlock(m_map_mutex);
494 LOG(dout_con<<"NOTE: Removing timed out unreliable split packet"<<std::endl);
504 void ConnectionCommand::send(session_t peer_id_, u8 channelnum_, NetworkPacket *pkt,
509 channelnum = channelnum_;
510 data = pkt->oldForgePacket();
511 reliable = reliable_;
518 u16 Channel::readNextIncomingSeqNum()
520 MutexAutoLock internal(m_internal_mutex);
521 return next_incoming_seqnum;
524 u16 Channel::incNextIncomingSeqNum()
526 MutexAutoLock internal(m_internal_mutex);
527 u16 retval = next_incoming_seqnum;
528 next_incoming_seqnum++;
532 u16 Channel::readNextSplitSeqNum()
534 MutexAutoLock internal(m_internal_mutex);
535 return next_outgoing_split_seqnum;
537 void Channel::setNextSplitSeqNum(u16 seqnum)
539 MutexAutoLock internal(m_internal_mutex);
540 next_outgoing_split_seqnum = seqnum;
543 u16 Channel::getOutgoingSequenceNumber(bool& successful)
545 MutexAutoLock internal(m_internal_mutex);
546 u16 retval = next_outgoing_seqnum;
547 u16 lowest_unacked_seqnumber;
549 /* shortcut if there ain't any packet in outgoing list */
550 if (outgoing_reliables_sent.empty())
552 next_outgoing_seqnum++;
556 if (outgoing_reliables_sent.getFirstSeqnum(lowest_unacked_seqnumber))
558 if (lowest_unacked_seqnumber < next_outgoing_seqnum) {
559 // ugly cast but this one is required in order to tell compiler we
560 // know about difference of two unsigned may be negative in general
561 // but we already made sure it won't happen in this case
562 if (((u16)(next_outgoing_seqnum - lowest_unacked_seqnumber)) > window_size) {
568 // ugly cast but this one is required in order to tell compiler we
569 // know about difference of two unsigned may be negative in general
570 // but we already made sure it won't happen in this case
571 if ((next_outgoing_seqnum + (u16)(SEQNUM_MAX - lowest_unacked_seqnumber)) >
579 next_outgoing_seqnum++;
583 u16 Channel::readOutgoingSequenceNumber()
585 MutexAutoLock internal(m_internal_mutex);
586 return next_outgoing_seqnum;
589 bool Channel::putBackSequenceNumber(u16 seqnum)
591 if (((seqnum + 1) % (SEQNUM_MAX+1)) == next_outgoing_seqnum) {
593 next_outgoing_seqnum = seqnum;
599 void Channel::UpdateBytesSent(unsigned int bytes, unsigned int packets)
601 MutexAutoLock internal(m_internal_mutex);
602 current_bytes_transfered += bytes;
603 current_packet_successfull += packets;
606 void Channel::UpdateBytesReceived(unsigned int bytes) {
607 MutexAutoLock internal(m_internal_mutex);
608 current_bytes_received += bytes;
611 void Channel::UpdateBytesLost(unsigned int bytes)
613 MutexAutoLock internal(m_internal_mutex);
614 current_bytes_lost += bytes;
618 void Channel::UpdatePacketLossCounter(unsigned int count)
620 MutexAutoLock internal(m_internal_mutex);
621 current_packet_loss += count;
624 void Channel::UpdatePacketTooLateCounter()
626 MutexAutoLock internal(m_internal_mutex);
627 current_packet_too_late++;
630 void Channel::UpdateTimers(float dtime,bool legacy_peer)
632 bpm_counter += dtime;
633 packet_loss_counter += dtime;
635 if (packet_loss_counter > 1.0)
637 packet_loss_counter -= 1.0;
639 unsigned int packet_loss = 11; /* use a neutral value for initialization */
640 unsigned int packets_successfull = 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_successfull = current_packet_successfull;
651 if (current_bytes_transfered > (unsigned int) (window_size*512/2))
653 reasonable_amount_of_data_transmitted = true;
655 current_packet_loss = 0;
656 current_packet_too_late = 0;
657 current_packet_successfull = 0;
660 /* dynamic window size is only available for non legacy peers */
662 float successfull_to_lost_ratio = 0.0;
665 if (packets_successfull > 0) {
666 successfull_to_lost_ratio = packet_loss/packets_successfull;
668 else if (packet_loss > 0)
672 MIN_RELIABLE_WINDOW_SIZE);
678 if ((successfull_to_lost_ratio < 0.01) &&
679 (window_size < MAX_RELIABLE_WINDOW_SIZE))
681 /* don't even think about increasing if we didn't even
682 * use major parts of our window */
683 if (reasonable_amount_of_data_transmitted)
686 MAX_RELIABLE_WINDOW_SIZE);
688 else if ((successfull_to_lost_ratio < 0.05) &&
689 (window_size < MAX_RELIABLE_WINDOW_SIZE))
691 /* don't even think about increasing if we didn't even
692 * use major parts of our window */
693 if (reasonable_amount_of_data_transmitted)
696 MAX_RELIABLE_WINDOW_SIZE);
698 else if (successfull_to_lost_ratio > 0.15)
702 MIN_RELIABLE_WINDOW_SIZE);
704 else if (successfull_to_lost_ratio > 0.1)
708 MIN_RELIABLE_WINDOW_SIZE);
714 if (bpm_counter > 10.0)
717 MutexAutoLock internal(m_internal_mutex);
719 (((float) current_bytes_transfered)/bpm_counter)/1024.0;
720 current_bytes_transfered = 0;
722 (((float) current_bytes_lost)/bpm_counter)/1024.0;
723 current_bytes_lost = 0;
725 (((float) current_bytes_received)/bpm_counter)/1024.0;
726 current_bytes_received = 0;
730 if (cur_kbps > max_kbps)
735 if (cur_kbps_lost > max_kbps_lost)
737 max_kbps_lost = cur_kbps_lost;
740 if (cur_incoming_kbps > max_incoming_kbps) {
741 max_incoming_kbps = cur_incoming_kbps;
744 rate_samples = MYMIN(rate_samples+1,10);
745 float old_fraction = ((float) (rate_samples-1) )/( (float) rate_samples);
746 avg_kbps = avg_kbps * old_fraction +
747 cur_kbps * (1.0 - old_fraction);
748 avg_kbps_lost = avg_kbps_lost * old_fraction +
749 cur_kbps_lost * (1.0 - old_fraction);
750 avg_incoming_kbps = avg_incoming_kbps * old_fraction +
751 cur_incoming_kbps * (1.0 - old_fraction);
760 PeerHelper::PeerHelper(Peer* peer) :
763 if (peer && !peer->IncUseCount())
767 PeerHelper::~PeerHelper()
770 m_peer->DecUseCount();
775 PeerHelper& PeerHelper::operator=(Peer* peer)
778 if (peer && !peer->IncUseCount())
783 Peer* PeerHelper::operator->() const
788 Peer* PeerHelper::operator&() const
793 bool PeerHelper::operator!()
798 bool PeerHelper::operator!=(void* ptr)
800 return ((void*) m_peer != ptr);
803 bool Peer::IncUseCount()
805 MutexAutoLock lock(m_exclusive_access_mutex);
807 if (!m_pending_deletion) {
815 void Peer::DecUseCount()
818 MutexAutoLock lock(m_exclusive_access_mutex);
819 sanity_check(m_usage > 0);
822 if (!((m_pending_deletion) && (m_usage == 0)))
828 void Peer::RTTStatistics(float rtt, const std::string &profiler_id)
830 static const float avg_factor = 100.0f / MAX_RELIABLE_WINDOW_SIZE;
832 if (m_last_rtt > 0) {
833 /* set min max values */
834 if (rtt < m_rtt.min_rtt)
836 if (rtt >= m_rtt.max_rtt)
839 /* do average calculation */
840 if (m_rtt.avg_rtt < 0.0)
843 m_rtt.avg_rtt += (rtt - m_rtt.avg_rtt) * avg_factor;
845 /* do jitter calculation */
847 //just use some neutral value at beginning
848 float jitter = std::fabs(rtt - m_last_rtt);
850 if (jitter < m_rtt.jitter_min)
851 m_rtt.jitter_min = jitter;
852 if (jitter >= m_rtt.jitter_max)
853 m_rtt.jitter_max = jitter;
855 if (m_rtt.jitter_avg < 0.0)
856 m_rtt.jitter_avg = jitter;
858 m_rtt.jitter_avg += (jitter - m_rtt.jitter_avg) * avg_factor;
860 if (!profiler_id.empty()) {
861 g_profiler->graphAdd(profiler_id + "_rtt", rtt);
862 g_profiler->graphAdd(profiler_id + "_jitter", jitter);
865 /* save values required for next loop */
869 bool Peer::isTimedOut(float timeout)
871 MutexAutoLock lock(m_exclusive_access_mutex);
872 u64 current_time = porting::getTimeMs();
874 float dtime = CALC_DTIME(m_last_timeout_check,current_time);
875 m_last_timeout_check = current_time;
877 m_timeout_counter += dtime;
879 return m_timeout_counter > timeout;
885 MutexAutoLock usage_lock(m_exclusive_access_mutex);
886 m_pending_deletion = true;
891 PROFILE(std::stringstream peerIdentifier1);
892 PROFILE(peerIdentifier1 << "runTimeouts[" << m_connection->getDesc()
893 << ";" << id << ";RELIABLE]");
894 PROFILE(g_profiler->remove(peerIdentifier1.str()));
895 PROFILE(std::stringstream peerIdentifier2);
896 PROFILE(peerIdentifier2 << "sendPackets[" << m_connection->getDesc()
897 << ";" << id << ";RELIABLE]");
898 PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier2.str(), SPT_AVG));
903 UDPPeer::UDPPeer(u16 a_id, Address a_address, Connection* connection) :
904 Peer(a_address,a_id,connection)
908 bool UDPPeer::getAddress(MTProtocols type,Address& toset)
910 if ((type == MTP_UDP) || (type == MTP_MINETEST_RELIABLE_UDP) || (type == MTP_PRIMARY))
919 void UDPPeer::setNonLegacyPeer()
921 m_legacy_peer = false;
922 for(unsigned int i=0; i< CHANNEL_COUNT; i++)
924 channels[i].setWindowSize(g_settings->getU16("max_packets_per_iteration"));
928 void UDPPeer::reportRTT(float rtt)
932 RTTStatistics(rtt, "rudp");
934 float timeout = getStat(AVG_RTT) * RESEND_TIMEOUT_FACTOR;
935 timeout = rangelim(timeout, RESEND_TIMEOUT_MIN, RESEND_TIMEOUT_MAX);
937 MutexAutoLock usage_lock(m_exclusive_access_mutex);
938 resend_timeout = timeout;
941 bool UDPPeer::Ping(float dtime,SharedBuffer<u8>& data)
943 m_ping_timer += dtime;
944 if (m_ping_timer >= PING_TIMEOUT)
946 // Create and send PING packet
947 writeU8(&data[0], PACKET_TYPE_CONTROL);
948 writeU8(&data[1], CONTROLTYPE_PING);
955 void UDPPeer::PutReliableSendCommand(ConnectionCommand &c,
956 unsigned int max_packet_size)
958 if (m_pending_disconnect)
961 if ( channels[c.channelnum].queued_commands.empty() &&
962 /* don't queue more packets then window size */
963 (channels[c.channelnum].queued_reliables.size()
964 < (channels[c.channelnum].getWindowSize()/2))) {
965 LOG(dout_con<<m_connection->getDesc()
966 <<" processing reliable command for peer id: " << c.peer_id
967 <<" data size: " << c.data.getSize() << std::endl);
968 if (!processReliableSendCommand(c,max_packet_size)) {
969 channels[c.channelnum].queued_commands.push_back(c);
973 LOG(dout_con<<m_connection->getDesc()
974 <<" Queueing reliable command for peer id: " << c.peer_id
975 <<" data size: " << c.data.getSize() <<std::endl);
976 channels[c.channelnum].queued_commands.push_back(c);
980 bool UDPPeer::processReliableSendCommand(
981 ConnectionCommand &c,
982 unsigned int max_packet_size)
984 if (m_pending_disconnect)
987 u32 chunksize_max = max_packet_size
989 - RELIABLE_HEADER_SIZE;
991 sanity_check(c.data.getSize() < MAX_RELIABLE_WINDOW_SIZE*512);
993 std::list<SharedBuffer<u8>> originals;
994 u16 split_sequence_number = channels[c.channelnum].readNextSplitSeqNum();
997 originals.emplace_back(c.data);
999 makeAutoSplitPacket(c.data, chunksize_max,split_sequence_number, &originals);
1000 channels[c.channelnum].setNextSplitSeqNum(split_sequence_number);
1003 bool have_sequence_number = true;
1004 bool have_initial_sequence_number = false;
1005 std::queue<BufferedPacket> toadd;
1006 volatile u16 initial_sequence_number = 0;
1008 for (SharedBuffer<u8> &original : originals) {
1009 u16 seqnum = channels[c.channelnum].getOutgoingSequenceNumber(have_sequence_number);
1011 /* oops, we don't have enough sequence numbers to send this packet */
1012 if (!have_sequence_number)
1015 if (!have_initial_sequence_number)
1017 initial_sequence_number = seqnum;
1018 have_initial_sequence_number = true;
1021 SharedBuffer<u8> reliable = makeReliablePacket(original, seqnum);
1023 // Add base headers and make a packet
1024 BufferedPacket p = con::makePacket(address, reliable,
1025 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1031 if (have_sequence_number) {
1032 volatile u16 pcount = 0;
1033 while (!toadd.empty()) {
1034 BufferedPacket p = toadd.front();
1036 // LOG(dout_con<<connection->getDesc()
1037 // << " queuing reliable packet for peer_id: " << c.peer_id
1038 // << " channel: " << (c.channelnum&0xFF)
1039 // << " seqnum: " << readU16(&p.data[BASE_HEADER_SIZE+1])
1041 channels[c.channelnum].queued_reliables.push(p);
1044 sanity_check(channels[c.channelnum].queued_reliables.size() < 0xFFFF);
1048 volatile u16 packets_available = toadd.size();
1049 /* we didn't get a single sequence number no need to fill queue */
1050 if (!have_initial_sequence_number) {
1054 while (!toadd.empty()) {
1058 bool successfully_put_back_sequence_number
1059 = channels[c.channelnum].putBackSequenceNumber(
1060 (initial_sequence_number+toadd.size() % (SEQNUM_MAX+1)));
1062 FATAL_ERROR_IF(!successfully_put_back_sequence_number, "error");
1065 LOG(dout_con<<m_connection->getDesc()
1066 << " Windowsize exceeded on reliable sending "
1067 << c.data.getSize() << " bytes"
1068 << std::endl << "\t\tinitial_sequence_number: "
1069 << initial_sequence_number
1070 << std::endl << "\t\tgot at most : "
1071 << packets_available << " packets"
1072 << std::endl << "\t\tpackets queued : "
1073 << channels[c.channelnum].outgoing_reliables_sent.size()
1079 void UDPPeer::RunCommandQueues(
1080 unsigned int max_packet_size,
1081 unsigned int maxcommands,
1082 unsigned int maxtransfer)
1085 for (Channel &channel : channels) {
1086 unsigned int commands_processed = 0;
1088 if ((!channel.queued_commands.empty()) &&
1089 (channel.queued_reliables.size() < maxtransfer) &&
1090 (commands_processed < maxcommands)) {
1092 ConnectionCommand c = channel.queued_commands.front();
1094 LOG(dout_con << m_connection->getDesc()
1095 << " processing queued reliable command " << std::endl);
1097 // Packet is processed, remove it from queue
1098 if (processReliableSendCommand(c,max_packet_size)) {
1099 channel.queued_commands.pop_front();
1101 LOG(dout_con << m_connection->getDesc()
1102 << " Failed to queue packets for peer_id: " << c.peer_id
1103 << ", delaying sending of " << c.data.getSize()
1104 << " bytes" << std::endl);
1107 catch (ItemNotFoundException &e) {
1108 // intentionally empty
1114 u16 UDPPeer::getNextSplitSequenceNumber(u8 channel)
1116 assert(channel < CHANNEL_COUNT); // Pre-condition
1117 return channels[channel].readNextSplitSeqNum();
1120 void UDPPeer::setNextSplitSequenceNumber(u8 channel, u16 seqnum)
1122 assert(channel < CHANNEL_COUNT); // Pre-condition
1123 channels[channel].setNextSplitSeqNum(seqnum);
1126 SharedBuffer<u8> UDPPeer::addSplitPacket(u8 channel, const BufferedPacket &toadd,
1129 assert(channel < CHANNEL_COUNT); // Pre-condition
1130 return channels[channel].incoming_splits.insert(toadd, reliable);
1137 Connection::Connection(u32 protocol_id, u32 max_packet_size, float timeout,
1138 bool ipv6, PeerHandler *peerhandler) :
1140 m_protocol_id(protocol_id),
1141 m_sendThread(new ConnectionSendThread(max_packet_size, timeout)),
1142 m_receiveThread(new ConnectionReceiveThread(max_packet_size)),
1143 m_bc_peerhandler(peerhandler)
1146 m_udpSocket.setTimeoutMs(5);
1148 m_sendThread->setParent(this);
1149 m_receiveThread->setParent(this);
1151 m_sendThread->start();
1152 m_receiveThread->start();
1156 Connection::~Connection()
1158 m_shutting_down = true;
1159 // request threads to stop
1160 m_sendThread->stop();
1161 m_receiveThread->stop();
1163 //TODO for some unkonwn reason send/receive threads do not exit as they're
1164 // supposed to be but wait on peer timeout. To speed up shutdown we reduce
1165 // timeout to half a second.
1166 m_sendThread->setPeerTimeout(0.5);
1168 // wait for threads to finish
1169 m_sendThread->wait();
1170 m_receiveThread->wait();
1173 for (auto &peer : m_peers) {
1178 /* Internal stuff */
1179 void Connection::putEvent(ConnectionEvent &e)
1181 assert(e.type != CONNEVENT_NONE); // Pre-condition
1182 m_event_queue.push_back(e);
1185 void Connection::TriggerSend()
1187 m_sendThread->Trigger();
1190 PeerHelper Connection::getPeerNoEx(session_t peer_id)
1192 MutexAutoLock peerlock(m_peers_mutex);
1193 std::map<session_t, Peer *>::iterator node = m_peers.find(peer_id);
1195 if (node == m_peers.end()) {
1196 return PeerHelper(NULL);
1200 FATAL_ERROR_IF(node->second->id != peer_id, "Invalid peer id");
1202 return PeerHelper(node->second);
1205 /* find peer_id for address */
1206 u16 Connection::lookupPeer(Address& sender)
1208 MutexAutoLock peerlock(m_peers_mutex);
1209 std::map<u16, Peer*>::iterator j;
1210 j = m_peers.begin();
1211 for(; j != m_peers.end(); ++j)
1213 Peer *peer = j->second;
1214 if (peer->isPendingDeletion())
1219 if ((peer->getAddress(MTP_MINETEST_RELIABLE_UDP, tocheck)) && (tocheck == sender))
1222 if ((peer->getAddress(MTP_UDP, tocheck)) && (tocheck == sender))
1226 return PEER_ID_INEXISTENT;
1229 bool Connection::deletePeer(session_t peer_id, bool timeout)
1233 /* lock list as short as possible */
1235 MutexAutoLock peerlock(m_peers_mutex);
1236 if (m_peers.find(peer_id) == m_peers.end())
1238 peer = m_peers[peer_id];
1239 m_peers.erase(peer_id);
1240 m_peer_ids.remove(peer_id);
1243 Address peer_address;
1244 //any peer has a primary address this never fails!
1245 peer->getAddress(MTP_PRIMARY, peer_address);
1248 e.peerRemoved(peer_id, timeout, peer_address);
1258 ConnectionEvent Connection::waitEvent(u32 timeout_ms)
1261 return m_event_queue.pop_front(timeout_ms);
1262 } catch(ItemNotFoundException &ex) {
1264 e.type = CONNEVENT_NONE;
1269 void Connection::putCommand(ConnectionCommand &c)
1271 if (!m_shutting_down) {
1272 m_command_queue.push_back(c);
1273 m_sendThread->Trigger();
1277 void Connection::Serve(Address bind_addr)
1279 ConnectionCommand c;
1284 void Connection::Connect(Address address)
1286 ConnectionCommand c;
1291 bool Connection::Connected()
1293 MutexAutoLock peerlock(m_peers_mutex);
1295 if (m_peers.size() != 1)
1298 std::map<session_t, Peer *>::iterator node = m_peers.find(PEER_ID_SERVER);
1299 if (node == m_peers.end())
1302 if (m_peer_id == PEER_ID_INEXISTENT)
1308 void Connection::Disconnect()
1310 ConnectionCommand c;
1315 void Connection::Receive(NetworkPacket* pkt)
1318 ConnectionEvent e = waitEvent(m_bc_receive_timeout);
1319 if (e.type != CONNEVENT_NONE)
1320 LOG(dout_con << getDesc() << ": Receive: got event: "
1321 << e.describe() << std::endl);
1323 case CONNEVENT_NONE:
1324 throw NoIncomingDataException("No incoming data");
1325 case CONNEVENT_DATA_RECEIVED:
1326 // Data size is lesser than command size, ignoring packet
1327 if (e.data.getSize() < 2) {
1331 pkt->putRawPacket(*e.data, e.data.getSize(), e.peer_id);
1333 case CONNEVENT_PEER_ADDED: {
1334 UDPPeer tmp(e.peer_id, e.address, this);
1335 if (m_bc_peerhandler)
1336 m_bc_peerhandler->peerAdded(&tmp);
1339 case CONNEVENT_PEER_REMOVED: {
1340 UDPPeer tmp(e.peer_id, e.address, this);
1341 if (m_bc_peerhandler)
1342 m_bc_peerhandler->deletingPeer(&tmp, e.timeout);
1345 case CONNEVENT_BIND_FAILED:
1346 throw ConnectionBindFailed("Failed to bind socket "
1347 "(port already in use?)");
1350 throw NoIncomingDataException("No incoming data");
1353 void Connection::Send(session_t peer_id, u8 channelnum,
1354 NetworkPacket *pkt, bool reliable)
1356 assert(channelnum < CHANNEL_COUNT); // Pre-condition
1358 ConnectionCommand c;
1360 c.send(peer_id, channelnum, pkt, reliable);
1364 Address Connection::GetPeerAddress(session_t peer_id)
1366 PeerHelper peer = getPeerNoEx(peer_id);
1369 throw PeerNotFoundException("No address for peer found!");
1370 Address peer_address;
1371 peer->getAddress(MTP_PRIMARY, peer_address);
1372 return peer_address;
1375 float Connection::getPeerStat(session_t peer_id, rtt_stat_type type)
1377 PeerHelper peer = getPeerNoEx(peer_id);
1378 if (!peer) return -1;
1379 return peer->getStat(type);
1382 float Connection::getLocalStat(rate_stat_type type)
1384 PeerHelper peer = getPeerNoEx(PEER_ID_SERVER);
1386 FATAL_ERROR_IF(!peer, "Connection::getLocalStat we couldn't get our own peer? are you serious???");
1390 for (Channel &channel : dynamic_cast<UDPPeer *>(&peer)->channels) {
1393 retval += channel.getCurrentDownloadRateKB();
1396 retval += channel.getAvgDownloadRateKB();
1399 retval += channel.getCurrentIncomingRateKB();
1402 retval += channel.getAvgIncomingRateKB();
1405 retval += channel.getAvgLossRateKB();
1408 retval += channel.getCurrentLossRateKB();
1411 FATAL_ERROR("Connection::getLocalStat Invalid stat type");
1417 u16 Connection::createPeer(Address& sender, MTProtocols protocol, int fd)
1419 // Somebody wants to make a new connection
1421 // Get a unique peer id (2 or higher)
1422 session_t peer_id_new = m_next_remote_peer_id;
1423 u16 overflow = MAX_UDP_PEERS;
1426 Find an unused peer id
1428 MutexAutoLock lock(m_peers_mutex);
1429 bool out_of_ids = false;
1432 if (m_peers.find(peer_id_new) == m_peers.end())
1435 // Check for overflow
1436 if (peer_id_new == overflow) {
1444 errorstream << getDesc() << " ran out of peer ids" << std::endl;
1445 return PEER_ID_INEXISTENT;
1450 peer = new UDPPeer(peer_id_new, sender, this);
1452 m_peers[peer->id] = peer;
1453 m_peer_ids.push_back(peer->id);
1455 m_next_remote_peer_id = (peer_id_new +1 ) % MAX_UDP_PEERS;
1457 LOG(dout_con << getDesc()
1458 << "createPeer(): giving peer_id=" << peer_id_new << std::endl);
1460 ConnectionCommand cmd;
1461 SharedBuffer<u8> reply(4);
1462 writeU8(&reply[0], PACKET_TYPE_CONTROL);
1463 writeU8(&reply[1], CONTROLTYPE_SET_PEER_ID);
1464 writeU16(&reply[2], peer_id_new);
1465 cmd.createPeer(peer_id_new,reply);
1468 // Create peer addition event
1470 e.peerAdded(peer_id_new, sender);
1473 // We're now talking to a valid peer_id
1477 void Connection::PrintInfo(std::ostream &out)
1479 m_info_mutex.lock();
1480 out<<getDesc()<<": ";
1481 m_info_mutex.unlock();
1484 const std::string Connection::getDesc()
1486 return std::string("con(")+
1487 itos(m_udpSocket.GetHandle())+"/"+itos(m_peer_id)+")";
1490 void Connection::DisconnectPeer(session_t peer_id)
1492 ConnectionCommand discon;
1493 discon.disconnect_peer(peer_id);
1497 void Connection::sendAck(session_t peer_id, u8 channelnum, u16 seqnum)
1499 assert(channelnum < CHANNEL_COUNT); // Pre-condition
1501 LOG(dout_con<<getDesc()
1502 <<" Queuing ACK command to peer_id: " << peer_id <<
1503 " channel: " << (channelnum & 0xFF) <<
1504 " seqnum: " << seqnum << std::endl);
1506 ConnectionCommand c;
1507 SharedBuffer<u8> ack(4);
1508 writeU8(&ack[0], PACKET_TYPE_CONTROL);
1509 writeU8(&ack[1], CONTROLTYPE_ACK);
1510 writeU16(&ack[2], seqnum);
1512 c.ack(peer_id, channelnum, ack);
1514 m_sendThread->Trigger();
1517 UDPPeer* Connection::createServerPeer(Address& address)
1519 if (getPeerNoEx(PEER_ID_SERVER) != 0)
1521 throw ConnectionException("Already connected to a server");
1524 UDPPeer *peer = new UDPPeer(PEER_ID_SERVER, address, this);
1527 MutexAutoLock lock(m_peers_mutex);
1528 m_peers[peer->id] = peer;
1529 m_peer_ids.push_back(peer->id);