3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 #include "connection.h"
25 #include "serialization.h"
28 #include "network/connectionthreads.h"
29 #include "network/networkpacket.h"
30 #include "network/peerhandler.h"
31 #include "util/serialize.h"
32 #include "util/numeric.h"
33 #include "util/string.h"
40 /******************************************************************************/
41 /* defines used for debugging and profiling */
42 /******************************************************************************/
47 /* this mutex is used to achieve log message consistency */
48 std::mutex log_message_mutex;
51 MutexAutoLock loglock(log_message_mutex); \
57 #define PING_TIMEOUT 5.0
59 BufferedPacket makePacket(Address &address, const SharedBuffer<u8> &data,
60 u32 protocol_id, session_t sender_peer_id, u8 channel)
62 u32 packet_size = data.getSize() + BASE_HEADER_SIZE;
63 BufferedPacket p(packet_size);
66 writeU32(&p.data[0], protocol_id);
67 writeU16(&p.data[4], sender_peer_id);
68 writeU8(&p.data[6], channel);
70 memcpy(&p.data[BASE_HEADER_SIZE], *data, data.getSize());
75 SharedBuffer<u8> makeOriginalPacket(const SharedBuffer<u8> &data)
78 u32 packet_size = data.getSize() + header_size;
79 SharedBuffer<u8> b(packet_size);
81 writeU8(&(b[0]), PACKET_TYPE_ORIGINAL);
82 if (data.getSize() > 0) {
83 memcpy(&(b[header_size]), *data, data.getSize());
88 // Split data in chunks and add TYPE_SPLIT headers to them
89 void makeSplitPacket(const SharedBuffer<u8> &data, u32 chunksize_max, u16 seqnum,
90 std::list<SharedBuffer<u8>> *chunks)
92 // Chunk packets, containing the TYPE_SPLIT header
93 u32 chunk_header_size = 7;
94 u32 maximum_data_size = chunksize_max - chunk_header_size;
100 end = start + maximum_data_size - 1;
101 if (end > data.getSize() - 1)
102 end = data.getSize() - 1;
104 u32 payload_size = end - start + 1;
105 u32 packet_size = chunk_header_size + payload_size;
107 SharedBuffer<u8> chunk(packet_size);
109 writeU8(&chunk[0], PACKET_TYPE_SPLIT);
110 writeU16(&chunk[1], seqnum);
111 // [3] u16 chunk_count is written at next stage
112 writeU16(&chunk[5], chunk_num);
113 memcpy(&chunk[chunk_header_size], &data[start], payload_size);
115 chunks->push_back(chunk);
121 while (end != data.getSize() - 1);
123 for (SharedBuffer<u8> &chunk : *chunks) {
125 writeU16(&(chunk[3]), chunk_count);
129 void makeAutoSplitPacket(const SharedBuffer<u8> &data, u32 chunksize_max,
130 u16 &split_seqnum, std::list<SharedBuffer<u8>> *list)
132 u32 original_header_size = 1;
134 if (data.getSize() + original_header_size > chunksize_max) {
135 makeSplitPacket(data, chunksize_max, split_seqnum, list);
140 list->push_back(makeOriginalPacket(data));
143 SharedBuffer<u8> makeReliablePacket(const SharedBuffer<u8> &data, u16 seqnum)
146 u32 packet_size = data.getSize() + header_size;
147 SharedBuffer<u8> b(packet_size);
149 writeU8(&b[0], PACKET_TYPE_RELIABLE);
150 writeU16(&b[1], seqnum);
152 memcpy(&b[header_size], *data, data.getSize());
161 void ReliablePacketBuffer::print()
163 MutexAutoLock listlock(m_list_mutex);
164 LOG(dout_con<<"Dump of ReliablePacketBuffer:" << std::endl);
165 unsigned int index = 0;
166 for (BufferedPacket &bufferedPacket : m_list) {
167 u16 s = readU16(&(bufferedPacket.data[BASE_HEADER_SIZE+1]));
168 LOG(dout_con<<index<< ":" << s << std::endl);
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,
813 unsigned int num_samples) {
815 if (m_last_rtt > 0) {
816 /* set min max values */
817 if (rtt < m_rtt.min_rtt)
819 if (rtt >= m_rtt.max_rtt)
822 /* do average calculation */
823 if (m_rtt.avg_rtt < 0.0)
826 m_rtt.avg_rtt = m_rtt.avg_rtt * (num_samples/(num_samples-1)) +
827 rtt * (1/num_samples);
829 /* do jitter calculation */
831 //just use some neutral value at beginning
832 float jitter = m_rtt.jitter_min;
834 if (rtt > m_last_rtt)
835 jitter = rtt-m_last_rtt;
837 if (rtt <= m_last_rtt)
838 jitter = m_last_rtt - rtt;
840 if (jitter < m_rtt.jitter_min)
841 m_rtt.jitter_min = jitter;
842 if (jitter >= m_rtt.jitter_max)
843 m_rtt.jitter_max = jitter;
845 if (m_rtt.jitter_avg < 0.0)
846 m_rtt.jitter_avg = jitter;
848 m_rtt.jitter_avg = m_rtt.jitter_avg * (num_samples/(num_samples-1)) +
849 jitter * (1/num_samples);
851 if (!profiler_id.empty()) {
852 g_profiler->graphAdd(profiler_id + "_rtt", rtt);
853 g_profiler->graphAdd(profiler_id + "_jitter", jitter);
856 /* save values required for next loop */
860 bool Peer::isTimedOut(float timeout)
862 MutexAutoLock lock(m_exclusive_access_mutex);
863 u64 current_time = porting::getTimeMs();
865 float dtime = CALC_DTIME(m_last_timeout_check,current_time);
866 m_last_timeout_check = current_time;
868 m_timeout_counter += dtime;
870 return m_timeout_counter > timeout;
876 MutexAutoLock usage_lock(m_exclusive_access_mutex);
877 m_pending_deletion = true;
882 PROFILE(std::stringstream peerIdentifier1);
883 PROFILE(peerIdentifier1 << "runTimeouts[" << m_connection->getDesc()
884 << ";" << id << ";RELIABLE]");
885 PROFILE(g_profiler->remove(peerIdentifier1.str()));
886 PROFILE(std::stringstream peerIdentifier2);
887 PROFILE(peerIdentifier2 << "sendPackets[" << m_connection->getDesc()
888 << ";" << id << ";RELIABLE]");
889 PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier2.str(), SPT_AVG));
894 UDPPeer::UDPPeer(u16 a_id, Address a_address, Connection* connection) :
895 Peer(a_address,a_id,connection)
897 for (Channel &channel : channels)
898 channel.setWindowSize(g_settings->getU16("max_packets_per_iteration"));
901 bool UDPPeer::getAddress(MTProtocols type,Address& toset)
903 if ((type == MTP_UDP) || (type == MTP_MINETEST_RELIABLE_UDP) || (type == MTP_PRIMARY))
912 void UDPPeer::reportRTT(float rtt)
917 RTTStatistics(rtt,"rudp",MAX_RELIABLE_WINDOW_SIZE*10);
919 float timeout = getStat(AVG_RTT) * RESEND_TIMEOUT_FACTOR;
920 if (timeout < RESEND_TIMEOUT_MIN)
921 timeout = RESEND_TIMEOUT_MIN;
922 if (timeout > RESEND_TIMEOUT_MAX)
923 timeout = RESEND_TIMEOUT_MAX;
925 MutexAutoLock usage_lock(m_exclusive_access_mutex);
926 resend_timeout = timeout;
929 bool UDPPeer::Ping(float dtime,SharedBuffer<u8>& data)
931 m_ping_timer += dtime;
932 if (m_ping_timer >= PING_TIMEOUT)
934 // Create and send PING packet
935 writeU8(&data[0], PACKET_TYPE_CONTROL);
936 writeU8(&data[1], CONTROLTYPE_PING);
943 void UDPPeer::PutReliableSendCommand(ConnectionCommand &c,
944 unsigned int max_packet_size)
946 if (m_pending_disconnect)
949 if ( channels[c.channelnum].queued_commands.empty() &&
950 /* don't queue more packets then window size */
951 (channels[c.channelnum].queued_reliables.size()
952 < (channels[c.channelnum].getWindowSize()/2))) {
953 LOG(dout_con<<m_connection->getDesc()
954 <<" processing reliable command for peer id: " << c.peer_id
955 <<" data size: " << c.data.getSize() << std::endl);
956 if (!processReliableSendCommand(c,max_packet_size)) {
957 channels[c.channelnum].queued_commands.push_back(c);
961 LOG(dout_con<<m_connection->getDesc()
962 <<" Queueing reliable command for peer id: " << c.peer_id
963 <<" data size: " << c.data.getSize() <<std::endl);
964 channels[c.channelnum].queued_commands.push_back(c);
968 bool UDPPeer::processReliableSendCommand(
969 ConnectionCommand &c,
970 unsigned int max_packet_size)
972 if (m_pending_disconnect)
975 u32 chunksize_max = max_packet_size
977 - RELIABLE_HEADER_SIZE;
979 sanity_check(c.data.getSize() < MAX_RELIABLE_WINDOW_SIZE*512);
981 std::list<SharedBuffer<u8>> originals;
982 u16 split_sequence_number = channels[c.channelnum].readNextSplitSeqNum();
985 originals.emplace_back(c.data);
987 makeAutoSplitPacket(c.data, chunksize_max,split_sequence_number, &originals);
988 channels[c.channelnum].setNextSplitSeqNum(split_sequence_number);
991 bool have_sequence_number = true;
992 bool have_initial_sequence_number = false;
993 std::queue<BufferedPacket> toadd;
994 volatile u16 initial_sequence_number = 0;
996 for (SharedBuffer<u8> &original : originals) {
997 u16 seqnum = channels[c.channelnum].getOutgoingSequenceNumber(have_sequence_number);
999 /* oops, we don't have enough sequence numbers to send this packet */
1000 if (!have_sequence_number)
1003 if (!have_initial_sequence_number)
1005 initial_sequence_number = seqnum;
1006 have_initial_sequence_number = true;
1009 SharedBuffer<u8> reliable = makeReliablePacket(original, seqnum);
1011 // Add base headers and make a packet
1012 BufferedPacket p = con::makePacket(address, reliable,
1013 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1019 if (have_sequence_number) {
1020 volatile u16 pcount = 0;
1021 while (!toadd.empty()) {
1022 BufferedPacket p = toadd.front();
1024 // LOG(dout_con<<connection->getDesc()
1025 // << " queuing reliable packet for peer_id: " << c.peer_id
1026 // << " channel: " << (c.channelnum&0xFF)
1027 // << " seqnum: " << readU16(&p.data[BASE_HEADER_SIZE+1])
1029 channels[c.channelnum].queued_reliables.push(p);
1032 sanity_check(channels[c.channelnum].queued_reliables.size() < 0xFFFF);
1036 volatile u16 packets_available = toadd.size();
1037 /* we didn't get a single sequence number no need to fill queue */
1038 if (!have_initial_sequence_number) {
1042 while (!toadd.empty()) {
1046 bool successfully_put_back_sequence_number
1047 = channels[c.channelnum].putBackSequenceNumber(
1048 (initial_sequence_number+toadd.size() % (SEQNUM_MAX+1)));
1050 FATAL_ERROR_IF(!successfully_put_back_sequence_number, "error");
1053 LOG(dout_con<<m_connection->getDesc()
1054 << " Windowsize exceeded on reliable sending "
1055 << c.data.getSize() << " bytes"
1056 << std::endl << "\t\tinitial_sequence_number: "
1057 << initial_sequence_number
1058 << std::endl << "\t\tgot at most : "
1059 << packets_available << " packets"
1060 << std::endl << "\t\tpackets queued : "
1061 << channels[c.channelnum].outgoing_reliables_sent.size()
1067 void UDPPeer::RunCommandQueues(
1068 unsigned int max_packet_size,
1069 unsigned int maxcommands,
1070 unsigned int maxtransfer)
1073 for (Channel &channel : channels) {
1074 unsigned int commands_processed = 0;
1076 if ((!channel.queued_commands.empty()) &&
1077 (channel.queued_reliables.size() < maxtransfer) &&
1078 (commands_processed < maxcommands)) {
1080 ConnectionCommand c = channel.queued_commands.front();
1082 LOG(dout_con << m_connection->getDesc()
1083 << " processing queued reliable command " << std::endl);
1085 // Packet is processed, remove it from queue
1086 if (processReliableSendCommand(c,max_packet_size)) {
1087 channel.queued_commands.pop_front();
1089 LOG(dout_con << m_connection->getDesc()
1090 << " Failed to queue packets for peer_id: " << c.peer_id
1091 << ", delaying sending of " << c.data.getSize()
1092 << " bytes" << std::endl);
1095 catch (ItemNotFoundException &e) {
1096 // intentionally empty
1102 u16 UDPPeer::getNextSplitSequenceNumber(u8 channel)
1104 assert(channel < CHANNEL_COUNT); // Pre-condition
1105 return channels[channel].readNextSplitSeqNum();
1108 void UDPPeer::setNextSplitSequenceNumber(u8 channel, u16 seqnum)
1110 assert(channel < CHANNEL_COUNT); // Pre-condition
1111 channels[channel].setNextSplitSeqNum(seqnum);
1114 SharedBuffer<u8> UDPPeer::addSplitPacket(u8 channel, const BufferedPacket &toadd,
1117 assert(channel < CHANNEL_COUNT); // Pre-condition
1118 return channels[channel].incoming_splits.insert(toadd, reliable);
1125 Connection::Connection(u32 protocol_id, u32 max_packet_size, float timeout,
1126 bool ipv6, PeerHandler *peerhandler) :
1128 m_protocol_id(protocol_id),
1129 m_sendThread(new ConnectionSendThread(max_packet_size, timeout)),
1130 m_receiveThread(new ConnectionReceiveThread(max_packet_size)),
1131 m_bc_peerhandler(peerhandler)
1134 m_udpSocket.setTimeoutMs(5);
1136 m_sendThread->setParent(this);
1137 m_receiveThread->setParent(this);
1139 m_sendThread->start();
1140 m_receiveThread->start();
1144 Connection::~Connection()
1146 m_shutting_down = true;
1147 // request threads to stop
1148 m_sendThread->stop();
1149 m_receiveThread->stop();
1151 //TODO for some unkonwn reason send/receive threads do not exit as they're
1152 // supposed to be but wait on peer timeout. To speed up shutdown we reduce
1153 // timeout to half a second.
1154 m_sendThread->setPeerTimeout(0.5);
1156 // wait for threads to finish
1157 m_sendThread->wait();
1158 m_receiveThread->wait();
1161 for (auto &peer : m_peers) {
1166 /* Internal stuff */
1167 void Connection::putEvent(ConnectionEvent &e)
1169 assert(e.type != CONNEVENT_NONE); // Pre-condition
1170 m_event_queue.push_back(e);
1173 void Connection::TriggerSend()
1175 m_sendThread->Trigger();
1178 PeerHelper Connection::getPeerNoEx(session_t peer_id)
1180 MutexAutoLock peerlock(m_peers_mutex);
1181 std::map<session_t, Peer *>::iterator node = m_peers.find(peer_id);
1183 if (node == m_peers.end()) {
1184 return PeerHelper(NULL);
1188 FATAL_ERROR_IF(node->second->id != peer_id, "Invalid peer id");
1190 return PeerHelper(node->second);
1193 /* find peer_id for address */
1194 u16 Connection::lookupPeer(Address& sender)
1196 MutexAutoLock peerlock(m_peers_mutex);
1197 std::map<u16, Peer*>::iterator j;
1198 j = m_peers.begin();
1199 for(; j != m_peers.end(); ++j)
1201 Peer *peer = j->second;
1202 if (peer->isPendingDeletion())
1207 if ((peer->getAddress(MTP_MINETEST_RELIABLE_UDP, tocheck)) && (tocheck == sender))
1210 if ((peer->getAddress(MTP_UDP, tocheck)) && (tocheck == sender))
1214 return PEER_ID_INEXISTENT;
1217 bool Connection::deletePeer(session_t peer_id, bool timeout)
1221 /* lock list as short as possible */
1223 MutexAutoLock peerlock(m_peers_mutex);
1224 if (m_peers.find(peer_id) == m_peers.end())
1226 peer = m_peers[peer_id];
1227 m_peers.erase(peer_id);
1228 m_peer_ids.remove(peer_id);
1231 Address peer_address;
1232 //any peer has a primary address this never fails!
1233 peer->getAddress(MTP_PRIMARY, peer_address);
1236 e.peerRemoved(peer_id, timeout, peer_address);
1246 ConnectionEvent Connection::waitEvent(u32 timeout_ms)
1249 return m_event_queue.pop_front(timeout_ms);
1250 } catch(ItemNotFoundException &ex) {
1252 e.type = CONNEVENT_NONE;
1257 void Connection::putCommand(ConnectionCommand &c)
1259 if (!m_shutting_down) {
1260 m_command_queue.push_back(c);
1261 m_sendThread->Trigger();
1265 void Connection::Serve(Address bind_addr)
1267 ConnectionCommand c;
1272 void Connection::Connect(Address address)
1274 ConnectionCommand c;
1279 bool Connection::Connected()
1281 MutexAutoLock peerlock(m_peers_mutex);
1283 if (m_peers.size() != 1)
1286 std::map<session_t, Peer *>::iterator node = m_peers.find(PEER_ID_SERVER);
1287 if (node == m_peers.end())
1290 if (m_peer_id == PEER_ID_INEXISTENT)
1296 void Connection::Disconnect()
1298 ConnectionCommand c;
1303 void Connection::Receive(NetworkPacket* pkt)
1306 ConnectionEvent e = waitEvent(m_bc_receive_timeout);
1307 if (e.type != CONNEVENT_NONE)
1308 LOG(dout_con << getDesc() << ": Receive: got event: "
1309 << e.describe() << std::endl);
1311 case CONNEVENT_NONE:
1312 throw NoIncomingDataException("No incoming data");
1313 case CONNEVENT_DATA_RECEIVED:
1314 // Data size is lesser than command size, ignoring packet
1315 if (e.data.getSize() < 2) {
1319 pkt->putRawPacket(*e.data, e.data.getSize(), e.peer_id);
1321 case CONNEVENT_PEER_ADDED: {
1322 UDPPeer tmp(e.peer_id, e.address, this);
1323 if (m_bc_peerhandler)
1324 m_bc_peerhandler->peerAdded(&tmp);
1327 case CONNEVENT_PEER_REMOVED: {
1328 UDPPeer tmp(e.peer_id, e.address, this);
1329 if (m_bc_peerhandler)
1330 m_bc_peerhandler->deletingPeer(&tmp, e.timeout);
1333 case CONNEVENT_BIND_FAILED:
1334 throw ConnectionBindFailed("Failed to bind socket "
1335 "(port already in use?)");
1338 throw NoIncomingDataException("No incoming data");
1341 void Connection::Send(session_t peer_id, u8 channelnum,
1342 NetworkPacket *pkt, bool reliable)
1344 assert(channelnum < CHANNEL_COUNT); // Pre-condition
1346 ConnectionCommand c;
1348 c.send(peer_id, channelnum, pkt, reliable);
1352 Address Connection::GetPeerAddress(session_t peer_id)
1354 PeerHelper peer = getPeerNoEx(peer_id);
1357 throw PeerNotFoundException("No address for peer found!");
1358 Address peer_address;
1359 peer->getAddress(MTP_PRIMARY, peer_address);
1360 return peer_address;
1363 float Connection::getPeerStat(session_t peer_id, rtt_stat_type type)
1365 PeerHelper peer = getPeerNoEx(peer_id);
1366 if (!peer) return -1;
1367 return peer->getStat(type);
1370 float Connection::getLocalStat(rate_stat_type type)
1372 PeerHelper peer = getPeerNoEx(PEER_ID_SERVER);
1374 FATAL_ERROR_IF(!peer, "Connection::getLocalStat we couldn't get our own peer? are you serious???");
1378 for (Channel &channel : dynamic_cast<UDPPeer *>(&peer)->channels) {
1381 retval += channel.getCurrentDownloadRateKB();
1384 retval += channel.getAvgDownloadRateKB();
1387 retval += channel.getCurrentIncomingRateKB();
1390 retval += channel.getAvgIncomingRateKB();
1393 retval += channel.getAvgLossRateKB();
1396 retval += channel.getCurrentLossRateKB();
1399 FATAL_ERROR("Connection::getLocalStat Invalid stat type");
1405 u16 Connection::createPeer(Address& sender, MTProtocols protocol, int fd)
1407 // Somebody wants to make a new connection
1409 // Get a unique peer id (2 or higher)
1410 session_t peer_id_new = m_next_remote_peer_id;
1411 u16 overflow = MAX_UDP_PEERS;
1414 Find an unused peer id
1416 MutexAutoLock lock(m_peers_mutex);
1417 bool out_of_ids = false;
1420 if (m_peers.find(peer_id_new) == m_peers.end())
1423 // Check for overflow
1424 if (peer_id_new == overflow) {
1432 errorstream << getDesc() << " ran out of peer ids" << std::endl;
1433 return PEER_ID_INEXISTENT;
1438 peer = new UDPPeer(peer_id_new, sender, this);
1440 m_peers[peer->id] = peer;
1441 m_peer_ids.push_back(peer->id);
1443 m_next_remote_peer_id = (peer_id_new +1 ) % MAX_UDP_PEERS;
1445 LOG(dout_con << getDesc()
1446 << "createPeer(): giving peer_id=" << peer_id_new << std::endl);
1448 ConnectionCommand cmd;
1449 SharedBuffer<u8> reply(4);
1450 writeU8(&reply[0], PACKET_TYPE_CONTROL);
1451 writeU8(&reply[1], CONTROLTYPE_SET_PEER_ID);
1452 writeU16(&reply[2], peer_id_new);
1453 cmd.createPeer(peer_id_new,reply);
1456 // Create peer addition event
1458 e.peerAdded(peer_id_new, sender);
1461 // We're now talking to a valid peer_id
1465 void Connection::PrintInfo(std::ostream &out)
1467 m_info_mutex.lock();
1468 out<<getDesc()<<": ";
1469 m_info_mutex.unlock();
1472 const std::string Connection::getDesc()
1474 return std::string("con(")+
1475 itos(m_udpSocket.GetHandle())+"/"+itos(m_peer_id)+")";
1478 void Connection::DisconnectPeer(session_t peer_id)
1480 ConnectionCommand discon;
1481 discon.disconnect_peer(peer_id);
1485 void Connection::sendAck(session_t peer_id, u8 channelnum, u16 seqnum)
1487 assert(channelnum < CHANNEL_COUNT); // Pre-condition
1489 LOG(dout_con<<getDesc()
1490 <<" Queuing ACK command to peer_id: " << peer_id <<
1491 " channel: " << (channelnum & 0xFF) <<
1492 " seqnum: " << seqnum << std::endl);
1494 ConnectionCommand c;
1495 SharedBuffer<u8> ack(4);
1496 writeU8(&ack[0], PACKET_TYPE_CONTROL);
1497 writeU8(&ack[1], CONTROLTYPE_ACK);
1498 writeU16(&ack[2], seqnum);
1500 c.ack(peer_id, channelnum, ack);
1502 m_sendThread->Trigger();
1505 UDPPeer* Connection::createServerPeer(Address& address)
1507 if (getPeerNoEx(PEER_ID_SERVER) != 0)
1509 throw ConnectionException("Already connected to a server");
1512 UDPPeer *peer = new UDPPeer(PEER_ID_SERVER, address, this);
1515 MutexAutoLock lock(m_peers_mutex);
1516 m_peers[peer->id] = peer;
1517 m_peer_ids.push_back(peer->id);