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.
22 #include "connection.h"
23 #include "serialization.h"
26 #include "network/networkpacket.h"
27 #include "util/serialize.h"
28 #include "util/numeric.h"
29 #include "util/string.h"
36 /******************************************************************************/
37 /* defines used for debugging and profiling */
38 /******************************************************************************/
42 #undef DEBUG_CONNECTION_KBPS
44 /* this mutex is used to achieve log message consistency */
45 Mutex log_message_mutex;
48 MutexAutoLock loglock(log_message_mutex); \
52 //#define DEBUG_CONNECTION_KBPS
53 #undef DEBUG_CONNECTION_KBPS
57 static inline float CALC_DTIME(unsigned int lasttime, unsigned int curtime) {
58 float value = ( curtime - lasttime) / 1000.0;
59 return MYMAX(MYMIN(value,0.1),0.0);
62 /* maximum window size to use, 0xFFFF is theoretical maximum don't think about
63 * touching it, the less you're away from it the more likely data corruption
66 #define MAX_RELIABLE_WINDOW_SIZE 0x8000
67 /* starting value for window size */
68 #define MIN_RELIABLE_WINDOW_SIZE 0x40
70 #define MAX_UDP_PEERS 65535
72 #define PING_TIMEOUT 5.0
74 /* maximum number of retries for reliable packets */
75 #define MAX_RELIABLE_RETRY 5
77 static u16 readPeerId(u8 *packetdata)
79 return readU16(&packetdata[4]);
81 static u8 readChannel(u8 *packetdata)
83 return readU8(&packetdata[6]);
86 BufferedPacket makePacket(Address &address, u8 *data, u32 datasize,
87 u32 protocol_id, u16 sender_peer_id, u8 channel)
89 u32 packet_size = datasize + BASE_HEADER_SIZE;
90 BufferedPacket p(packet_size);
93 writeU32(&p.data[0], protocol_id);
94 writeU16(&p.data[4], sender_peer_id);
95 writeU8(&p.data[6], channel);
97 memcpy(&p.data[BASE_HEADER_SIZE], data, datasize);
102 BufferedPacket makePacket(Address &address, SharedBuffer<u8> &data,
103 u32 protocol_id, u16 sender_peer_id, u8 channel)
105 return makePacket(address, *data, data.getSize(),
106 protocol_id, sender_peer_id, channel);
109 SharedBuffer<u8> makeOriginalPacket(
110 SharedBuffer<u8> data)
113 u32 packet_size = data.getSize() + header_size;
114 SharedBuffer<u8> b(packet_size);
116 writeU8(&(b[0]), TYPE_ORIGINAL);
117 if (data.getSize() > 0) {
118 memcpy(&(b[header_size]), *data, data.getSize());
123 std::list<SharedBuffer<u8> > makeSplitPacket(
124 SharedBuffer<u8> data,
128 // Chunk packets, containing the TYPE_SPLIT header
129 std::list<SharedBuffer<u8> > chunks;
131 u32 chunk_header_size = 7;
132 u32 maximum_data_size = chunksize_max - chunk_header_size;
138 end = start + maximum_data_size - 1;
139 if (end > data.getSize() - 1)
140 end = data.getSize() - 1;
142 u32 payload_size = end - start + 1;
143 u32 packet_size = chunk_header_size + payload_size;
145 SharedBuffer<u8> chunk(packet_size);
147 writeU8(&chunk[0], TYPE_SPLIT);
148 writeU16(&chunk[1], seqnum);
149 // [3] u16 chunk_count is written at next stage
150 writeU16(&chunk[5], chunk_num);
151 memcpy(&chunk[chunk_header_size], &data[start], payload_size);
153 chunks.push_back(chunk);
159 while(end != data.getSize() - 1);
161 for(std::list<SharedBuffer<u8> >::iterator i = chunks.begin();
162 i != chunks.end(); ++i)
165 writeU16(&((*i)[3]), chunk_count);
171 std::list<SharedBuffer<u8> > makeAutoSplitPacket(
172 SharedBuffer<u8> data,
176 u32 original_header_size = 1;
177 std::list<SharedBuffer<u8> > list;
178 if (data.getSize() + original_header_size > chunksize_max)
180 list = makeSplitPacket(data, chunksize_max, split_seqnum);
186 list.push_back(makeOriginalPacket(data));
191 SharedBuffer<u8> makeReliablePacket(
192 SharedBuffer<u8> data,
196 u32 packet_size = data.getSize() + header_size;
197 SharedBuffer<u8> b(packet_size);
199 writeU8(&b[0], TYPE_RELIABLE);
200 writeU16(&b[1], seqnum);
202 memcpy(&b[header_size], *data, data.getSize());
211 ReliablePacketBuffer::ReliablePacketBuffer(): m_list_size(0) {}
213 void ReliablePacketBuffer::print()
215 MutexAutoLock listlock(m_list_mutex);
216 LOG(dout_con<<"Dump of ReliablePacketBuffer:" << std::endl);
217 unsigned int index = 0;
218 for(std::list<BufferedPacket>::iterator i = m_list.begin();
222 u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
223 LOG(dout_con<<index<< ":" << s << std::endl);
227 bool ReliablePacketBuffer::empty()
229 MutexAutoLock listlock(m_list_mutex);
230 return m_list.empty();
233 u32 ReliablePacketBuffer::size()
238 bool ReliablePacketBuffer::containsPacket(u16 seqnum)
240 return !(findPacket(seqnum) == m_list.end());
243 RPBSearchResult ReliablePacketBuffer::findPacket(u16 seqnum)
245 std::list<BufferedPacket>::iterator i = m_list.begin();
246 for(; i != m_list.end(); ++i)
248 u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
249 /*dout_con<<"findPacket(): finding seqnum="<<seqnum
250 <<", comparing to s="<<s<<std::endl;*/
256 RPBSearchResult ReliablePacketBuffer::notFound()
260 bool ReliablePacketBuffer::getFirstSeqnum(u16& result)
262 MutexAutoLock listlock(m_list_mutex);
265 BufferedPacket p = *m_list.begin();
266 result = readU16(&p.data[BASE_HEADER_SIZE+1]);
270 BufferedPacket ReliablePacketBuffer::popFirst()
272 MutexAutoLock listlock(m_list_mutex);
274 throw NotFoundException("Buffer is empty");
275 BufferedPacket p = *m_list.begin();
276 m_list.erase(m_list.begin());
279 if (m_list_size == 0) {
280 m_oldest_non_answered_ack = 0;
282 m_oldest_non_answered_ack =
283 readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]);
287 BufferedPacket ReliablePacketBuffer::popSeqnum(u16 seqnum)
289 MutexAutoLock listlock(m_list_mutex);
290 RPBSearchResult r = findPacket(seqnum);
291 if (r == notFound()) {
292 LOG(dout_con<<"Sequence number: " << seqnum
293 << " not found in reliable buffer"<<std::endl);
294 throw NotFoundException("seqnum not found in buffer");
296 BufferedPacket p = *r;
299 RPBSearchResult next = r;
301 if (next != notFound()) {
302 u16 s = readU16(&(next->data[BASE_HEADER_SIZE+1]));
303 m_oldest_non_answered_ack = s;
309 if (m_list_size == 0)
310 { m_oldest_non_answered_ack = 0; }
312 { m_oldest_non_answered_ack = readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]); }
315 void ReliablePacketBuffer::insert(BufferedPacket &p,u16 next_expected)
317 MutexAutoLock listlock(m_list_mutex);
318 if (p.data.getSize() < BASE_HEADER_SIZE + 3) {
319 errorstream << "ReliablePacketBuffer::insert(): Invalid data size for "
320 "reliable packet" << std::endl;
323 u8 type = readU8(&p.data[BASE_HEADER_SIZE + 0]);
324 if (type != TYPE_RELIABLE) {
325 errorstream << "ReliablePacketBuffer::insert(): type is not reliable"
329 u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE + 1]);
331 if (!seqnum_in_window(seqnum, next_expected, MAX_RELIABLE_WINDOW_SIZE)) {
332 errorstream << "ReliablePacketBuffer::insert(): seqnum is outside of "
333 "expected window " << std::endl;
336 if (seqnum == next_expected) {
337 errorstream << "ReliablePacketBuffer::insert(): seqnum is next expected"
343 sanity_check(m_list_size <= SEQNUM_MAX+1); // FIXME: Handle the error?
345 // Find the right place for the packet and insert it there
346 // If list is empty, just add it
350 m_oldest_non_answered_ack = seqnum;
355 // Otherwise find the right place
356 std::list<BufferedPacket>::iterator i = m_list.begin();
357 // Find the first packet in the list which has a higher seqnum
358 u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
360 /* case seqnum is smaller then next_expected seqnum */
361 /* this is true e.g. on wrap around */
362 if (seqnum < next_expected) {
363 while(((s < seqnum) || (s >= next_expected)) && (i != m_list.end())) {
365 if (i != m_list.end())
366 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
369 /* non wrap around case (at least for incoming and next_expected */
372 while(((s < seqnum) && (s >= next_expected)) && (i != m_list.end())) {
374 if (i != m_list.end())
375 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
381 (readU16(&(i->data[BASE_HEADER_SIZE+1])) != seqnum) ||
382 (i->data.getSize() != p.data.getSize()) ||
383 (i->address != p.address)
386 /* if this happens your maximum transfer window may be to big */
388 "Duplicated seqnum %d non matching packet detected:\n",
390 fprintf(stderr, "Old: seqnum: %05d size: %04d, address: %s\n",
391 readU16(&(i->data[BASE_HEADER_SIZE+1])),i->data.getSize(),
392 i->address.serializeString().c_str());
393 fprintf(stderr, "New: seqnum: %05d size: %04u, address: %s\n",
394 readU16(&(p.data[BASE_HEADER_SIZE+1])),p.data.getSize(),
395 p.address.serializeString().c_str());
396 throw IncomingDataCorruption("duplicated packet isn't same as original one");
399 /* nothing to do this seems to be a resent packet */
400 /* for paranoia reason data should be compared */
403 /* insert or push back */
404 else if (i != m_list.end()) {
411 /* update last packet number */
412 m_oldest_non_answered_ack = readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]);
415 void ReliablePacketBuffer::incrementTimeouts(float dtime)
417 MutexAutoLock listlock(m_list_mutex);
418 for(std::list<BufferedPacket>::iterator i = m_list.begin();
419 i != m_list.end(); ++i)
422 i->totaltime += dtime;
426 std::list<BufferedPacket> ReliablePacketBuffer::getTimedOuts(float timeout,
427 unsigned int max_packets)
429 MutexAutoLock listlock(m_list_mutex);
430 std::list<BufferedPacket> timed_outs;
431 for(std::list<BufferedPacket>::iterator i = m_list.begin();
432 i != m_list.end(); ++i)
434 if (i->time >= timeout) {
435 timed_outs.push_back(*i);
437 //this packet will be sent right afterwards reset timeout here
439 if (timed_outs.size() >= max_packets)
450 IncomingSplitBuffer::~IncomingSplitBuffer()
452 MutexAutoLock listlock(m_map_mutex);
453 for(std::map<u16, IncomingSplitPacket*>::iterator i = m_buf.begin();
454 i != m_buf.end(); ++i)
460 This will throw a GotSplitPacketException when a full
461 split packet is constructed.
463 SharedBuffer<u8> IncomingSplitBuffer::insert(BufferedPacket &p, bool reliable)
465 MutexAutoLock listlock(m_map_mutex);
466 u32 headersize = BASE_HEADER_SIZE + 7;
467 if (p.data.getSize() < headersize) {
468 errorstream << "Invalid data size for split packet" << std::endl;
469 return SharedBuffer<u8>();
471 u8 type = readU8(&p.data[BASE_HEADER_SIZE+0]);
472 u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]);
473 u16 chunk_count = readU16(&p.data[BASE_HEADER_SIZE+3]);
474 u16 chunk_num = readU16(&p.data[BASE_HEADER_SIZE+5]);
476 if (type != TYPE_SPLIT) {
477 errorstream << "IncomingSplitBuffer::insert(): type is not split"
479 return SharedBuffer<u8>();
482 // Add if doesn't exist
483 if (m_buf.find(seqnum) == m_buf.end())
485 IncomingSplitPacket *sp = new IncomingSplitPacket();
486 sp->chunk_count = chunk_count;
487 sp->reliable = reliable;
491 IncomingSplitPacket *sp = m_buf[seqnum];
493 // TODO: These errors should be thrown or something? Dunno.
494 if (chunk_count != sp->chunk_count)
495 LOG(derr_con<<"Connection: WARNING: chunk_count="<<chunk_count
496 <<" != sp->chunk_count="<<sp->chunk_count
498 if (reliable != sp->reliable)
499 LOG(derr_con<<"Connection: WARNING: reliable="<<reliable
500 <<" != sp->reliable="<<sp->reliable
503 // If chunk already exists, ignore it.
504 // Sometimes two identical packets may arrive when there is network
505 // lag and the server re-sends stuff.
506 if (sp->chunks.find(chunk_num) != sp->chunks.end())
507 return SharedBuffer<u8>();
509 // Cut chunk data out of packet
510 u32 chunkdatasize = p.data.getSize() - headersize;
511 SharedBuffer<u8> chunkdata(chunkdatasize);
512 memcpy(*chunkdata, &(p.data[headersize]), chunkdatasize);
514 // Set chunk data in buffer
515 sp->chunks[chunk_num] = chunkdata;
517 // If not all chunks are received, return empty buffer
518 if (sp->allReceived() == false)
519 return SharedBuffer<u8>();
521 // Calculate total size
523 for(std::map<u16, SharedBuffer<u8> >::iterator i = sp->chunks.begin();
524 i != sp->chunks.end(); ++i)
526 totalsize += i->second.getSize();
529 SharedBuffer<u8> fulldata(totalsize);
531 // Copy chunks to data buffer
533 for(u32 chunk_i=0; chunk_i<sp->chunk_count;
536 SharedBuffer<u8> buf = sp->chunks[chunk_i];
537 u16 chunkdatasize = buf.getSize();
538 memcpy(&fulldata[start], *buf, chunkdatasize);
539 start += chunkdatasize;;
542 // Remove sp from buffer
548 void IncomingSplitBuffer::removeUnreliableTimedOuts(float dtime, float timeout)
550 std::list<u16> remove_queue;
552 MutexAutoLock listlock(m_map_mutex);
553 for(std::map<u16, IncomingSplitPacket*>::iterator i = m_buf.begin();
554 i != m_buf.end(); ++i)
556 IncomingSplitPacket *p = i->second;
557 // Reliable ones are not removed by timeout
558 if (p->reliable == true)
561 if (p->time >= timeout)
562 remove_queue.push_back(i->first);
565 for(std::list<u16>::iterator j = remove_queue.begin();
566 j != remove_queue.end(); ++j)
568 MutexAutoLock listlock(m_map_mutex);
569 LOG(dout_con<<"NOTE: Removing timed out unreliable split packet"<<std::endl);
580 window_size(MIN_RELIABLE_WINDOW_SIZE),
581 next_incoming_seqnum(SEQNUM_INITIAL),
582 next_outgoing_seqnum(SEQNUM_INITIAL),
583 next_outgoing_split_seqnum(SEQNUM_INITIAL),
584 current_packet_loss(0),
585 current_packet_too_late(0),
586 current_packet_successfull(0),
587 packet_loss_counter(0),
588 current_bytes_transfered(0),
589 current_bytes_received(0),
590 current_bytes_lost(0),
594 max_incoming_kbps(0.0),
595 cur_incoming_kbps(0.0),
596 avg_incoming_kbps(0.0),
609 u16 Channel::readNextIncomingSeqNum()
611 MutexAutoLock internal(m_internal_mutex);
612 return next_incoming_seqnum;
615 u16 Channel::incNextIncomingSeqNum()
617 MutexAutoLock internal(m_internal_mutex);
618 u16 retval = next_incoming_seqnum;
619 next_incoming_seqnum++;
623 u16 Channel::readNextSplitSeqNum()
625 MutexAutoLock internal(m_internal_mutex);
626 return next_outgoing_split_seqnum;
628 void Channel::setNextSplitSeqNum(u16 seqnum)
630 MutexAutoLock internal(m_internal_mutex);
631 next_outgoing_split_seqnum = seqnum;
634 u16 Channel::getOutgoingSequenceNumber(bool& successful)
636 MutexAutoLock internal(m_internal_mutex);
637 u16 retval = next_outgoing_seqnum;
638 u16 lowest_unacked_seqnumber;
640 /* shortcut if there ain't any packet in outgoing list */
641 if (outgoing_reliables_sent.empty())
643 next_outgoing_seqnum++;
647 if (outgoing_reliables_sent.getFirstSeqnum(lowest_unacked_seqnumber))
649 if (lowest_unacked_seqnumber < next_outgoing_seqnum) {
650 // ugly cast but this one is required in order to tell compiler we
651 // know about difference of two unsigned may be negative in general
652 // but we already made sure it won't happen in this case
653 if (((u16)(next_outgoing_seqnum - lowest_unacked_seqnumber)) > window_size) {
659 // ugly cast but this one is required in order to tell compiler we
660 // know about difference of two unsigned may be negative in general
661 // but we already made sure it won't happen in this case
662 if ((next_outgoing_seqnum + (u16)(SEQNUM_MAX - lowest_unacked_seqnumber)) >
670 next_outgoing_seqnum++;
674 u16 Channel::readOutgoingSequenceNumber()
676 MutexAutoLock internal(m_internal_mutex);
677 return next_outgoing_seqnum;
680 bool Channel::putBackSequenceNumber(u16 seqnum)
682 if (((seqnum + 1) % (SEQNUM_MAX+1)) == next_outgoing_seqnum) {
684 next_outgoing_seqnum = seqnum;
690 void Channel::UpdateBytesSent(unsigned int bytes, unsigned int packets)
692 MutexAutoLock internal(m_internal_mutex);
693 current_bytes_transfered += bytes;
694 current_packet_successfull += packets;
697 void Channel::UpdateBytesReceived(unsigned int bytes) {
698 MutexAutoLock internal(m_internal_mutex);
699 current_bytes_received += bytes;
702 void Channel::UpdateBytesLost(unsigned int bytes)
704 MutexAutoLock internal(m_internal_mutex);
705 current_bytes_lost += bytes;
709 void Channel::UpdatePacketLossCounter(unsigned int count)
711 MutexAutoLock internal(m_internal_mutex);
712 current_packet_loss += count;
715 void Channel::UpdatePacketTooLateCounter()
717 MutexAutoLock internal(m_internal_mutex);
718 current_packet_too_late++;
721 void Channel::UpdateTimers(float dtime,bool legacy_peer)
723 bpm_counter += dtime;
724 packet_loss_counter += dtime;
726 if (packet_loss_counter > 1.0)
728 packet_loss_counter -= 1.0;
730 unsigned int packet_loss = 11; /* use a neutral value for initialization */
731 unsigned int packets_successfull = 0;
732 //unsigned int packet_too_late = 0;
734 bool reasonable_amount_of_data_transmitted = false;
737 MutexAutoLock internal(m_internal_mutex);
738 packet_loss = current_packet_loss;
739 //packet_too_late = current_packet_too_late;
740 packets_successfull = current_packet_successfull;
742 if (current_bytes_transfered > (unsigned int) (window_size*512/2))
744 reasonable_amount_of_data_transmitted = true;
746 current_packet_loss = 0;
747 current_packet_too_late = 0;
748 current_packet_successfull = 0;
751 /* dynamic window size is only available for non legacy peers */
753 float successfull_to_lost_ratio = 0.0;
756 if (packets_successfull > 0) {
757 successfull_to_lost_ratio = packet_loss/packets_successfull;
759 else if (packet_loss > 0)
763 MIN_RELIABLE_WINDOW_SIZE);
769 if ((successfull_to_lost_ratio < 0.01) &&
770 (window_size < MAX_RELIABLE_WINDOW_SIZE))
772 /* don't even think about increasing if we didn't even
773 * use major parts of our window */
774 if (reasonable_amount_of_data_transmitted)
777 MAX_RELIABLE_WINDOW_SIZE);
779 else if ((successfull_to_lost_ratio < 0.05) &&
780 (window_size < MAX_RELIABLE_WINDOW_SIZE))
782 /* don't even think about increasing if we didn't even
783 * use major parts of our window */
784 if (reasonable_amount_of_data_transmitted)
787 MAX_RELIABLE_WINDOW_SIZE);
789 else if (successfull_to_lost_ratio > 0.15)
793 MIN_RELIABLE_WINDOW_SIZE);
795 else if (successfull_to_lost_ratio > 0.1)
799 MIN_RELIABLE_WINDOW_SIZE);
805 if (bpm_counter > 10.0)
808 MutexAutoLock internal(m_internal_mutex);
810 (((float) current_bytes_transfered)/bpm_counter)/1024.0;
811 current_bytes_transfered = 0;
813 (((float) current_bytes_lost)/bpm_counter)/1024.0;
814 current_bytes_lost = 0;
816 (((float) current_bytes_received)/bpm_counter)/1024.0;
817 current_bytes_received = 0;
821 if (cur_kbps > max_kbps)
826 if (cur_kbps_lost > max_kbps_lost)
828 max_kbps_lost = cur_kbps_lost;
831 if (cur_incoming_kbps > max_incoming_kbps) {
832 max_incoming_kbps = cur_incoming_kbps;
835 rate_samples = MYMIN(rate_samples+1,10);
836 float old_fraction = ((float) (rate_samples-1) )/( (float) rate_samples);
837 avg_kbps = avg_kbps * old_fraction +
838 cur_kbps * (1.0 - old_fraction);
839 avg_kbps_lost = avg_kbps_lost * old_fraction +
840 cur_kbps_lost * (1.0 - old_fraction);
841 avg_incoming_kbps = avg_incoming_kbps * old_fraction +
842 cur_incoming_kbps * (1.0 - old_fraction);
851 PeerHelper::PeerHelper() :
855 PeerHelper::PeerHelper(Peer* peer) :
860 if (!peer->IncUseCount())
867 PeerHelper::~PeerHelper()
870 m_peer->DecUseCount();
875 PeerHelper& PeerHelper::operator=(Peer* peer)
880 if (!peer->IncUseCount())
888 Peer* PeerHelper::operator->() const
893 Peer* PeerHelper::operator&() const
898 bool PeerHelper::operator!() {
902 bool PeerHelper::operator!=(void* ptr)
904 return ((void*) m_peer != ptr);
907 bool Peer::IncUseCount()
909 MutexAutoLock lock(m_exclusive_access_mutex);
911 if (!m_pending_deletion)
920 void Peer::DecUseCount()
923 MutexAutoLock lock(m_exclusive_access_mutex);
924 sanity_check(m_usage > 0);
927 if (!((m_pending_deletion) && (m_usage == 0)))
933 void Peer::RTTStatistics(float rtt, const std::string &profiler_id,
934 unsigned int num_samples) {
936 if (m_last_rtt > 0) {
937 /* set min max values */
938 if (rtt < m_rtt.min_rtt)
940 if (rtt >= m_rtt.max_rtt)
943 /* do average calculation */
944 if (m_rtt.avg_rtt < 0.0)
947 m_rtt.avg_rtt = m_rtt.avg_rtt * (num_samples/(num_samples-1)) +
948 rtt * (1/num_samples);
950 /* do jitter calculation */
952 //just use some neutral value at beginning
953 float jitter = m_rtt.jitter_min;
955 if (rtt > m_last_rtt)
956 jitter = rtt-m_last_rtt;
958 if (rtt <= m_last_rtt)
959 jitter = m_last_rtt - rtt;
961 if (jitter < m_rtt.jitter_min)
962 m_rtt.jitter_min = jitter;
963 if (jitter >= m_rtt.jitter_max)
964 m_rtt.jitter_max = jitter;
966 if (m_rtt.jitter_avg < 0.0)
967 m_rtt.jitter_avg = jitter;
969 m_rtt.jitter_avg = m_rtt.jitter_avg * (num_samples/(num_samples-1)) +
970 jitter * (1/num_samples);
972 if (profiler_id != "") {
973 g_profiler->graphAdd(profiler_id + "_rtt", rtt);
974 g_profiler->graphAdd(profiler_id + "_jitter", jitter);
977 /* save values required for next loop */
981 bool Peer::isTimedOut(float timeout)
983 MutexAutoLock lock(m_exclusive_access_mutex);
984 u32 current_time = porting::getTimeMs();
986 float dtime = CALC_DTIME(m_last_timeout_check,current_time);
987 m_last_timeout_check = current_time;
989 m_timeout_counter += dtime;
991 return m_timeout_counter > timeout;
997 MutexAutoLock usage_lock(m_exclusive_access_mutex);
998 m_pending_deletion = true;
1003 PROFILE(std::stringstream peerIdentifier1);
1004 PROFILE(peerIdentifier1 << "runTimeouts[" << m_connection->getDesc()
1005 << ";" << id << ";RELIABLE]");
1006 PROFILE(g_profiler->remove(peerIdentifier1.str()));
1007 PROFILE(std::stringstream peerIdentifier2);
1008 PROFILE(peerIdentifier2 << "sendPackets[" << m_connection->getDesc()
1009 << ";" << id << ";RELIABLE]");
1010 PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier2.str(), SPT_AVG));
1015 UDPPeer::UDPPeer(u16 a_id, Address a_address, Connection* connection) :
1016 Peer(a_address,a_id,connection),
1017 m_pending_disconnect(false),
1018 resend_timeout(0.5),
1023 bool UDPPeer::getAddress(MTProtocols type,Address& toset)
1025 if ((type == MTP_UDP) || (type == MTP_MINETEST_RELIABLE_UDP) || (type == MTP_PRIMARY))
1034 void UDPPeer::setNonLegacyPeer()
1036 m_legacy_peer = false;
1037 for(unsigned int i=0; i< CHANNEL_COUNT; i++)
1039 channels->setWindowSize(g_settings->getU16("max_packets_per_iteration"));
1043 void UDPPeer::reportRTT(float rtt)
1048 RTTStatistics(rtt,"rudp",MAX_RELIABLE_WINDOW_SIZE*10);
1050 float timeout = getStat(AVG_RTT) * RESEND_TIMEOUT_FACTOR;
1051 if (timeout < RESEND_TIMEOUT_MIN)
1052 timeout = RESEND_TIMEOUT_MIN;
1053 if (timeout > RESEND_TIMEOUT_MAX)
1054 timeout = RESEND_TIMEOUT_MAX;
1056 MutexAutoLock usage_lock(m_exclusive_access_mutex);
1057 resend_timeout = timeout;
1060 bool UDPPeer::Ping(float dtime,SharedBuffer<u8>& data)
1062 m_ping_timer += dtime;
1063 if (m_ping_timer >= PING_TIMEOUT)
1065 // Create and send PING packet
1066 writeU8(&data[0], TYPE_CONTROL);
1067 writeU8(&data[1], CONTROLTYPE_PING);
1074 void UDPPeer::PutReliableSendCommand(ConnectionCommand &c,
1075 unsigned int max_packet_size)
1077 if (m_pending_disconnect)
1080 if ( channels[c.channelnum].queued_commands.empty() &&
1081 /* don't queue more packets then window size */
1082 (channels[c.channelnum].queued_reliables.size()
1083 < (channels[c.channelnum].getWindowSize()/2))) {
1084 LOG(dout_con<<m_connection->getDesc()
1085 <<" processing reliable command for peer id: " << c.peer_id
1086 <<" data size: " << c.data.getSize() << std::endl);
1087 if (!processReliableSendCommand(c,max_packet_size)) {
1088 channels[c.channelnum].queued_commands.push_back(c);
1092 LOG(dout_con<<m_connection->getDesc()
1093 <<" Queueing reliable command for peer id: " << c.peer_id
1094 <<" data size: " << c.data.getSize() <<std::endl);
1095 channels[c.channelnum].queued_commands.push_back(c);
1099 bool UDPPeer::processReliableSendCommand(
1100 ConnectionCommand &c,
1101 unsigned int max_packet_size)
1103 if (m_pending_disconnect)
1106 u32 chunksize_max = max_packet_size
1108 - RELIABLE_HEADER_SIZE;
1110 sanity_check(c.data.getSize() < MAX_RELIABLE_WINDOW_SIZE*512);
1112 std::list<SharedBuffer<u8> > originals;
1113 u16 split_sequence_number = channels[c.channelnum].readNextSplitSeqNum();
1117 originals.push_back(c.data);
1120 originals = makeAutoSplitPacket(c.data, chunksize_max,split_sequence_number);
1121 channels[c.channelnum].setNextSplitSeqNum(split_sequence_number);
1124 bool have_sequence_number = true;
1125 bool have_initial_sequence_number = false;
1126 std::queue<BufferedPacket> toadd;
1127 volatile u16 initial_sequence_number = 0;
1129 for(std::list<SharedBuffer<u8> >::iterator i = originals.begin();
1130 i != originals.end(); ++i)
1132 u16 seqnum = channels[c.channelnum].getOutgoingSequenceNumber(have_sequence_number);
1134 /* oops, we don't have enough sequence numbers to send this packet */
1135 if (!have_sequence_number)
1138 if (!have_initial_sequence_number)
1140 initial_sequence_number = seqnum;
1141 have_initial_sequence_number = true;
1144 SharedBuffer<u8> reliable = makeReliablePacket(*i, seqnum);
1146 // Add base headers and make a packet
1147 BufferedPacket p = con::makePacket(address, reliable,
1148 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1154 if (have_sequence_number) {
1155 volatile u16 pcount = 0;
1156 while(toadd.size() > 0) {
1157 BufferedPacket p = toadd.front();
1159 // LOG(dout_con<<connection->getDesc()
1160 // << " queuing reliable packet for peer_id: " << c.peer_id
1161 // << " channel: " << (c.channelnum&0xFF)
1162 // << " seqnum: " << readU16(&p.data[BASE_HEADER_SIZE+1])
1164 channels[c.channelnum].queued_reliables.push(p);
1167 sanity_check(channels[c.channelnum].queued_reliables.size() < 0xFFFF);
1171 volatile u16 packets_available = toadd.size();
1172 /* we didn't get a single sequence number no need to fill queue */
1173 if (!have_initial_sequence_number)
1177 while(toadd.size() > 0) {
1181 bool successfully_put_back_sequence_number
1182 = channels[c.channelnum].putBackSequenceNumber(
1183 (initial_sequence_number+toadd.size() % (SEQNUM_MAX+1)));
1185 FATAL_ERROR_IF(!successfully_put_back_sequence_number, "error");
1187 LOG(dout_con<<m_connection->getDesc()
1188 << " Windowsize exceeded on reliable sending "
1189 << c.data.getSize() << " bytes"
1190 << std::endl << "\t\tinitial_sequence_number: "
1191 << initial_sequence_number
1192 << std::endl << "\t\tgot at most : "
1193 << packets_available << " packets"
1194 << std::endl << "\t\tpackets queued : "
1195 << channels[c.channelnum].outgoing_reliables_sent.size()
1201 void UDPPeer::RunCommandQueues(
1202 unsigned int max_packet_size,
1203 unsigned int maxcommands,
1204 unsigned int maxtransfer)
1207 for (unsigned int i = 0; i < CHANNEL_COUNT; i++) {
1208 unsigned int commands_processed = 0;
1210 if ((channels[i].queued_commands.size() > 0) &&
1211 (channels[i].queued_reliables.size() < maxtransfer) &&
1212 (commands_processed < maxcommands)) {
1214 ConnectionCommand c = channels[i].queued_commands.front();
1216 LOG(dout_con << m_connection->getDesc()
1217 << " processing queued reliable command " << std::endl);
1219 // Packet is processed, remove it from queue
1220 if (processReliableSendCommand(c,max_packet_size)) {
1221 channels[i].queued_commands.pop_front();
1223 LOG(dout_con << m_connection->getDesc()
1224 << " Failed to queue packets for peer_id: " << c.peer_id
1225 << ", delaying sending of " << c.data.getSize()
1226 << " bytes" << std::endl);
1229 catch (ItemNotFoundException &e) {
1230 // intentionally empty
1236 u16 UDPPeer::getNextSplitSequenceNumber(u8 channel)
1238 assert(channel < CHANNEL_COUNT); // Pre-condition
1239 return channels[channel].readNextSplitSeqNum();
1242 void UDPPeer::setNextSplitSequenceNumber(u8 channel, u16 seqnum)
1244 assert(channel < CHANNEL_COUNT); // Pre-condition
1245 channels[channel].setNextSplitSeqNum(seqnum);
1248 SharedBuffer<u8> UDPPeer::addSpiltPacket(u8 channel,
1249 BufferedPacket toadd,
1252 assert(channel < CHANNEL_COUNT); // Pre-condition
1253 return channels[channel].incoming_splits.insert(toadd,reliable);
1256 /******************************************************************************/
1257 /* Connection Threads */
1258 /******************************************************************************/
1260 ConnectionSendThread::ConnectionSendThread(unsigned int max_packet_size,
1262 Thread("ConnectionSend"),
1264 m_max_packet_size(max_packet_size),
1266 m_max_commands_per_iteration(1),
1267 m_max_data_packets_per_iteration(g_settings->getU16("max_packets_per_iteration")),
1268 m_max_packets_requeued(256)
1272 void * ConnectionSendThread::run()
1274 assert(m_connection);
1276 LOG(dout_con<<m_connection->getDesc()
1277 <<"ConnectionSend thread started"<<std::endl);
1279 u32 curtime = porting::getTimeMs();
1280 u32 lasttime = curtime;
1282 PROFILE(std::stringstream ThreadIdentifier);
1283 PROFILE(ThreadIdentifier << "ConnectionSend: [" << m_connection->getDesc() << "]");
1285 /* if stop is requested don't stop immediately but try to send all */
1287 while(!stopRequested() || packetsQueued()) {
1288 BEGIN_DEBUG_EXCEPTION_HANDLER
1289 PROFILE(ScopeProfiler sp(g_profiler, ThreadIdentifier.str(), SPT_AVG));
1291 m_iteration_packets_avaialble = m_max_data_packets_per_iteration;
1293 /* wait for trigger or timeout */
1294 m_send_sleep_semaphore.wait(50);
1296 /* remove all triggers */
1297 while(m_send_sleep_semaphore.wait(0)) {}
1300 curtime = porting::getTimeMs();
1301 float dtime = CALC_DTIME(lasttime,curtime);
1303 /* first do all the reliable stuff */
1306 /* translate commands to packets */
1307 ConnectionCommand c = m_connection->m_command_queue.pop_frontNoEx(0);
1308 while(c.type != CONNCMD_NONE)
1311 processReliableCommand(c);
1313 processNonReliableCommand(c);
1315 c = m_connection->m_command_queue.pop_frontNoEx(0);
1318 /* send non reliable packets */
1321 END_DEBUG_EXCEPTION_HANDLER
1324 PROFILE(g_profiler->remove(ThreadIdentifier.str()));
1328 void ConnectionSendThread::Trigger()
1330 m_send_sleep_semaphore.post();
1333 bool ConnectionSendThread::packetsQueued()
1335 std::list<u16> peerIds = m_connection->getPeerIDs();
1337 if (!m_outgoing_queue.empty() && !peerIds.empty())
1340 for(std::list<u16>::iterator j = peerIds.begin();
1341 j != peerIds.end(); ++j)
1343 PeerHelper peer = m_connection->getPeerNoEx(*j);
1348 if (dynamic_cast<UDPPeer*>(&peer) == 0)
1351 for(u16 i=0; i < CHANNEL_COUNT; i++) {
1352 Channel *channel = &(dynamic_cast<UDPPeer*>(&peer))->channels[i];
1354 if (channel->queued_commands.size() > 0) {
1364 void ConnectionSendThread::runTimeouts(float dtime)
1366 std::list<u16> timeouted_peers;
1367 std::list<u16> peerIds = m_connection->getPeerIDs();
1369 for(std::list<u16>::iterator j = peerIds.begin();
1370 j != peerIds.end(); ++j)
1372 PeerHelper peer = m_connection->getPeerNoEx(*j);
1377 if (dynamic_cast<UDPPeer*>(&peer) == 0)
1380 PROFILE(std::stringstream peerIdentifier);
1381 PROFILE(peerIdentifier << "runTimeouts[" << m_connection->getDesc()
1382 << ";" << *j << ";RELIABLE]");
1383 PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier.str(), SPT_AVG));
1385 SharedBuffer<u8> data(2); // data for sending ping, required here because of goto
1390 if (peer->isTimedOut(m_timeout))
1392 infostream<<m_connection->getDesc()
1393 <<"RunTimeouts(): Peer "<<peer->id
1395 <<" (source=peer->timeout_counter)"
1397 // Add peer to the list
1398 timeouted_peers.push_back(peer->id);
1399 // Don't bother going through the buffers of this one
1403 float resend_timeout = dynamic_cast<UDPPeer*>(&peer)->getResendTimeout();
1404 bool retry_count_exceeded = false;
1405 for(u16 i=0; i<CHANNEL_COUNT; i++)
1407 std::list<BufferedPacket> timed_outs;
1408 Channel *channel = &(dynamic_cast<UDPPeer*>(&peer))->channels[i];
1410 if (dynamic_cast<UDPPeer*>(&peer)->getLegacyPeer())
1411 channel->setWindowSize(g_settings->getU16("workaround_window_size"));
1413 // Remove timed out incomplete unreliable split packets
1414 channel->incoming_splits.removeUnreliableTimedOuts(dtime, m_timeout);
1416 // Increment reliable packet times
1417 channel->outgoing_reliables_sent.incrementTimeouts(dtime);
1419 unsigned int numpeers = m_connection->m_peers.size();
1424 // Re-send timed out outgoing reliables
1425 timed_outs = channel->
1426 outgoing_reliables_sent.getTimedOuts(resend_timeout,
1427 (m_max_data_packets_per_iteration/numpeers));
1429 channel->UpdatePacketLossCounter(timed_outs.size());
1430 g_profiler->graphAdd("packets_lost", timed_outs.size());
1432 m_iteration_packets_avaialble -= timed_outs.size();
1434 for(std::list<BufferedPacket>::iterator k = timed_outs.begin();
1435 k != timed_outs.end(); ++k)
1437 u16 peer_id = readPeerId(*(k->data));
1438 u8 channelnum = readChannel(*(k->data));
1439 u16 seqnum = readU16(&(k->data[BASE_HEADER_SIZE+1]));
1441 channel->UpdateBytesLost(k->data.getSize());
1444 if (k-> resend_count > MAX_RELIABLE_RETRY) {
1445 retry_count_exceeded = true;
1446 timeouted_peers.push_back(peer->id);
1447 /* no need to check additional packets if a single one did timeout*/
1451 LOG(derr_con<<m_connection->getDesc()
1452 <<"RE-SENDING timed-out RELIABLE to "
1453 << k->address.serializeString()
1454 << "(t/o="<<resend_timeout<<"): "
1455 <<"from_peer_id="<<peer_id
1456 <<", channel="<<((int)channelnum&0xff)
1457 <<", seqnum="<<seqnum
1462 // do not handle rtt here as we can't decide if this packet was
1463 // lost or really takes more time to transmit
1466 if (retry_count_exceeded) {
1467 break; /* no need to check other channels if we already did timeout */
1470 channel->UpdateTimers(dtime,dynamic_cast<UDPPeer*>(&peer)->getLegacyPeer());
1473 /* skip to next peer if we did timeout */
1474 if (retry_count_exceeded)
1477 /* send ping if necessary */
1478 if (dynamic_cast<UDPPeer*>(&peer)->Ping(dtime,data)) {
1479 LOG(dout_con<<m_connection->getDesc()
1480 <<"Sending ping for peer_id: "
1481 << dynamic_cast<UDPPeer*>(&peer)->id <<std::endl);
1482 /* this may fail if there ain't a sequence number left */
1483 if (!rawSendAsPacket(dynamic_cast<UDPPeer*>(&peer)->id, 0, data, true))
1485 //retrigger with reduced ping interval
1486 dynamic_cast<UDPPeer*>(&peer)->Ping(4.0,data);
1490 dynamic_cast<UDPPeer*>(&peer)->RunCommandQueues(m_max_packet_size,
1491 m_max_commands_per_iteration,
1492 m_max_packets_requeued);
1495 // Remove timed out peers
1496 for(std::list<u16>::iterator i = timeouted_peers.begin();
1497 i != timeouted_peers.end(); ++i)
1499 LOG(derr_con<<m_connection->getDesc()
1500 <<"RunTimeouts(): Removing peer "<<(*i)<<std::endl);
1501 m_connection->deletePeer(*i, true);
1505 void ConnectionSendThread::rawSend(const BufferedPacket &packet)
1508 m_connection->m_udpSocket.Send(packet.address, *packet.data,
1509 packet.data.getSize());
1510 LOG(dout_con <<m_connection->getDesc()
1511 << " rawSend: " << packet.data.getSize()
1512 << " bytes sent" << std::endl);
1513 } catch(SendFailedException &e) {
1514 LOG(derr_con<<m_connection->getDesc()
1515 <<"Connection::rawSend(): SendFailedException: "
1516 <<packet.address.serializeString()<<std::endl);
1520 void ConnectionSendThread::sendAsPacketReliable(BufferedPacket& p, Channel* channel)
1523 p.absolute_send_time = porting::getTimeMs();
1524 // Buffer the packet
1525 channel->outgoing_reliables_sent.insert(p,
1526 (channel->readOutgoingSequenceNumber() - MAX_RELIABLE_WINDOW_SIZE)
1527 % (MAX_RELIABLE_WINDOW_SIZE+1));
1529 catch(AlreadyExistsException &e)
1531 LOG(derr_con<<m_connection->getDesc()
1532 <<"WARNING: Going to send a reliable packet"
1533 <<" in outgoing buffer" <<std::endl);
1540 bool ConnectionSendThread::rawSendAsPacket(u16 peer_id, u8 channelnum,
1541 SharedBuffer<u8> data, bool reliable)
1543 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
1545 LOG(dout_con<<m_connection->getDesc()
1546 <<" INFO: dropped packet for non existent peer_id: "
1547 << peer_id << std::endl);
1548 FATAL_ERROR_IF(!reliable, "Trying to send raw packet reliable but no peer found!");
1551 Channel *channel = &(dynamic_cast<UDPPeer*>(&peer)->channels[channelnum]);
1555 bool have_sequence_number_for_raw_packet = true;
1557 channel->getOutgoingSequenceNumber(have_sequence_number_for_raw_packet);
1559 if (!have_sequence_number_for_raw_packet)
1562 SharedBuffer<u8> reliable = makeReliablePacket(data, seqnum);
1563 Address peer_address;
1564 peer->getAddress(MTP_MINETEST_RELIABLE_UDP, peer_address);
1566 // Add base headers and make a packet
1567 BufferedPacket p = con::makePacket(peer_address, reliable,
1568 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1571 // first check if our send window is already maxed out
1572 if (channel->outgoing_reliables_sent.size()
1573 < channel->getWindowSize()) {
1574 LOG(dout_con<<m_connection->getDesc()
1575 <<" INFO: sending a reliable packet to peer_id " << peer_id
1576 <<" channel: " << channelnum
1577 <<" seqnum: " << seqnum << std::endl);
1578 sendAsPacketReliable(p,channel);
1582 LOG(dout_con<<m_connection->getDesc()
1583 <<" INFO: queueing reliable packet for peer_id: " << peer_id
1584 <<" channel: " << channelnum
1585 <<" seqnum: " << seqnum << std::endl);
1586 channel->queued_reliables.push(p);
1592 Address peer_address;
1594 if (peer->getAddress(MTP_UDP, peer_address))
1596 // Add base headers and make a packet
1597 BufferedPacket p = con::makePacket(peer_address, data,
1598 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1606 LOG(dout_con<<m_connection->getDesc()
1607 <<" INFO: dropped unreliable packet for peer_id: " << peer_id
1608 <<" because of (yet) missing udp address" << std::endl);
1617 void ConnectionSendThread::processReliableCommand(ConnectionCommand &c)
1619 assert(c.reliable); // Pre-condition
1623 LOG(dout_con<<m_connection->getDesc()
1624 <<"UDP processing reliable CONNCMD_NONE"<<std::endl);
1628 LOG(dout_con<<m_connection->getDesc()
1629 <<"UDP processing reliable CONNCMD_SEND"<<std::endl);
1633 case CONNCMD_SEND_TO_ALL:
1634 LOG(dout_con<<m_connection->getDesc()
1635 <<"UDP processing CONNCMD_SEND_TO_ALL"<<std::endl);
1636 sendToAllReliable(c);
1639 case CONCMD_CREATE_PEER:
1640 LOG(dout_con<<m_connection->getDesc()
1641 <<"UDP processing reliable CONCMD_CREATE_PEER"<<std::endl);
1642 if (!rawSendAsPacket(c.peer_id,c.channelnum,c.data,c.reliable))
1644 /* put to queue if we couldn't send it immediately */
1649 case CONCMD_DISABLE_LEGACY:
1650 LOG(dout_con<<m_connection->getDesc()
1651 <<"UDP processing reliable CONCMD_DISABLE_LEGACY"<<std::endl);
1652 if (!rawSendAsPacket(c.peer_id,c.channelnum,c.data,c.reliable))
1654 /* put to queue if we couldn't send it immediately */
1660 case CONNCMD_CONNECT:
1661 case CONNCMD_DISCONNECT:
1663 FATAL_ERROR("Got command that shouldn't be reliable as reliable command");
1665 LOG(dout_con<<m_connection->getDesc()
1666 <<" Invalid reliable command type: " << c.type <<std::endl);
1671 void ConnectionSendThread::processNonReliableCommand(ConnectionCommand &c)
1673 assert(!c.reliable); // Pre-condition
1677 LOG(dout_con<<m_connection->getDesc()
1678 <<" UDP processing CONNCMD_NONE"<<std::endl);
1681 LOG(dout_con<<m_connection->getDesc()
1682 <<" UDP processing CONNCMD_SERVE port="
1683 <<c.address.serializeString()<<std::endl);
1686 case CONNCMD_CONNECT:
1687 LOG(dout_con<<m_connection->getDesc()
1688 <<" UDP processing CONNCMD_CONNECT"<<std::endl);
1691 case CONNCMD_DISCONNECT:
1692 LOG(dout_con<<m_connection->getDesc()
1693 <<" UDP processing CONNCMD_DISCONNECT"<<std::endl);
1696 case CONNCMD_DISCONNECT_PEER:
1697 LOG(dout_con<<m_connection->getDesc()
1698 <<" UDP processing CONNCMD_DISCONNECT_PEER"<<std::endl);
1699 disconnect_peer(c.peer_id);
1702 LOG(dout_con<<m_connection->getDesc()
1703 <<" UDP processing CONNCMD_SEND"<<std::endl);
1704 send(c.peer_id, c.channelnum, c.data);
1706 case CONNCMD_SEND_TO_ALL:
1707 LOG(dout_con<<m_connection->getDesc()
1708 <<" UDP processing CONNCMD_SEND_TO_ALL"<<std::endl);
1709 sendToAll(c.channelnum, c.data);
1712 LOG(dout_con<<m_connection->getDesc()
1713 <<" UDP processing CONCMD_ACK"<<std::endl);
1714 sendAsPacket(c.peer_id,c.channelnum,c.data,true);
1716 case CONCMD_CREATE_PEER:
1717 FATAL_ERROR("Got command that should be reliable as unreliable command");
1719 LOG(dout_con<<m_connection->getDesc()
1720 <<" Invalid command type: " << c.type <<std::endl);
1724 void ConnectionSendThread::serve(Address bind_address)
1726 LOG(dout_con<<m_connection->getDesc()
1727 <<"UDP serving at port " << bind_address.serializeString() <<std::endl);
1729 m_connection->m_udpSocket.Bind(bind_address);
1730 m_connection->SetPeerID(PEER_ID_SERVER);
1732 catch(SocketException &e) {
1736 m_connection->putEvent(ce);
1740 void ConnectionSendThread::connect(Address address)
1742 LOG(dout_con<<m_connection->getDesc()<<" connecting to "<<address.serializeString()
1743 <<":"<<address.getPort()<<std::endl);
1745 UDPPeer *peer = m_connection->createServerPeer(address);
1749 e.peerAdded(peer->id, peer->address);
1750 m_connection->putEvent(e);
1754 if (address.isIPv6())
1755 bind_addr.setAddress((IPv6AddressBytes*) NULL);
1757 bind_addr.setAddress(0,0,0,0);
1759 m_connection->m_udpSocket.Bind(bind_addr);
1761 // Send a dummy packet to server with peer_id = PEER_ID_INEXISTENT
1762 m_connection->SetPeerID(PEER_ID_INEXISTENT);
1763 NetworkPacket pkt(0,0);
1764 m_connection->Send(PEER_ID_SERVER, 0, &pkt, true);
1767 void ConnectionSendThread::disconnect()
1769 LOG(dout_con<<m_connection->getDesc()<<" disconnecting"<<std::endl);
1771 // Create and send DISCO packet
1772 SharedBuffer<u8> data(2);
1773 writeU8(&data[0], TYPE_CONTROL);
1774 writeU8(&data[1], CONTROLTYPE_DISCO);
1778 std::list<u16> peerids = m_connection->getPeerIDs();
1780 for (std::list<u16>::iterator i = peerids.begin();
1784 sendAsPacket(*i, 0,data,false);
1788 void ConnectionSendThread::disconnect_peer(u16 peer_id)
1790 LOG(dout_con<<m_connection->getDesc()<<" disconnecting peer"<<std::endl);
1792 // Create and send DISCO packet
1793 SharedBuffer<u8> data(2);
1794 writeU8(&data[0], TYPE_CONTROL);
1795 writeU8(&data[1], CONTROLTYPE_DISCO);
1796 sendAsPacket(peer_id, 0,data,false);
1798 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
1803 if (dynamic_cast<UDPPeer*>(&peer) == 0)
1808 dynamic_cast<UDPPeer*>(&peer)->m_pending_disconnect = true;
1811 void ConnectionSendThread::send(u16 peer_id, u8 channelnum,
1812 SharedBuffer<u8> data)
1814 assert(channelnum < CHANNEL_COUNT); // Pre-condition
1816 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
1819 LOG(dout_con<<m_connection->getDesc()<<" peer: peer_id="<<peer_id
1820 << ">>>NOT<<< found on sending packet"
1821 << ", channel " << (channelnum % 0xFF)
1822 << ", size: " << data.getSize() <<std::endl);
1826 LOG(dout_con<<m_connection->getDesc()<<" sending to peer_id="<<peer_id
1827 << ", channel " << (channelnum % 0xFF)
1828 << ", size: " << data.getSize() <<std::endl);
1830 u16 split_sequence_number = peer->getNextSplitSequenceNumber(channelnum);
1832 u32 chunksize_max = m_max_packet_size - BASE_HEADER_SIZE;
1833 std::list<SharedBuffer<u8> > originals;
1835 originals = makeAutoSplitPacket(data, chunksize_max,split_sequence_number);
1837 peer->setNextSplitSequenceNumber(channelnum,split_sequence_number);
1839 for(std::list<SharedBuffer<u8> >::iterator i = originals.begin();
1840 i != originals.end(); ++i)
1842 SharedBuffer<u8> original = *i;
1843 sendAsPacket(peer_id, channelnum, original);
1847 void ConnectionSendThread::sendReliable(ConnectionCommand &c)
1849 PeerHelper peer = m_connection->getPeerNoEx(c.peer_id);
1853 peer->PutReliableSendCommand(c,m_max_packet_size);
1856 void ConnectionSendThread::sendToAll(u8 channelnum, SharedBuffer<u8> data)
1858 std::list<u16> peerids = m_connection->getPeerIDs();
1860 for (std::list<u16>::iterator i = peerids.begin();
1864 send(*i, channelnum, data);
1868 void ConnectionSendThread::sendToAllReliable(ConnectionCommand &c)
1870 std::list<u16> peerids = m_connection->getPeerIDs();
1872 for (std::list<u16>::iterator i = peerids.begin();
1876 PeerHelper peer = m_connection->getPeerNoEx(*i);
1881 peer->PutReliableSendCommand(c,m_max_packet_size);
1885 void ConnectionSendThread::sendPackets(float dtime)
1887 std::list<u16> peerIds = m_connection->getPeerIDs();
1888 std::list<u16> pendingDisconnect;
1889 std::map<u16,bool> pending_unreliable;
1891 for(std::list<u16>::iterator
1892 j = peerIds.begin();
1893 j != peerIds.end(); ++j)
1895 PeerHelper peer = m_connection->getPeerNoEx(*j);
1896 //peer may have been removed
1898 LOG(dout_con<<m_connection->getDesc()<< " Peer not found: peer_id=" << *j << std::endl);
1901 peer->m_increment_packets_remaining = m_iteration_packets_avaialble/m_connection->m_peers.size();
1903 if (dynamic_cast<UDPPeer*>(&peer) == 0)
1908 if (dynamic_cast<UDPPeer*>(&peer)->m_pending_disconnect)
1910 pendingDisconnect.push_back(*j);
1913 PROFILE(std::stringstream peerIdentifier);
1914 PROFILE(peerIdentifier << "sendPackets[" << m_connection->getDesc() << ";" << *j << ";RELIABLE]");
1915 PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier.str(), SPT_AVG));
1917 LOG(dout_con<<m_connection->getDesc()
1918 << " Handle per peer queues: peer_id=" << *j
1919 << " packet quota: " << peer->m_increment_packets_remaining << std::endl);
1920 // first send queued reliable packets for all peers (if possible)
1921 for (unsigned int i=0; i < CHANNEL_COUNT; i++)
1923 u16 next_to_ack = 0;
1924 dynamic_cast<UDPPeer*>(&peer)->channels[i].outgoing_reliables_sent.getFirstSeqnum(next_to_ack);
1925 u16 next_to_receive = 0;
1926 dynamic_cast<UDPPeer*>(&peer)->channels[i].incoming_reliables.getFirstSeqnum(next_to_receive);
1928 LOG(dout_con<<m_connection->getDesc()<< "\t channel: "
1929 << i << ", peer quota:"
1930 << peer->m_increment_packets_remaining
1932 << "\t\t\treliables on wire: "
1933 << dynamic_cast<UDPPeer*>(&peer)->channels[i].outgoing_reliables_sent.size()
1934 << ", waiting for ack for " << next_to_ack
1936 << "\t\t\tincoming_reliables: "
1937 << dynamic_cast<UDPPeer*>(&peer)->channels[i].incoming_reliables.size()
1938 << ", next reliable packet: "
1939 << dynamic_cast<UDPPeer*>(&peer)->channels[i].readNextIncomingSeqNum()
1940 << ", next queued: " << next_to_receive
1942 << "\t\t\treliables queued : "
1943 << dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.size()
1945 << "\t\t\tqueued commands : "
1946 << dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_commands.size()
1949 while ((dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.size() > 0) &&
1950 (dynamic_cast<UDPPeer*>(&peer)->channels[i].outgoing_reliables_sent.size()
1951 < dynamic_cast<UDPPeer*>(&peer)->channels[i].getWindowSize())&&
1952 (peer->m_increment_packets_remaining > 0))
1954 BufferedPacket p = dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.front();
1955 dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.pop();
1956 Channel* channel = &(dynamic_cast<UDPPeer*>(&peer)->channels[i]);
1957 LOG(dout_con<<m_connection->getDesc()
1958 <<" INFO: sending a queued reliable packet "
1960 <<", seqnum: " << readU16(&p.data[BASE_HEADER_SIZE+1])
1962 sendAsPacketReliable(p,channel);
1963 peer->m_increment_packets_remaining--;
1968 if (m_outgoing_queue.size())
1970 LOG(dout_con<<m_connection->getDesc()
1971 << " Handle non reliable queue ("
1972 << m_outgoing_queue.size() << " pkts)" << std::endl);
1975 unsigned int initial_queuesize = m_outgoing_queue.size();
1976 /* send non reliable packets*/
1977 for(unsigned int i=0;i < initial_queuesize;i++) {
1978 OutgoingPacket packet = m_outgoing_queue.front();
1979 m_outgoing_queue.pop();
1981 if (packet.reliable)
1984 PeerHelper peer = m_connection->getPeerNoEx(packet.peer_id);
1986 LOG(dout_con<<m_connection->getDesc()
1987 <<" Outgoing queue: peer_id="<<packet.peer_id
1988 << ">>>NOT<<< found on sending packet"
1989 << ", channel " << (packet.channelnum % 0xFF)
1990 << ", size: " << packet.data.getSize() <<std::endl);
1993 /* send acks immediately */
1994 else if (packet.ack)
1996 rawSendAsPacket(packet.peer_id, packet.channelnum,
1997 packet.data, packet.reliable);
1998 peer->m_increment_packets_remaining =
1999 MYMIN(0,peer->m_increment_packets_remaining--);
2002 ( peer->m_increment_packets_remaining > 0) ||
2003 (stopRequested())) {
2004 rawSendAsPacket(packet.peer_id, packet.channelnum,
2005 packet.data, packet.reliable);
2006 peer->m_increment_packets_remaining--;
2009 m_outgoing_queue.push(packet);
2010 pending_unreliable[packet.peer_id] = true;
2014 for(std::list<u16>::iterator
2015 k = pendingDisconnect.begin();
2016 k != pendingDisconnect.end(); ++k)
2018 if (!pending_unreliable[*k])
2020 m_connection->deletePeer(*k,false);
2025 void ConnectionSendThread::sendAsPacket(u16 peer_id, u8 channelnum,
2026 SharedBuffer<u8> data, bool ack)
2028 OutgoingPacket packet(peer_id, channelnum, data, false, ack);
2029 m_outgoing_queue.push(packet);
2032 ConnectionReceiveThread::ConnectionReceiveThread(unsigned int max_packet_size) :
2033 Thread("ConnectionReceive"),
2038 void * ConnectionReceiveThread::run()
2040 assert(m_connection);
2042 LOG(dout_con<<m_connection->getDesc()
2043 <<"ConnectionReceive thread started"<<std::endl);
2045 PROFILE(std::stringstream ThreadIdentifier);
2046 PROFILE(ThreadIdentifier << "ConnectionReceive: [" << m_connection->getDesc() << "]");
2048 #ifdef DEBUG_CONNECTION_KBPS
2049 u32 curtime = porting::getTimeMs();
2050 u32 lasttime = curtime;
2051 float debug_print_timer = 0.0;
2054 while(!stopRequested()) {
2055 BEGIN_DEBUG_EXCEPTION_HANDLER
2056 PROFILE(ScopeProfiler sp(g_profiler, ThreadIdentifier.str(), SPT_AVG));
2058 #ifdef DEBUG_CONNECTION_KBPS
2060 curtime = porting::getTimeMs();
2061 float dtime = CALC_DTIME(lasttime,curtime);
2064 /* receive packets */
2067 #ifdef DEBUG_CONNECTION_KBPS
2068 debug_print_timer += dtime;
2069 if (debug_print_timer > 20.0) {
2070 debug_print_timer -= 20.0;
2072 std::list<u16> peerids = m_connection->getPeerIDs();
2074 for (std::list<u16>::iterator i = peerids.begin();
2078 PeerHelper peer = m_connection->getPeerNoEx(*i);
2082 float peer_current = 0.0;
2083 float peer_loss = 0.0;
2084 float avg_rate = 0.0;
2085 float avg_loss = 0.0;
2087 for(u16 j=0; j<CHANNEL_COUNT; j++)
2089 peer_current +=peer->channels[j].getCurrentDownloadRateKB();
2090 peer_loss += peer->channels[j].getCurrentLossRateKB();
2091 avg_rate += peer->channels[j].getAvgDownloadRateKB();
2092 avg_loss += peer->channels[j].getAvgLossRateKB();
2095 std::stringstream output;
2096 output << std::fixed << std::setprecision(1);
2097 output << "OUT to Peer " << *i << " RATES (good / loss) " << std::endl;
2098 output << "\tcurrent (sum): " << peer_current << "kb/s "<< peer_loss << "kb/s" << std::endl;
2099 output << "\taverage (sum): " << avg_rate << "kb/s "<< avg_loss << "kb/s" << std::endl;
2100 output << std::setfill(' ');
2101 for(u16 j=0; j<CHANNEL_COUNT; j++)
2103 output << "\tcha " << j << ":"
2104 << " CUR: " << std::setw(6) << peer->channels[j].getCurrentDownloadRateKB() <<"kb/s"
2105 << " AVG: " << std::setw(6) << peer->channels[j].getAvgDownloadRateKB() <<"kb/s"
2106 << " MAX: " << std::setw(6) << peer->channels[j].getMaxDownloadRateKB() <<"kb/s"
2108 << " CUR: " << std::setw(6) << peer->channels[j].getCurrentLossRateKB() <<"kb/s"
2109 << " AVG: " << std::setw(6) << peer->channels[j].getAvgLossRateKB() <<"kb/s"
2110 << " MAX: " << std::setw(6) << peer->channels[j].getMaxLossRateKB() <<"kb/s"
2111 << " / WS: " << peer->channels[j].getWindowSize()
2115 fprintf(stderr,"%s\n",output.str().c_str());
2119 END_DEBUG_EXCEPTION_HANDLER
2122 PROFILE(g_profiler->remove(ThreadIdentifier.str()));
2126 // Receive packets from the network and buffers and create ConnectionEvents
2127 void ConnectionReceiveThread::receive()
2129 // use IPv6 minimum allowed MTU as receive buffer size as this is
2130 // theoretical reliable upper boundary of a udp packet for all IPv6 enabled
2132 unsigned int packet_maxsize = 1500;
2133 SharedBuffer<u8> packetdata(packet_maxsize);
2135 bool packet_queued = true;
2137 unsigned int loop_count = 0;
2139 /* first of all read packets from socket */
2140 /* check for incoming data available */
2141 while( (loop_count < 10) &&
2142 (m_connection->m_udpSocket.WaitData(50))) {
2145 if (packet_queued) {
2146 bool data_left = true;
2148 SharedBuffer<u8> resultdata;
2151 data_left = getFromBuffers(peer_id, resultdata);
2154 e.dataReceived(peer_id, resultdata);
2155 m_connection->putEvent(e);
2158 catch(ProcessedSilentlyException &e) {
2159 /* try reading again */
2162 packet_queued = false;
2166 s32 received_size = m_connection->m_udpSocket.Receive(sender, *packetdata, packet_maxsize);
2168 if ((received_size < BASE_HEADER_SIZE) ||
2169 (readU32(&packetdata[0]) != m_connection->GetProtocolID()))
2171 LOG(derr_con<<m_connection->getDesc()
2172 <<"Receive(): Invalid incoming packet, "
2173 <<"size: " << received_size
2175 << ((received_size >= 4) ? readU32(&packetdata[0]) : -1)
2180 u16 peer_id = readPeerId(*packetdata);
2181 u8 channelnum = readChannel(*packetdata);
2183 if (channelnum > CHANNEL_COUNT-1) {
2184 LOG(derr_con<<m_connection->getDesc()
2185 <<"Receive(): Invalid channel "<<channelnum<<std::endl);
2186 throw InvalidIncomingDataException("Channel doesn't exist");
2189 /* Try to identify peer by sender address (may happen on join) */
2190 if (peer_id == PEER_ID_INEXISTENT) {
2191 peer_id = m_connection->lookupPeer(sender);
2192 // We do not have to remind the peer of its
2193 // peer id as the CONTROLTYPE_SET_PEER_ID
2194 // command was sent reliably.
2197 /* The peer was not found in our lists. Add it. */
2198 if (peer_id == PEER_ID_INEXISTENT) {
2199 peer_id = m_connection->createPeer(sender, MTP_MINETEST_RELIABLE_UDP, 0);
2202 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
2205 LOG(dout_con<<m_connection->getDesc()
2206 <<" got packet from unknown peer_id: "
2207 <<peer_id<<" Ignoring."<<std::endl);
2211 // Validate peer address
2213 Address peer_address;
2215 if (peer->getAddress(MTP_UDP, peer_address)) {
2216 if (peer_address != sender) {
2217 LOG(derr_con<<m_connection->getDesc()
2218 <<m_connection->getDesc()
2219 <<" Peer "<<peer_id<<" sending from different address."
2220 " Ignoring."<<std::endl);
2226 bool invalid_address = true;
2227 if (invalid_address) {
2228 LOG(derr_con<<m_connection->getDesc()
2229 <<m_connection->getDesc()
2230 <<" Peer "<<peer_id<<" unknown."
2231 " Ignoring."<<std::endl);
2236 peer->ResetTimeout();
2238 Channel *channel = 0;
2240 if (dynamic_cast<UDPPeer*>(&peer) != 0)
2242 channel = &(dynamic_cast<UDPPeer*>(&peer)->channels[channelnum]);
2246 channel->UpdateBytesReceived(received_size);
2249 // Throw the received packet to channel->processPacket()
2251 // Make a new SharedBuffer from the data without the base headers
2252 SharedBuffer<u8> strippeddata(received_size - BASE_HEADER_SIZE);
2253 memcpy(*strippeddata, &packetdata[BASE_HEADER_SIZE],
2254 strippeddata.getSize());
2257 // Process it (the result is some data with no headers made by us)
2258 SharedBuffer<u8> resultdata = processPacket
2259 (channel, strippeddata, peer_id, channelnum, false);
2261 LOG(dout_con<<m_connection->getDesc()
2262 <<" ProcessPacket from peer_id: " << peer_id
2263 << ",channel: " << (channelnum & 0xFF) << ", returned "
2264 << resultdata.getSize() << " bytes" <<std::endl);
2267 e.dataReceived(peer_id, resultdata);
2268 m_connection->putEvent(e);
2270 catch(ProcessedSilentlyException &e) {
2272 catch(ProcessedQueued &e) {
2273 packet_queued = true;
2276 catch(InvalidIncomingDataException &e) {
2278 catch(ProcessedSilentlyException &e) {
2283 bool ConnectionReceiveThread::getFromBuffers(u16 &peer_id, SharedBuffer<u8> &dst)
2285 std::list<u16> peerids = m_connection->getPeerIDs();
2287 for(std::list<u16>::iterator j = peerids.begin();
2288 j != peerids.end(); ++j)
2290 PeerHelper peer = m_connection->getPeerNoEx(*j);
2294 if (dynamic_cast<UDPPeer*>(&peer) == 0)
2297 for(u16 i=0; i<CHANNEL_COUNT; i++)
2299 Channel *channel = &(dynamic_cast<UDPPeer*>(&peer))->channels[i];
2301 if (checkIncomingBuffers(channel, peer_id, dst)) {
2309 bool ConnectionReceiveThread::checkIncomingBuffers(Channel *channel,
2310 u16 &peer_id, SharedBuffer<u8> &dst)
2312 u16 firstseqnum = 0;
2313 if (channel->incoming_reliables.getFirstSeqnum(firstseqnum))
2315 if (firstseqnum == channel->readNextIncomingSeqNum())
2317 BufferedPacket p = channel->incoming_reliables.popFirst();
2318 peer_id = readPeerId(*p.data);
2319 u8 channelnum = readChannel(*p.data);
2320 u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]);
2322 LOG(dout_con<<m_connection->getDesc()
2323 <<"UNBUFFERING TYPE_RELIABLE"
2324 <<" seqnum="<<seqnum
2325 <<" peer_id="<<peer_id
2326 <<" channel="<<((int)channelnum&0xff)
2329 channel->incNextIncomingSeqNum();
2331 u32 headers_size = BASE_HEADER_SIZE + RELIABLE_HEADER_SIZE;
2332 // Get out the inside packet and re-process it
2333 SharedBuffer<u8> payload(p.data.getSize() - headers_size);
2334 memcpy(*payload, &p.data[headers_size], payload.getSize());
2336 dst = processPacket(channel, payload, peer_id, channelnum, true);
2343 SharedBuffer<u8> ConnectionReceiveThread::processPacket(Channel *channel,
2344 SharedBuffer<u8> packetdata, u16 peer_id, u8 channelnum, bool reliable)
2346 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
2349 errorstream << "Peer not found (possible timeout)" << std::endl;
2350 throw ProcessedSilentlyException("Peer not found (possible timeout)");
2353 if (packetdata.getSize() < 1)
2354 throw InvalidIncomingDataException("packetdata.getSize() < 1");
2356 u8 type = readU8(&(packetdata[0]));
2358 if (MAX_UDP_PEERS <= 65535 && peer_id >= MAX_UDP_PEERS) {
2359 std::string errmsg = "Invalid peer_id=" + itos(peer_id);
2360 errorstream << errmsg << std::endl;
2361 throw InvalidIncomingDataException(errmsg.c_str());
2364 if (type == TYPE_CONTROL)
2366 if (packetdata.getSize() < 2)
2367 throw InvalidIncomingDataException("packetdata.getSize() < 2");
2369 u8 controltype = readU8(&(packetdata[1]));
2371 if (controltype == CONTROLTYPE_ACK)
2373 assert(channel != NULL);
2375 if (packetdata.getSize() < 4) {
2376 throw InvalidIncomingDataException(
2377 "packetdata.getSize() < 4 (ACK header size)");
2380 u16 seqnum = readU16(&packetdata[2]);
2381 LOG(dout_con<<m_connection->getDesc()
2382 <<" [ CONTROLTYPE_ACK: channelnum="
2383 <<((int)channelnum&0xff)<<", peer_id="<<peer_id
2384 <<", seqnum="<<seqnum<< " ]"<<std::endl);
2388 channel->outgoing_reliables_sent.popSeqnum(seqnum);
2390 // only calculate rtt from straight sent packets
2391 if (p.resend_count == 0) {
2392 // Get round trip time
2393 unsigned int current_time = porting::getTimeMs();
2395 // a overflow is quite unlikely but as it'd result in major
2396 // rtt miscalculation we handle it here
2397 if (current_time > p.absolute_send_time)
2399 float rtt = (current_time - p.absolute_send_time) / 1000.0;
2401 // Let peer calculate stuff according to it
2402 // (avg_rtt and resend_timeout)
2403 dynamic_cast<UDPPeer*>(&peer)->reportRTT(rtt);
2405 else if (p.totaltime > 0)
2407 float rtt = p.totaltime;
2409 // Let peer calculate stuff according to it
2410 // (avg_rtt and resend_timeout)
2411 dynamic_cast<UDPPeer*>(&peer)->reportRTT(rtt);
2414 //put bytes for max bandwidth calculation
2415 channel->UpdateBytesSent(p.data.getSize(),1);
2416 if (channel->outgoing_reliables_sent.size() == 0)
2418 m_connection->TriggerSend();
2421 catch(NotFoundException &e) {
2422 LOG(derr_con<<m_connection->getDesc()
2423 <<"WARNING: ACKed packet not "
2426 channel->UpdatePacketTooLateCounter();
2428 throw ProcessedSilentlyException("Got an ACK");
2430 else if (controltype == CONTROLTYPE_SET_PEER_ID) {
2431 // Got a packet to set our peer id
2432 if (packetdata.getSize() < 4)
2433 throw InvalidIncomingDataException
2434 ("packetdata.getSize() < 4 (SET_PEER_ID header size)");
2435 u16 peer_id_new = readU16(&packetdata[2]);
2436 LOG(dout_con<<m_connection->getDesc()
2437 <<"Got new peer id: "<<peer_id_new<<"... "<<std::endl);
2439 if (m_connection->GetPeerID() != PEER_ID_INEXISTENT)
2441 LOG(derr_con<<m_connection->getDesc()
2442 <<"WARNING: Not changing"
2443 " existing peer id."<<std::endl);
2447 LOG(dout_con<<m_connection->getDesc()<<"changing own peer id"<<std::endl);
2448 m_connection->SetPeerID(peer_id_new);
2451 ConnectionCommand cmd;
2453 SharedBuffer<u8> reply(2);
2454 writeU8(&reply[0], TYPE_CONTROL);
2455 writeU8(&reply[1], CONTROLTYPE_ENABLE_BIG_SEND_WINDOW);
2456 cmd.disableLegacy(PEER_ID_SERVER,reply);
2457 m_connection->putCommand(cmd);
2459 throw ProcessedSilentlyException("Got a SET_PEER_ID");
2461 else if (controltype == CONTROLTYPE_PING)
2463 // Just ignore it, the incoming data already reset
2464 // the timeout counter
2465 LOG(dout_con<<m_connection->getDesc()<<"PING"<<std::endl);
2466 throw ProcessedSilentlyException("Got a PING");
2468 else if (controltype == CONTROLTYPE_DISCO)
2470 // Just ignore it, the incoming data already reset
2471 // the timeout counter
2472 LOG(dout_con<<m_connection->getDesc()
2473 <<"DISCO: Removing peer "<<(peer_id)<<std::endl);
2475 if (m_connection->deletePeer(peer_id, false) == false)
2477 derr_con<<m_connection->getDesc()
2478 <<"DISCO: Peer not found"<<std::endl;
2481 throw ProcessedSilentlyException("Got a DISCO");
2483 else if (controltype == CONTROLTYPE_ENABLE_BIG_SEND_WINDOW)
2485 dynamic_cast<UDPPeer*>(&peer)->setNonLegacyPeer();
2486 throw ProcessedSilentlyException("Got non legacy control");
2489 LOG(derr_con<<m_connection->getDesc()
2490 <<"INVALID TYPE_CONTROL: invalid controltype="
2491 <<((int)controltype&0xff)<<std::endl);
2492 throw InvalidIncomingDataException("Invalid control type");
2495 else if (type == TYPE_ORIGINAL)
2497 if (packetdata.getSize() <= ORIGINAL_HEADER_SIZE)
2498 throw InvalidIncomingDataException
2499 ("packetdata.getSize() <= ORIGINAL_HEADER_SIZE");
2500 LOG(dout_con<<m_connection->getDesc()
2501 <<"RETURNING TYPE_ORIGINAL to user"
2503 // Get the inside packet out and return it
2504 SharedBuffer<u8> payload(packetdata.getSize() - ORIGINAL_HEADER_SIZE);
2505 memcpy(*payload, &(packetdata[ORIGINAL_HEADER_SIZE]), payload.getSize());
2508 else if (type == TYPE_SPLIT)
2510 Address peer_address;
2512 if (peer->getAddress(MTP_UDP, peer_address)) {
2514 // We have to create a packet again for buffering
2515 // This isn't actually too bad an idea.
2516 BufferedPacket packet = makePacket(
2519 m_connection->GetProtocolID(),
2523 // Buffer the packet
2524 SharedBuffer<u8> data =
2525 peer->addSpiltPacket(channelnum,packet,reliable);
2527 if (data.getSize() != 0)
2529 LOG(dout_con<<m_connection->getDesc()
2530 <<"RETURNING TYPE_SPLIT: Constructed full data, "
2531 <<"size="<<data.getSize()<<std::endl);
2534 LOG(dout_con<<m_connection->getDesc()<<"BUFFERED TYPE_SPLIT"<<std::endl);
2535 throw ProcessedSilentlyException("Buffered a split packet chunk");
2538 //TODO throw some error
2541 else if (type == TYPE_RELIABLE)
2543 assert(channel != NULL);
2545 // Recursive reliable packets not allowed
2547 throw InvalidIncomingDataException("Found nested reliable packets");
2549 if (packetdata.getSize() < RELIABLE_HEADER_SIZE)
2550 throw InvalidIncomingDataException
2551 ("packetdata.getSize() < RELIABLE_HEADER_SIZE");
2553 u16 seqnum = readU16(&packetdata[1]);
2554 bool is_future_packet = false;
2555 bool is_old_packet = false;
2557 /* packet is within our receive window send ack */
2558 if (seqnum_in_window(seqnum, channel->readNextIncomingSeqNum(),MAX_RELIABLE_WINDOW_SIZE))
2560 m_connection->sendAck(peer_id,channelnum,seqnum);
2563 is_future_packet = seqnum_higher(seqnum, channel->readNextIncomingSeqNum());
2564 is_old_packet = seqnum_higher(channel->readNextIncomingSeqNum(), seqnum);
2567 /* packet is not within receive window, don't send ack. *
2568 * if this was a valid packet it's gonna be retransmitted */
2569 if (is_future_packet)
2571 throw ProcessedSilentlyException("Received packet newer then expected, not sending ack");
2574 /* seems like our ack was lost, send another one for a old packet */
2577 LOG(dout_con<<m_connection->getDesc()
2578 << "RE-SENDING ACK: peer_id: " << peer_id
2579 << ", channel: " << (channelnum&0xFF)
2580 << ", seqnum: " << seqnum << std::endl;)
2581 m_connection->sendAck(peer_id,channelnum,seqnum);
2583 // we already have this packet so this one was on wire at least
2584 // the current timeout
2585 // we don't know how long this packet was on wire don't do silly guessing
2586 // dynamic_cast<UDPPeer*>(&peer)->reportRTT(dynamic_cast<UDPPeer*>(&peer)->getResendTimeout());
2588 throw ProcessedSilentlyException("Retransmitting ack for old packet");
2592 if (seqnum != channel->readNextIncomingSeqNum())
2594 Address peer_address;
2596 // this is a reliable packet so we have a udp address for sure
2597 peer->getAddress(MTP_MINETEST_RELIABLE_UDP, peer_address);
2598 // This one comes later, buffer it.
2599 // Actually we have to make a packet to buffer one.
2600 // Well, we have all the ingredients, so just do it.
2601 BufferedPacket packet = con::makePacket(
2604 m_connection->GetProtocolID(),
2608 channel->incoming_reliables.insert(packet,channel->readNextIncomingSeqNum());
2610 LOG(dout_con<<m_connection->getDesc()
2611 << "BUFFERING, TYPE_RELIABLE peer_id: " << peer_id
2612 << ", channel: " << (channelnum&0xFF)
2613 << ", seqnum: " << seqnum << std::endl;)
2615 throw ProcessedQueued("Buffered future reliable packet");
2617 catch(AlreadyExistsException &e)
2620 catch(IncomingDataCorruption &e)
2622 ConnectionCommand discon;
2623 discon.disconnect_peer(peer_id);
2624 m_connection->putCommand(discon);
2626 LOG(derr_con<<m_connection->getDesc()
2627 << "INVALID, TYPE_RELIABLE peer_id: " << peer_id
2628 << ", channel: " << (channelnum&0xFF)
2629 << ", seqnum: " << seqnum
2630 << "DROPPING CLIENT!" << std::endl;)
2634 /* we got a packet to process right now */
2635 LOG(dout_con<<m_connection->getDesc()
2636 << "RECURSIVE, TYPE_RELIABLE peer_id: " << peer_id
2637 << ", channel: " << (channelnum&0xFF)
2638 << ", seqnum: " << seqnum << std::endl;)
2641 /* check for resend case */
2642 u16 queued_seqnum = 0;
2643 if (channel->incoming_reliables.getFirstSeqnum(queued_seqnum))
2645 if (queued_seqnum == seqnum)
2647 BufferedPacket queued_packet = channel->incoming_reliables.popFirst();
2648 /** TODO find a way to verify the new against the old packet */
2652 channel->incNextIncomingSeqNum();
2654 // Get out the inside packet and re-process it
2655 SharedBuffer<u8> payload(packetdata.getSize() - RELIABLE_HEADER_SIZE);
2656 memcpy(*payload, &packetdata[RELIABLE_HEADER_SIZE], payload.getSize());
2658 return processPacket(channel, payload, peer_id, channelnum, true);
2662 derr_con<<m_connection->getDesc()
2663 <<"Got invalid type="<<((int)type&0xff)<<std::endl;
2664 throw InvalidIncomingDataException("Invalid packet type");
2667 // We should never get here.
2668 FATAL_ERROR("Invalid execution point");
2675 Connection::Connection(u32 protocol_id, u32 max_packet_size, float timeout,
2676 bool ipv6, PeerHandler *peerhandler) :
2681 m_protocol_id(protocol_id),
2682 m_sendThread(max_packet_size, timeout),
2683 m_receiveThread(max_packet_size),
2685 m_bc_peerhandler(peerhandler),
2686 m_bc_receive_timeout(0),
2687 m_shutting_down(false),
2688 m_next_remote_peer_id(2)
2691 m_udpSocket.setTimeoutMs(5);
2693 m_sendThread.setParent(this);
2694 m_receiveThread.setParent(this);
2696 m_sendThread.start();
2697 m_receiveThread.start();
2702 Connection::~Connection()
2704 m_shutting_down = true;
2705 // request threads to stop
2706 m_sendThread.stop();
2707 m_receiveThread.stop();
2709 //TODO for some unkonwn reason send/receive threads do not exit as they're
2710 // supposed to be but wait on peer timeout. To speed up shutdown we reduce
2711 // timeout to half a second.
2712 m_sendThread.setPeerTimeout(0.5);
2714 // wait for threads to finish
2715 m_sendThread.wait();
2716 m_receiveThread.wait();
2719 for(std::map<u16, Peer*>::iterator
2720 j = m_peers.begin();
2721 j != m_peers.end(); ++j)
2727 /* Internal stuff */
2728 void Connection::putEvent(ConnectionEvent &e)
2730 assert(e.type != CONNEVENT_NONE); // Pre-condition
2731 m_event_queue.push_back(e);
2734 PeerHelper Connection::getPeer(u16 peer_id)
2736 MutexAutoLock peerlock(m_peers_mutex);
2737 std::map<u16, Peer*>::iterator node = m_peers.find(peer_id);
2739 if (node == m_peers.end()) {
2740 throw PeerNotFoundException("GetPeer: Peer not found (possible timeout)");
2744 FATAL_ERROR_IF(node->second->id != peer_id, "Invalid peer id");
2746 return PeerHelper(node->second);
2749 PeerHelper Connection::getPeerNoEx(u16 peer_id)
2751 MutexAutoLock peerlock(m_peers_mutex);
2752 std::map<u16, Peer*>::iterator node = m_peers.find(peer_id);
2754 if (node == m_peers.end()) {
2755 return PeerHelper(NULL);
2759 FATAL_ERROR_IF(node->second->id != peer_id, "Invalid peer id");
2761 return PeerHelper(node->second);
2764 /* find peer_id for address */
2765 u16 Connection::lookupPeer(Address& sender)
2767 MutexAutoLock peerlock(m_peers_mutex);
2768 std::map<u16, Peer*>::iterator j;
2769 j = m_peers.begin();
2770 for(; j != m_peers.end(); ++j)
2772 Peer *peer = j->second;
2773 if (peer->isPendingDeletion())
2778 if ((peer->getAddress(MTP_MINETEST_RELIABLE_UDP, tocheck)) && (tocheck == sender))
2781 if ((peer->getAddress(MTP_UDP, tocheck)) && (tocheck == sender))
2785 return PEER_ID_INEXISTENT;
2788 std::list<Peer*> Connection::getPeers()
2790 std::list<Peer*> list;
2791 for(std::map<u16, Peer*>::iterator j = m_peers.begin();
2792 j != m_peers.end(); ++j)
2794 Peer *peer = j->second;
2795 list.push_back(peer);
2800 bool Connection::deletePeer(u16 peer_id, bool timeout)
2804 /* lock list as short as possible */
2806 MutexAutoLock peerlock(m_peers_mutex);
2807 if (m_peers.find(peer_id) == m_peers.end())
2809 peer = m_peers[peer_id];
2810 m_peers.erase(peer_id);
2811 m_peer_ids.remove(peer_id);
2814 Address peer_address;
2815 //any peer has a primary address this never fails!
2816 peer->getAddress(MTP_PRIMARY, peer_address);
2819 e.peerRemoved(peer_id, timeout, peer_address);
2829 ConnectionEvent Connection::waitEvent(u32 timeout_ms)
2832 return m_event_queue.pop_front(timeout_ms);
2833 } catch(ItemNotFoundException &ex) {
2835 e.type = CONNEVENT_NONE;
2840 void Connection::putCommand(ConnectionCommand &c)
2842 if (!m_shutting_down) {
2843 m_command_queue.push_back(c);
2844 m_sendThread.Trigger();
2848 void Connection::Serve(Address bind_addr)
2850 ConnectionCommand c;
2855 void Connection::Connect(Address address)
2857 ConnectionCommand c;
2862 bool Connection::Connected()
2864 MutexAutoLock peerlock(m_peers_mutex);
2866 if (m_peers.size() != 1)
2869 std::map<u16, Peer*>::iterator node = m_peers.find(PEER_ID_SERVER);
2870 if (node == m_peers.end())
2873 if (m_peer_id == PEER_ID_INEXISTENT)
2879 void Connection::Disconnect()
2881 ConnectionCommand c;
2886 void Connection::Receive(NetworkPacket* pkt)
2889 ConnectionEvent e = waitEvent(m_bc_receive_timeout);
2890 if (e.type != CONNEVENT_NONE)
2891 LOG(dout_con << getDesc() << ": Receive: got event: "
2892 << e.describe() << std::endl);
2894 case CONNEVENT_NONE:
2895 throw NoIncomingDataException("No incoming data");
2896 case CONNEVENT_DATA_RECEIVED:
2897 // Data size is lesser than command size, ignoring packet
2898 if (e.data.getSize() < 2) {
2902 pkt->putRawPacket(*e.data, e.data.getSize(), e.peer_id);
2904 case CONNEVENT_PEER_ADDED: {
2905 UDPPeer tmp(e.peer_id, e.address, this);
2906 if (m_bc_peerhandler)
2907 m_bc_peerhandler->peerAdded(&tmp);
2910 case CONNEVENT_PEER_REMOVED: {
2911 UDPPeer tmp(e.peer_id, e.address, this);
2912 if (m_bc_peerhandler)
2913 m_bc_peerhandler->deletingPeer(&tmp, e.timeout);
2916 case CONNEVENT_BIND_FAILED:
2917 throw ConnectionBindFailed("Failed to bind socket "
2918 "(port already in use?)");
2921 throw NoIncomingDataException("No incoming data");
2924 void Connection::Send(u16 peer_id, u8 channelnum,
2925 NetworkPacket* pkt, bool reliable)
2927 assert(channelnum < CHANNEL_COUNT); // Pre-condition
2929 ConnectionCommand c;
2931 c.send(peer_id, channelnum, pkt, reliable);
2935 Address Connection::GetPeerAddress(u16 peer_id)
2937 PeerHelper peer = getPeerNoEx(peer_id);
2940 throw PeerNotFoundException("No address for peer found!");
2941 Address peer_address;
2942 peer->getAddress(MTP_PRIMARY, peer_address);
2943 return peer_address;
2946 float Connection::getPeerStat(u16 peer_id, rtt_stat_type type)
2948 PeerHelper peer = getPeerNoEx(peer_id);
2949 if (!peer) return -1;
2950 return peer->getStat(type);
2953 float Connection::getLocalStat(rate_stat_type type)
2955 PeerHelper peer = getPeerNoEx(PEER_ID_SERVER);
2957 FATAL_ERROR_IF(!peer, "Connection::getLocalStat we couldn't get our own peer? are you serious???");
2961 for (u16 j=0; j<CHANNEL_COUNT; j++) {
2964 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getCurrentDownloadRateKB();
2967 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getAvgDownloadRateKB();
2970 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getCurrentIncomingRateKB();
2973 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getAvgIncomingRateKB();
2976 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getAvgLossRateKB();
2979 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getCurrentLossRateKB();
2982 FATAL_ERROR("Connection::getLocalStat Invalid stat type");
2988 u16 Connection::createPeer(Address& sender, MTProtocols protocol, int fd)
2990 // Somebody wants to make a new connection
2992 // Get a unique peer id (2 or higher)
2993 u16 peer_id_new = m_next_remote_peer_id;
2994 u16 overflow = MAX_UDP_PEERS;
2997 Find an unused peer id
2999 MutexAutoLock lock(m_peers_mutex);
3000 bool out_of_ids = false;
3003 if (m_peers.find(peer_id_new) == m_peers.end())
3006 // Check for overflow
3007 if (peer_id_new == overflow) {
3015 errorstream << getDesc() << " ran out of peer ids" << std::endl;
3016 return PEER_ID_INEXISTENT;
3021 peer = new UDPPeer(peer_id_new, sender, this);
3023 m_peers[peer->id] = peer;
3024 m_peer_ids.push_back(peer->id);
3026 m_next_remote_peer_id = (peer_id_new +1 ) % MAX_UDP_PEERS;
3028 LOG(dout_con << getDesc()
3029 << "createPeer(): giving peer_id=" << peer_id_new << std::endl);
3031 ConnectionCommand cmd;
3032 SharedBuffer<u8> reply(4);
3033 writeU8(&reply[0], TYPE_CONTROL);
3034 writeU8(&reply[1], CONTROLTYPE_SET_PEER_ID);
3035 writeU16(&reply[2], peer_id_new);
3036 cmd.createPeer(peer_id_new,reply);
3039 // Create peer addition event
3041 e.peerAdded(peer_id_new, sender);
3044 // We're now talking to a valid peer_id
3048 void Connection::PrintInfo(std::ostream &out)
3050 m_info_mutex.lock();
3051 out<<getDesc()<<": ";
3052 m_info_mutex.unlock();
3055 void Connection::PrintInfo()
3057 PrintInfo(dout_con);
3060 const std::string Connection::getDesc()
3062 return std::string("con(")+
3063 itos(m_udpSocket.GetHandle())+"/"+itos(m_peer_id)+")";
3066 void Connection::DisconnectPeer(u16 peer_id)
3068 ConnectionCommand discon;
3069 discon.disconnect_peer(peer_id);
3073 void Connection::sendAck(u16 peer_id, u8 channelnum, u16 seqnum)
3075 assert(channelnum < CHANNEL_COUNT); // Pre-condition
3077 LOG(dout_con<<getDesc()
3078 <<" Queuing ACK command to peer_id: " << peer_id <<
3079 " channel: " << (channelnum & 0xFF) <<
3080 " seqnum: " << seqnum << std::endl);
3082 ConnectionCommand c;
3083 SharedBuffer<u8> ack(4);
3084 writeU8(&ack[0], TYPE_CONTROL);
3085 writeU8(&ack[1], CONTROLTYPE_ACK);
3086 writeU16(&ack[2], seqnum);
3088 c.ack(peer_id, channelnum, ack);
3090 m_sendThread.Trigger();
3093 UDPPeer* Connection::createServerPeer(Address& address)
3095 if (getPeerNoEx(PEER_ID_SERVER) != 0)
3097 throw ConnectionException("Already connected to a server");
3100 UDPPeer *peer = new UDPPeer(PEER_ID_SERVER, address, this);
3103 MutexAutoLock lock(m_peers_mutex);
3104 m_peers[peer->id] = peer;
3105 m_peer_ids.push_back(peer->id);