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 JMutex log_message_mutex;
48 JMutexAutoLock 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 static u16 readPeerId(u8 *packetdata)
76 return readU16(&packetdata[4]);
78 static u8 readChannel(u8 *packetdata)
80 return readU8(&packetdata[6]);
83 BufferedPacket makePacket(Address &address, u8 *data, u32 datasize,
84 u32 protocol_id, u16 sender_peer_id, u8 channel)
86 u32 packet_size = datasize + BASE_HEADER_SIZE;
87 BufferedPacket p(packet_size);
90 writeU32(&p.data[0], protocol_id);
91 writeU16(&p.data[4], sender_peer_id);
92 writeU8(&p.data[6], channel);
94 memcpy(&p.data[BASE_HEADER_SIZE], data, datasize);
99 BufferedPacket makePacket(Address &address, SharedBuffer<u8> &data,
100 u32 protocol_id, u16 sender_peer_id, u8 channel)
102 return makePacket(address, *data, data.getSize(),
103 protocol_id, sender_peer_id, channel);
106 SharedBuffer<u8> makeOriginalPacket(
107 SharedBuffer<u8> data)
110 u32 packet_size = data.getSize() + header_size;
111 SharedBuffer<u8> b(packet_size);
113 writeU8(&(b[0]), TYPE_ORIGINAL);
114 if (data.getSize() > 0) {
115 memcpy(&(b[header_size]), *data, data.getSize());
120 std::list<SharedBuffer<u8> > makeSplitPacket(
121 SharedBuffer<u8> data,
125 // Chunk packets, containing the TYPE_SPLIT header
126 std::list<SharedBuffer<u8> > chunks;
128 u32 chunk_header_size = 7;
129 u32 maximum_data_size = chunksize_max - chunk_header_size;
135 end = start + maximum_data_size - 1;
136 if (end > data.getSize() - 1)
137 end = data.getSize() - 1;
139 u32 payload_size = end - start + 1;
140 u32 packet_size = chunk_header_size + payload_size;
142 SharedBuffer<u8> chunk(packet_size);
144 writeU8(&chunk[0], TYPE_SPLIT);
145 writeU16(&chunk[1], seqnum);
146 // [3] u16 chunk_count is written at next stage
147 writeU16(&chunk[5], chunk_num);
148 memcpy(&chunk[chunk_header_size], &data[start], payload_size);
150 chunks.push_back(chunk);
156 while(end != data.getSize() - 1);
158 for(std::list<SharedBuffer<u8> >::iterator i = chunks.begin();
159 i != chunks.end(); ++i)
162 writeU16(&((*i)[3]), chunk_count);
168 std::list<SharedBuffer<u8> > makeAutoSplitPacket(
169 SharedBuffer<u8> data,
173 u32 original_header_size = 1;
174 std::list<SharedBuffer<u8> > list;
175 if (data.getSize() + original_header_size > chunksize_max)
177 list = makeSplitPacket(data, chunksize_max, split_seqnum);
183 list.push_back(makeOriginalPacket(data));
188 SharedBuffer<u8> makeReliablePacket(
189 SharedBuffer<u8> data,
193 u32 packet_size = data.getSize() + header_size;
194 SharedBuffer<u8> b(packet_size);
196 writeU8(&b[0], TYPE_RELIABLE);
197 writeU16(&b[1], seqnum);
199 memcpy(&b[header_size], *data, data.getSize());
208 ReliablePacketBuffer::ReliablePacketBuffer(): m_list_size(0) {}
210 void ReliablePacketBuffer::print()
212 JMutexAutoLock listlock(m_list_mutex);
213 LOG(dout_con<<"Dump of ReliablePacketBuffer:" << std::endl);
214 unsigned int index = 0;
215 for(std::list<BufferedPacket>::iterator i = m_list.begin();
219 u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
220 LOG(dout_con<<index<< ":" << s << std::endl);
224 bool ReliablePacketBuffer::empty()
226 JMutexAutoLock listlock(m_list_mutex);
227 return m_list.empty();
230 u32 ReliablePacketBuffer::size()
235 bool ReliablePacketBuffer::containsPacket(u16 seqnum)
237 return !(findPacket(seqnum) == m_list.end());
240 RPBSearchResult ReliablePacketBuffer::findPacket(u16 seqnum)
242 std::list<BufferedPacket>::iterator i = m_list.begin();
243 for(; i != m_list.end(); ++i)
245 u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
246 /*dout_con<<"findPacket(): finding seqnum="<<seqnum
247 <<", comparing to s="<<s<<std::endl;*/
253 RPBSearchResult ReliablePacketBuffer::notFound()
257 bool ReliablePacketBuffer::getFirstSeqnum(u16& result)
259 JMutexAutoLock listlock(m_list_mutex);
262 BufferedPacket p = *m_list.begin();
263 result = readU16(&p.data[BASE_HEADER_SIZE+1]);
267 BufferedPacket ReliablePacketBuffer::popFirst()
269 JMutexAutoLock listlock(m_list_mutex);
271 throw NotFoundException("Buffer is empty");
272 BufferedPacket p = *m_list.begin();
273 m_list.erase(m_list.begin());
276 if (m_list_size == 0) {
277 m_oldest_non_answered_ack = 0;
279 m_oldest_non_answered_ack =
280 readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]);
284 BufferedPacket ReliablePacketBuffer::popSeqnum(u16 seqnum)
286 JMutexAutoLock listlock(m_list_mutex);
287 RPBSearchResult r = findPacket(seqnum);
288 if (r == notFound()) {
289 LOG(dout_con<<"Sequence number: " << seqnum
290 << " not found in reliable buffer"<<std::endl);
291 throw NotFoundException("seqnum not found in buffer");
293 BufferedPacket p = *r;
296 RPBSearchResult next = r;
298 if (next != notFound()) {
299 u16 s = readU16(&(next->data[BASE_HEADER_SIZE+1]));
300 m_oldest_non_answered_ack = s;
306 if (m_list_size == 0)
307 { m_oldest_non_answered_ack = 0; }
309 { m_oldest_non_answered_ack = readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]); }
312 void ReliablePacketBuffer::insert(BufferedPacket &p,u16 next_expected)
314 JMutexAutoLock listlock(m_list_mutex);
315 if (p.data.getSize() < BASE_HEADER_SIZE + 3) {
316 errorstream << "ReliablePacketBuffer::insert(): Invalid data size for "
317 "reliable packet" << std::endl;
320 u8 type = readU8(&p.data[BASE_HEADER_SIZE + 0]);
321 if (type != TYPE_RELIABLE) {
322 errorstream << "ReliablePacketBuffer::insert(): type is not reliable"
326 u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE + 1]);
328 if (!seqnum_in_window(seqnum, next_expected, MAX_RELIABLE_WINDOW_SIZE)) {
329 errorstream << "ReliablePacketBuffer::insert(): seqnum is outside of "
330 "expected window " << std::endl;
333 if (seqnum == next_expected) {
334 errorstream << "ReliablePacketBuffer::insert(): seqnum is next expected"
340 sanity_check(m_list_size <= SEQNUM_MAX+1); // FIXME: Handle the error?
342 // Find the right place for the packet and insert it there
343 // If list is empty, just add it
347 m_oldest_non_answered_ack = seqnum;
352 // Otherwise find the right place
353 std::list<BufferedPacket>::iterator i = m_list.begin();
354 // Find the first packet in the list which has a higher seqnum
355 u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
357 /* case seqnum is smaller then next_expected seqnum */
358 /* this is true e.g. on wrap around */
359 if (seqnum < next_expected) {
360 while(((s < seqnum) || (s >= next_expected)) && (i != m_list.end())) {
362 if (i != m_list.end())
363 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
366 /* non wrap around case (at least for incoming and next_expected */
369 while(((s < seqnum) && (s >= next_expected)) && (i != m_list.end())) {
371 if (i != m_list.end())
372 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
378 (readU16(&(i->data[BASE_HEADER_SIZE+1])) != seqnum) ||
379 (i->data.getSize() != p.data.getSize()) ||
380 (i->address != p.address)
383 /* if this happens your maximum transfer window may be to big */
385 "Duplicated seqnum %d non matching packet detected:\n",
387 fprintf(stderr, "Old: seqnum: %05d size: %04d, address: %s\n",
388 readU16(&(i->data[BASE_HEADER_SIZE+1])),i->data.getSize(),
389 i->address.serializeString().c_str());
390 fprintf(stderr, "New: seqnum: %05d size: %04u, address: %s\n",
391 readU16(&(p.data[BASE_HEADER_SIZE+1])),p.data.getSize(),
392 p.address.serializeString().c_str());
393 throw IncomingDataCorruption("duplicated packet isn't same as original one");
396 /* nothing to do this seems to be a resent packet */
397 /* for paranoia reason data should be compared */
400 /* insert or push back */
401 else if (i != m_list.end()) {
408 /* update last packet number */
409 m_oldest_non_answered_ack = readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]);
412 void ReliablePacketBuffer::incrementTimeouts(float dtime)
414 JMutexAutoLock listlock(m_list_mutex);
415 for(std::list<BufferedPacket>::iterator i = m_list.begin();
416 i != m_list.end(); ++i)
419 i->totaltime += dtime;
423 std::list<BufferedPacket> ReliablePacketBuffer::getTimedOuts(float timeout,
424 unsigned int max_packets)
426 JMutexAutoLock listlock(m_list_mutex);
427 std::list<BufferedPacket> timed_outs;
428 for(std::list<BufferedPacket>::iterator i = m_list.begin();
429 i != m_list.end(); ++i)
431 if (i->time >= timeout) {
432 timed_outs.push_back(*i);
434 //this packet will be sent right afterwards reset timeout here
436 if (timed_outs.size() >= max_packets)
447 IncomingSplitBuffer::~IncomingSplitBuffer()
449 JMutexAutoLock listlock(m_map_mutex);
450 for(std::map<u16, IncomingSplitPacket*>::iterator i = m_buf.begin();
451 i != m_buf.end(); ++i)
457 This will throw a GotSplitPacketException when a full
458 split packet is constructed.
460 SharedBuffer<u8> IncomingSplitBuffer::insert(BufferedPacket &p, bool reliable)
462 JMutexAutoLock listlock(m_map_mutex);
463 u32 headersize = BASE_HEADER_SIZE + 7;
464 if (p.data.getSize() < headersize) {
465 errorstream << "Invalid data size for split packet" << std::endl;
466 return SharedBuffer<u8>();
468 u8 type = readU8(&p.data[BASE_HEADER_SIZE+0]);
469 u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]);
470 u16 chunk_count = readU16(&p.data[BASE_HEADER_SIZE+3]);
471 u16 chunk_num = readU16(&p.data[BASE_HEADER_SIZE+5]);
473 if (type != TYPE_SPLIT) {
474 errorstream << "IncomingSplitBuffer::insert(): type is not split"
476 return SharedBuffer<u8>();
479 // Add if doesn't exist
480 if (m_buf.find(seqnum) == m_buf.end())
482 IncomingSplitPacket *sp = new IncomingSplitPacket();
483 sp->chunk_count = chunk_count;
484 sp->reliable = reliable;
488 IncomingSplitPacket *sp = m_buf[seqnum];
490 // TODO: These errors should be thrown or something? Dunno.
491 if (chunk_count != sp->chunk_count)
492 LOG(derr_con<<"Connection: WARNING: chunk_count="<<chunk_count
493 <<" != sp->chunk_count="<<sp->chunk_count
495 if (reliable != sp->reliable)
496 LOG(derr_con<<"Connection: WARNING: reliable="<<reliable
497 <<" != sp->reliable="<<sp->reliable
500 // If chunk already exists, ignore it.
501 // Sometimes two identical packets may arrive when there is network
502 // lag and the server re-sends stuff.
503 if (sp->chunks.find(chunk_num) != sp->chunks.end())
504 return SharedBuffer<u8>();
506 // Cut chunk data out of packet
507 u32 chunkdatasize = p.data.getSize() - headersize;
508 SharedBuffer<u8> chunkdata(chunkdatasize);
509 memcpy(*chunkdata, &(p.data[headersize]), chunkdatasize);
511 // Set chunk data in buffer
512 sp->chunks[chunk_num] = chunkdata;
514 // If not all chunks are received, return empty buffer
515 if (sp->allReceived() == false)
516 return SharedBuffer<u8>();
518 // Calculate total size
520 for(std::map<u16, SharedBuffer<u8> >::iterator i = sp->chunks.begin();
521 i != sp->chunks.end(); ++i)
523 totalsize += i->second.getSize();
526 SharedBuffer<u8> fulldata(totalsize);
528 // Copy chunks to data buffer
530 for(u32 chunk_i=0; chunk_i<sp->chunk_count;
533 SharedBuffer<u8> buf = sp->chunks[chunk_i];
534 u16 chunkdatasize = buf.getSize();
535 memcpy(&fulldata[start], *buf, chunkdatasize);
536 start += chunkdatasize;;
539 // Remove sp from buffer
545 void IncomingSplitBuffer::removeUnreliableTimedOuts(float dtime, float timeout)
547 std::list<u16> remove_queue;
549 JMutexAutoLock listlock(m_map_mutex);
550 for(std::map<u16, IncomingSplitPacket*>::iterator i = m_buf.begin();
551 i != m_buf.end(); ++i)
553 IncomingSplitPacket *p = i->second;
554 // Reliable ones are not removed by timeout
555 if (p->reliable == true)
558 if (p->time >= timeout)
559 remove_queue.push_back(i->first);
562 for(std::list<u16>::iterator j = remove_queue.begin();
563 j != remove_queue.end(); ++j)
565 JMutexAutoLock listlock(m_map_mutex);
566 LOG(dout_con<<"NOTE: Removing timed out unreliable split packet"<<std::endl);
577 window_size(MIN_RELIABLE_WINDOW_SIZE),
578 next_incoming_seqnum(SEQNUM_INITIAL),
579 next_outgoing_seqnum(SEQNUM_INITIAL),
580 next_outgoing_split_seqnum(SEQNUM_INITIAL),
581 current_packet_loss(0),
582 current_packet_too_late(0),
583 current_packet_successfull(0),
584 packet_loss_counter(0),
585 current_bytes_transfered(0),
586 current_bytes_received(0),
587 current_bytes_lost(0),
591 max_incoming_kbps(0.0),
592 cur_incoming_kbps(0.0),
593 avg_incoming_kbps(0.0),
606 u16 Channel::readNextIncomingSeqNum()
608 JMutexAutoLock internal(m_internal_mutex);
609 return next_incoming_seqnum;
612 u16 Channel::incNextIncomingSeqNum()
614 JMutexAutoLock internal(m_internal_mutex);
615 u16 retval = next_incoming_seqnum;
616 next_incoming_seqnum++;
620 u16 Channel::readNextSplitSeqNum()
622 JMutexAutoLock internal(m_internal_mutex);
623 return next_outgoing_split_seqnum;
625 void Channel::setNextSplitSeqNum(u16 seqnum)
627 JMutexAutoLock internal(m_internal_mutex);
628 next_outgoing_split_seqnum = seqnum;
631 u16 Channel::getOutgoingSequenceNumber(bool& successful)
633 JMutexAutoLock internal(m_internal_mutex);
634 u16 retval = next_outgoing_seqnum;
635 u16 lowest_unacked_seqnumber;
637 /* shortcut if there ain't any packet in outgoing list */
638 if (outgoing_reliables_sent.empty())
640 next_outgoing_seqnum++;
644 if (outgoing_reliables_sent.getFirstSeqnum(lowest_unacked_seqnumber))
646 if (lowest_unacked_seqnumber < next_outgoing_seqnum) {
647 // ugly cast but this one is required in order to tell compiler we
648 // know about difference of two unsigned may be negative in general
649 // but we already made sure it won't happen in this case
650 if (((u16)(next_outgoing_seqnum - lowest_unacked_seqnumber)) > window_size) {
656 // ugly cast but this one is required in order to tell compiler we
657 // know about difference of two unsigned may be negative in general
658 // but we already made sure it won't happen in this case
659 if ((next_outgoing_seqnum + (u16)(SEQNUM_MAX - lowest_unacked_seqnumber)) >
667 next_outgoing_seqnum++;
671 u16 Channel::readOutgoingSequenceNumber()
673 JMutexAutoLock internal(m_internal_mutex);
674 return next_outgoing_seqnum;
677 bool Channel::putBackSequenceNumber(u16 seqnum)
679 if (((seqnum + 1) % (SEQNUM_MAX+1)) == next_outgoing_seqnum) {
681 next_outgoing_seqnum = seqnum;
687 void Channel::UpdateBytesSent(unsigned int bytes, unsigned int packets)
689 JMutexAutoLock internal(m_internal_mutex);
690 current_bytes_transfered += bytes;
691 current_packet_successfull += packets;
694 void Channel::UpdateBytesReceived(unsigned int bytes) {
695 JMutexAutoLock internal(m_internal_mutex);
696 current_bytes_received += bytes;
699 void Channel::UpdateBytesLost(unsigned int bytes)
701 JMutexAutoLock internal(m_internal_mutex);
702 current_bytes_lost += bytes;
706 void Channel::UpdatePacketLossCounter(unsigned int count)
708 JMutexAutoLock internal(m_internal_mutex);
709 current_packet_loss += count;
712 void Channel::UpdatePacketTooLateCounter()
714 JMutexAutoLock internal(m_internal_mutex);
715 current_packet_too_late++;
718 void Channel::UpdateTimers(float dtime,bool legacy_peer)
720 bpm_counter += dtime;
721 packet_loss_counter += dtime;
723 if (packet_loss_counter > 1.0)
725 packet_loss_counter -= 1.0;
727 unsigned int packet_loss = 11; /* use a neutral value for initialization */
728 unsigned int packets_successfull = 0;
729 //unsigned int packet_too_late = 0;
731 bool reasonable_amount_of_data_transmitted = false;
734 JMutexAutoLock internal(m_internal_mutex);
735 packet_loss = current_packet_loss;
736 //packet_too_late = current_packet_too_late;
737 packets_successfull = current_packet_successfull;
739 if (current_bytes_transfered > (unsigned int) (window_size*512/2))
741 reasonable_amount_of_data_transmitted = true;
743 current_packet_loss = 0;
744 current_packet_too_late = 0;
745 current_packet_successfull = 0;
748 /* dynamic window size is only available for non legacy peers */
750 float successfull_to_lost_ratio = 0.0;
753 if (packets_successfull > 0) {
754 successfull_to_lost_ratio = packet_loss/packets_successfull;
756 else if (packet_loss > 0)
760 MIN_RELIABLE_WINDOW_SIZE);
766 if ((successfull_to_lost_ratio < 0.01) &&
767 (window_size < MAX_RELIABLE_WINDOW_SIZE))
769 /* don't even think about increasing if we didn't even
770 * use major parts of our window */
771 if (reasonable_amount_of_data_transmitted)
774 MAX_RELIABLE_WINDOW_SIZE);
776 else if ((successfull_to_lost_ratio < 0.05) &&
777 (window_size < MAX_RELIABLE_WINDOW_SIZE))
779 /* don't even think about increasing if we didn't even
780 * use major parts of our window */
781 if (reasonable_amount_of_data_transmitted)
784 MAX_RELIABLE_WINDOW_SIZE);
786 else if (successfull_to_lost_ratio > 0.15)
790 MIN_RELIABLE_WINDOW_SIZE);
792 else if (successfull_to_lost_ratio > 0.1)
796 MIN_RELIABLE_WINDOW_SIZE);
802 if (bpm_counter > 10.0)
805 JMutexAutoLock internal(m_internal_mutex);
807 (((float) current_bytes_transfered)/bpm_counter)/1024.0;
808 current_bytes_transfered = 0;
810 (((float) current_bytes_lost)/bpm_counter)/1024.0;
811 current_bytes_lost = 0;
813 (((float) current_bytes_received)/bpm_counter)/1024.0;
814 current_bytes_received = 0;
818 if (cur_kbps > max_kbps)
823 if (cur_kbps_lost > max_kbps_lost)
825 max_kbps_lost = cur_kbps_lost;
828 if (cur_incoming_kbps > max_incoming_kbps) {
829 max_incoming_kbps = cur_incoming_kbps;
832 rate_samples = MYMIN(rate_samples+1,10);
833 float old_fraction = ((float) (rate_samples-1) )/( (float) rate_samples);
834 avg_kbps = avg_kbps * old_fraction +
835 cur_kbps * (1.0 - old_fraction);
836 avg_kbps_lost = avg_kbps_lost * old_fraction +
837 cur_kbps_lost * (1.0 - old_fraction);
838 avg_incoming_kbps = avg_incoming_kbps * old_fraction +
839 cur_incoming_kbps * (1.0 - old_fraction);
848 PeerHelper::PeerHelper() :
852 PeerHelper::PeerHelper(Peer* peer) :
857 if (!peer->IncUseCount())
864 PeerHelper::~PeerHelper()
867 m_peer->DecUseCount();
872 PeerHelper& PeerHelper::operator=(Peer* peer)
877 if (!peer->IncUseCount())
885 Peer* PeerHelper::operator->() const
890 Peer* PeerHelper::operator&() const
895 bool PeerHelper::operator!() {
899 bool PeerHelper::operator!=(void* ptr)
901 return ((void*) m_peer != ptr);
904 bool Peer::IncUseCount()
906 JMutexAutoLock lock(m_exclusive_access_mutex);
908 if (!m_pending_deletion)
917 void Peer::DecUseCount()
920 JMutexAutoLock lock(m_exclusive_access_mutex);
921 sanity_check(m_usage > 0);
924 if (!((m_pending_deletion) && (m_usage == 0)))
930 void Peer::RTTStatistics(float rtt, std::string profiler_id,
931 unsigned int num_samples) {
933 if (m_last_rtt > 0) {
934 /* set min max values */
935 if (rtt < m_rtt.min_rtt)
937 if (rtt >= m_rtt.max_rtt)
940 /* do average calculation */
941 if (m_rtt.avg_rtt < 0.0)
944 m_rtt.avg_rtt = m_rtt.avg_rtt * (num_samples/(num_samples-1)) +
945 rtt * (1/num_samples);
947 /* do jitter calculation */
949 //just use some neutral value at beginning
950 float jitter = m_rtt.jitter_min;
952 if (rtt > m_last_rtt)
953 jitter = rtt-m_last_rtt;
955 if (rtt <= m_last_rtt)
956 jitter = m_last_rtt - rtt;
958 if (jitter < m_rtt.jitter_min)
959 m_rtt.jitter_min = jitter;
960 if (jitter >= m_rtt.jitter_max)
961 m_rtt.jitter_max = jitter;
963 if (m_rtt.jitter_avg < 0.0)
964 m_rtt.jitter_avg = jitter;
966 m_rtt.jitter_avg = m_rtt.jitter_avg * (num_samples/(num_samples-1)) +
967 jitter * (1/num_samples);
969 if (profiler_id != "")
971 g_profiler->graphAdd(profiler_id + "_rtt", rtt);
972 g_profiler->graphAdd(profiler_id + "_jitter", jitter);
975 /* save values required for next loop */
979 bool Peer::isTimedOut(float timeout)
981 JMutexAutoLock lock(m_exclusive_access_mutex);
982 u32 current_time = porting::getTimeMs();
984 float dtime = CALC_DTIME(m_last_timeout_check,current_time);
985 m_last_timeout_check = current_time;
987 m_timeout_counter += dtime;
989 return m_timeout_counter > timeout;
995 JMutexAutoLock usage_lock(m_exclusive_access_mutex);
996 m_pending_deletion = true;
1001 PROFILE(std::stringstream peerIdentifier1);
1002 PROFILE(peerIdentifier1 << "runTimeouts[" << m_connection->getDesc()
1003 << ";" << id << ";RELIABLE]");
1004 PROFILE(g_profiler->remove(peerIdentifier1.str()));
1005 PROFILE(std::stringstream peerIdentifier2);
1006 PROFILE(peerIdentifier2 << "sendPackets[" << m_connection->getDesc()
1007 << ";" << id << ";RELIABLE]");
1008 PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier2.str(), SPT_AVG));
1013 UDPPeer::UDPPeer(u16 a_id, Address a_address, Connection* connection) :
1014 Peer(a_address,a_id,connection),
1015 m_pending_disconnect(false),
1016 resend_timeout(0.5),
1021 bool UDPPeer::getAddress(MTProtocols type,Address& toset)
1023 if ((type == MTP_UDP) || (type == MTP_MINETEST_RELIABLE_UDP) || (type == MTP_PRIMARY))
1032 void UDPPeer::setNonLegacyPeer()
1034 m_legacy_peer = false;
1035 for(unsigned int i=0; i< CHANNEL_COUNT; i++)
1037 channels->setWindowSize(g_settings->getU16("max_packets_per_iteration"));
1041 void UDPPeer::reportRTT(float rtt)
1046 RTTStatistics(rtt,"rudp",MAX_RELIABLE_WINDOW_SIZE*10);
1048 float timeout = getStat(AVG_RTT) * RESEND_TIMEOUT_FACTOR;
1049 if (timeout < RESEND_TIMEOUT_MIN)
1050 timeout = RESEND_TIMEOUT_MIN;
1051 if (timeout > RESEND_TIMEOUT_MAX)
1052 timeout = RESEND_TIMEOUT_MAX;
1054 JMutexAutoLock usage_lock(m_exclusive_access_mutex);
1055 resend_timeout = timeout;
1058 bool UDPPeer::Ping(float dtime,SharedBuffer<u8>& data)
1060 m_ping_timer += dtime;
1061 if (m_ping_timer >= PING_TIMEOUT)
1063 // Create and send PING packet
1064 writeU8(&data[0], TYPE_CONTROL);
1065 writeU8(&data[1], CONTROLTYPE_PING);
1072 void UDPPeer::PutReliableSendCommand(ConnectionCommand &c,
1073 unsigned int max_packet_size)
1075 if (m_pending_disconnect)
1078 if ( channels[c.channelnum].queued_commands.empty() &&
1079 /* don't queue more packets then window size */
1080 (channels[c.channelnum].queued_reliables.size()
1081 < (channels[c.channelnum].getWindowSize()/2))) {
1082 LOG(dout_con<<m_connection->getDesc()
1083 <<" processing reliable command for peer id: " << c.peer_id
1084 <<" data size: " << c.data.getSize() << std::endl);
1085 if (!processReliableSendCommand(c,max_packet_size)) {
1086 channels[c.channelnum].queued_commands.push_back(c);
1090 LOG(dout_con<<m_connection->getDesc()
1091 <<" Queueing reliable command for peer id: " << c.peer_id
1092 <<" data size: " << c.data.getSize() <<std::endl);
1093 channels[c.channelnum].queued_commands.push_back(c);
1097 bool UDPPeer::processReliableSendCommand(
1098 ConnectionCommand &c,
1099 unsigned int max_packet_size)
1101 if (m_pending_disconnect)
1104 u32 chunksize_max = max_packet_size
1106 - RELIABLE_HEADER_SIZE;
1108 sanity_check(c.data.getSize() < MAX_RELIABLE_WINDOW_SIZE*512);
1110 std::list<SharedBuffer<u8> > originals;
1111 u16 split_sequence_number = channels[c.channelnum].readNextSplitSeqNum();
1115 originals.push_back(c.data);
1118 originals = makeAutoSplitPacket(c.data, chunksize_max,split_sequence_number);
1119 channels[c.channelnum].setNextSplitSeqNum(split_sequence_number);
1122 bool have_sequence_number = true;
1123 bool have_initial_sequence_number = false;
1124 std::queue<BufferedPacket> toadd;
1125 volatile u16 initial_sequence_number = 0;
1127 for(std::list<SharedBuffer<u8> >::iterator i = originals.begin();
1128 i != originals.end(); ++i)
1130 u16 seqnum = channels[c.channelnum].getOutgoingSequenceNumber(have_sequence_number);
1132 /* oops, we don't have enough sequence numbers to send this packet */
1133 if (!have_sequence_number)
1136 if (!have_initial_sequence_number)
1138 initial_sequence_number = seqnum;
1139 have_initial_sequence_number = true;
1142 SharedBuffer<u8> reliable = makeReliablePacket(*i, seqnum);
1144 // Add base headers and make a packet
1145 BufferedPacket p = con::makePacket(address, reliable,
1146 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1152 if (have_sequence_number) {
1153 volatile u16 pcount = 0;
1154 while(toadd.size() > 0) {
1155 BufferedPacket p = toadd.front();
1157 // LOG(dout_con<<connection->getDesc()
1158 // << " queuing reliable packet for peer_id: " << c.peer_id
1159 // << " channel: " << (c.channelnum&0xFF)
1160 // << " seqnum: " << readU16(&p.data[BASE_HEADER_SIZE+1])
1162 channels[c.channelnum].queued_reliables.push(p);
1165 sanity_check(channels[c.channelnum].queued_reliables.size() < 0xFFFF);
1169 volatile u16 packets_available = toadd.size();
1170 /* we didn't get a single sequence number no need to fill queue */
1171 if (!have_initial_sequence_number)
1175 while(toadd.size() > 0) {
1179 bool successfully_put_back_sequence_number
1180 = channels[c.channelnum].putBackSequenceNumber(
1181 (initial_sequence_number+toadd.size() % (SEQNUM_MAX+1)));
1183 FATAL_ERROR_IF(!successfully_put_back_sequence_number, "error");
1185 LOG(dout_con<<m_connection->getDesc()
1186 << " Windowsize exceeded on reliable sending "
1187 << c.data.getSize() << " bytes"
1188 << std::endl << "\t\tinitial_sequence_number: "
1189 << initial_sequence_number
1190 << std::endl << "\t\tgot at most : "
1191 << packets_available << " packets"
1192 << std::endl << "\t\tpackets queued : "
1193 << channels[c.channelnum].outgoing_reliables_sent.size()
1199 void UDPPeer::RunCommandQueues(
1200 unsigned int max_packet_size,
1201 unsigned int maxcommands,
1202 unsigned int maxtransfer)
1205 for (unsigned int i = 0; i < CHANNEL_COUNT; i++) {
1206 unsigned int commands_processed = 0;
1208 if ((channels[i].queued_commands.size() > 0) &&
1209 (channels[i].queued_reliables.size() < maxtransfer) &&
1210 (commands_processed < maxcommands)) {
1212 ConnectionCommand c = channels[i].queued_commands.front();
1214 LOG(dout_con << m_connection->getDesc()
1215 << " processing queued reliable command " << std::endl);
1217 // Packet is processed, remove it from queue
1218 if (processReliableSendCommand(c,max_packet_size)) {
1219 channels[i].queued_commands.pop_front();
1221 LOG(dout_con << m_connection->getDesc()
1222 << " Failed to queue packets for peer_id: " << c.peer_id
1223 << ", delaying sending of " << c.data.getSize()
1224 << " bytes" << std::endl);
1227 catch (ItemNotFoundException &e) {
1228 // intentionally empty
1234 u16 UDPPeer::getNextSplitSequenceNumber(u8 channel)
1236 assert(channel < CHANNEL_COUNT); // Pre-condition
1237 return channels[channel].readNextIncomingSeqNum();
1240 void UDPPeer::setNextSplitSequenceNumber(u8 channel, u16 seqnum)
1242 assert(channel < CHANNEL_COUNT); // Pre-condition
1243 channels[channel].setNextSplitSeqNum(seqnum);
1246 SharedBuffer<u8> UDPPeer::addSpiltPacket(u8 channel,
1247 BufferedPacket toadd,
1250 assert(channel < CHANNEL_COUNT); // Pre-condition
1251 return channels[channel].incoming_splits.insert(toadd,reliable);
1254 /******************************************************************************/
1255 /* Connection Threads */
1256 /******************************************************************************/
1258 ConnectionSendThread::ConnectionSendThread( unsigned int max_packet_size,
1261 m_max_packet_size(max_packet_size),
1263 m_max_commands_per_iteration(1),
1264 m_max_data_packets_per_iteration(g_settings->getU16("max_packets_per_iteration")),
1265 m_max_packets_requeued(256)
1269 void * ConnectionSendThread::Thread()
1271 assert(m_connection != NULL);
1273 log_register_thread("ConnectionSend");
1275 LOG(dout_con<<m_connection->getDesc()
1276 <<"ConnectionSend thread started"<<std::endl);
1278 u32 curtime = porting::getTimeMs();
1279 u32 lasttime = curtime;
1281 PROFILE(std::stringstream ThreadIdentifier);
1282 PROFILE(ThreadIdentifier << "ConnectionSend: [" << m_connection->getDesc() << "]");
1284 porting::setThreadName("ConnectionSend");
1286 /* if stop is requested don't stop immediately but try to send all */
1288 while(!StopRequested() || packetsQueued()) {
1289 BEGIN_DEBUG_EXCEPTION_HANDLER
1290 PROFILE(ScopeProfiler sp(g_profiler, ThreadIdentifier.str(), SPT_AVG));
1292 m_iteration_packets_avaialble = m_max_data_packets_per_iteration;
1294 /* wait for trigger or timeout */
1295 m_send_sleep_semaphore.Wait(50);
1297 /* remove all triggers */
1298 while(m_send_sleep_semaphore.Wait(0)) {}
1301 curtime = porting::getTimeMs();
1302 float dtime = CALC_DTIME(lasttime,curtime);
1304 /* first do all the reliable stuff */
1307 /* translate commands to packets */
1308 ConnectionCommand c = m_connection->m_command_queue.pop_frontNoEx(0);
1309 while(c.type != CONNCMD_NONE)
1312 processReliableCommand(c);
1314 processNonReliableCommand(c);
1316 c = m_connection->m_command_queue.pop_frontNoEx(0);
1319 /* send non reliable packets */
1322 END_DEBUG_EXCEPTION_HANDLER(errorstream);
1325 PROFILE(g_profiler->remove(ThreadIdentifier.str()));
1329 void ConnectionSendThread::Trigger()
1331 m_send_sleep_semaphore.Post();
1334 bool ConnectionSendThread::packetsQueued()
1336 std::list<u16> peerIds = m_connection->getPeerIDs();
1338 if (!m_outgoing_queue.empty() && !peerIds.empty())
1341 for(std::list<u16>::iterator j = peerIds.begin();
1342 j != peerIds.end(); ++j)
1344 PeerHelper peer = m_connection->getPeerNoEx(*j);
1349 if (dynamic_cast<UDPPeer*>(&peer) == 0)
1352 for(u16 i=0; i < CHANNEL_COUNT; i++) {
1353 Channel *channel = &(dynamic_cast<UDPPeer*>(&peer))->channels[i];
1355 if (channel->queued_commands.size() > 0) {
1365 void ConnectionSendThread::runTimeouts(float dtime)
1367 std::list<u16> timeouted_peers;
1368 std::list<u16> peerIds = m_connection->getPeerIDs();
1370 for(std::list<u16>::iterator j = peerIds.begin();
1371 j != peerIds.end(); ++j)
1373 PeerHelper peer = m_connection->getPeerNoEx(*j);
1378 if (dynamic_cast<UDPPeer*>(&peer) == 0)
1381 PROFILE(std::stringstream peerIdentifier);
1382 PROFILE(peerIdentifier << "runTimeouts[" << m_connection->getDesc()
1383 << ";" << *j << ";RELIABLE]");
1384 PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier.str(), SPT_AVG));
1386 SharedBuffer<u8> data(2); // data for sending ping, required here because of goto
1391 if (peer->isTimedOut(m_timeout))
1393 infostream<<m_connection->getDesc()
1394 <<"RunTimeouts(): Peer "<<peer->id
1396 <<" (source=peer->timeout_counter)"
1398 // Add peer to the list
1399 timeouted_peers.push_back(peer->id);
1400 // Don't bother going through the buffers of this one
1404 float resend_timeout = dynamic_cast<UDPPeer*>(&peer)->getResendTimeout();
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 LOG(derr_con<<m_connection->getDesc()
1445 <<"RE-SENDING timed-out RELIABLE to "
1446 << k->address.serializeString()
1447 << "(t/o="<<resend_timeout<<"): "
1448 <<"from_peer_id="<<peer_id
1449 <<", channel="<<((int)channelnum&0xff)
1450 <<", seqnum="<<seqnum
1455 // do not handle rtt here as we can't decide if this packet was
1456 // lost or really takes more time to transmit
1458 channel->UpdateTimers(dtime,dynamic_cast<UDPPeer*>(&peer)->getLegacyPeer());
1461 /* send ping if necessary */
1462 if (dynamic_cast<UDPPeer*>(&peer)->Ping(dtime,data)) {
1463 LOG(dout_con<<m_connection->getDesc()
1464 <<"Sending ping for peer_id: "
1465 << dynamic_cast<UDPPeer*>(&peer)->id <<std::endl);
1466 /* this may fail if there ain't a sequence number left */
1467 if (!rawSendAsPacket(dynamic_cast<UDPPeer*>(&peer)->id, 0, data, true))
1469 //retrigger with reduced ping interval
1470 dynamic_cast<UDPPeer*>(&peer)->Ping(4.0,data);
1474 dynamic_cast<UDPPeer*>(&peer)->RunCommandQueues(m_max_packet_size,
1475 m_max_commands_per_iteration,
1476 m_max_packets_requeued);
1479 // Remove timed out peers
1480 for(std::list<u16>::iterator i = timeouted_peers.begin();
1481 i != timeouted_peers.end(); ++i)
1483 LOG(derr_con<<m_connection->getDesc()
1484 <<"RunTimeouts(): Removing peer "<<(*i)<<std::endl);
1485 m_connection->deletePeer(*i, true);
1489 void ConnectionSendThread::rawSend(const BufferedPacket &packet)
1492 m_connection->m_udpSocket.Send(packet.address, *packet.data,
1493 packet.data.getSize());
1494 LOG(dout_con <<m_connection->getDesc()
1495 << " rawSend: " << packet.data.getSize()
1496 << " bytes sent" << std::endl);
1497 } catch(SendFailedException &e) {
1498 LOG(derr_con<<m_connection->getDesc()
1499 <<"Connection::rawSend(): SendFailedException: "
1500 <<packet.address.serializeString()<<std::endl);
1504 void ConnectionSendThread::sendAsPacketReliable(BufferedPacket& p, Channel* channel)
1507 p.absolute_send_time = porting::getTimeMs();
1508 // Buffer the packet
1509 channel->outgoing_reliables_sent.insert(p,
1510 (channel->readOutgoingSequenceNumber() - MAX_RELIABLE_WINDOW_SIZE)
1511 % (MAX_RELIABLE_WINDOW_SIZE+1));
1513 catch(AlreadyExistsException &e)
1515 LOG(derr_con<<m_connection->getDesc()
1516 <<"WARNING: Going to send a reliable packet"
1517 <<" in outgoing buffer" <<std::endl);
1524 bool ConnectionSendThread::rawSendAsPacket(u16 peer_id, u8 channelnum,
1525 SharedBuffer<u8> data, bool reliable)
1527 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
1529 LOG(dout_con<<m_connection->getDesc()
1530 <<" INFO: dropped packet for non existent peer_id: "
1531 << peer_id << std::endl);
1532 FATAL_ERROR_IF(!reliable, "Trying to send raw packet reliable but no peer found!");
1535 Channel *channel = &(dynamic_cast<UDPPeer*>(&peer)->channels[channelnum]);
1539 bool have_sequence_number_for_raw_packet = true;
1541 channel->getOutgoingSequenceNumber(have_sequence_number_for_raw_packet);
1543 if (!have_sequence_number_for_raw_packet)
1546 SharedBuffer<u8> reliable = makeReliablePacket(data, seqnum);
1547 Address peer_address;
1548 peer->getAddress(MTP_MINETEST_RELIABLE_UDP, peer_address);
1550 // Add base headers and make a packet
1551 BufferedPacket p = con::makePacket(peer_address, reliable,
1552 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1555 // first check if our send window is already maxed out
1556 if (channel->outgoing_reliables_sent.size()
1557 < channel->getWindowSize()) {
1558 LOG(dout_con<<m_connection->getDesc()
1559 <<" INFO: sending a reliable packet to peer_id " << peer_id
1560 <<" channel: " << channelnum
1561 <<" seqnum: " << seqnum << std::endl);
1562 sendAsPacketReliable(p,channel);
1566 LOG(dout_con<<m_connection->getDesc()
1567 <<" INFO: queueing reliable packet for peer_id: " << peer_id
1568 <<" channel: " << channelnum
1569 <<" seqnum: " << seqnum << std::endl);
1570 channel->queued_reliables.push(p);
1576 Address peer_address;
1578 if (peer->getAddress(MTP_UDP, peer_address))
1580 // Add base headers and make a packet
1581 BufferedPacket p = con::makePacket(peer_address, data,
1582 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1590 LOG(dout_con<<m_connection->getDesc()
1591 <<" INFO: dropped unreliable packet for peer_id: " << peer_id
1592 <<" because of (yet) missing udp address" << std::endl);
1601 void ConnectionSendThread::processReliableCommand(ConnectionCommand &c)
1603 assert(c.reliable); // Pre-condition
1607 LOG(dout_con<<m_connection->getDesc()
1608 <<"UDP processing reliable CONNCMD_NONE"<<std::endl);
1612 LOG(dout_con<<m_connection->getDesc()
1613 <<"UDP processing reliable CONNCMD_SEND"<<std::endl);
1617 case CONNCMD_SEND_TO_ALL:
1618 LOG(dout_con<<m_connection->getDesc()
1619 <<"UDP processing CONNCMD_SEND_TO_ALL"<<std::endl);
1620 sendToAllReliable(c);
1623 case CONCMD_CREATE_PEER:
1624 LOG(dout_con<<m_connection->getDesc()
1625 <<"UDP processing reliable CONCMD_CREATE_PEER"<<std::endl);
1626 if (!rawSendAsPacket(c.peer_id,c.channelnum,c.data,c.reliable))
1628 /* put to queue if we couldn't send it immediately */
1633 case CONCMD_DISABLE_LEGACY:
1634 LOG(dout_con<<m_connection->getDesc()
1635 <<"UDP processing reliable CONCMD_DISABLE_LEGACY"<<std::endl);
1636 if (!rawSendAsPacket(c.peer_id,c.channelnum,c.data,c.reliable))
1638 /* put to queue if we couldn't send it immediately */
1644 case CONNCMD_CONNECT:
1645 case CONNCMD_DISCONNECT:
1647 FATAL_ERROR("Got command that shouldn't be reliable as reliable command");
1649 LOG(dout_con<<m_connection->getDesc()
1650 <<" Invalid reliable command type: " << c.type <<std::endl);
1655 void ConnectionSendThread::processNonReliableCommand(ConnectionCommand &c)
1657 assert(!c.reliable); // Pre-condition
1661 LOG(dout_con<<m_connection->getDesc()
1662 <<" UDP processing CONNCMD_NONE"<<std::endl);
1665 LOG(dout_con<<m_connection->getDesc()
1666 <<" UDP processing CONNCMD_SERVE port="
1667 <<c.address.serializeString()<<std::endl);
1670 case CONNCMD_CONNECT:
1671 LOG(dout_con<<m_connection->getDesc()
1672 <<" UDP processing CONNCMD_CONNECT"<<std::endl);
1675 case CONNCMD_DISCONNECT:
1676 LOG(dout_con<<m_connection->getDesc()
1677 <<" UDP processing CONNCMD_DISCONNECT"<<std::endl);
1680 case CONNCMD_DISCONNECT_PEER:
1681 LOG(dout_con<<m_connection->getDesc()
1682 <<" UDP processing CONNCMD_DISCONNECT_PEER"<<std::endl);
1683 disconnect_peer(c.peer_id);
1686 LOG(dout_con<<m_connection->getDesc()
1687 <<" UDP processing CONNCMD_SEND"<<std::endl);
1688 send(c.peer_id, c.channelnum, c.data);
1690 case CONNCMD_SEND_TO_ALL:
1691 LOG(dout_con<<m_connection->getDesc()
1692 <<" UDP processing CONNCMD_SEND_TO_ALL"<<std::endl);
1693 sendToAll(c.channelnum, c.data);
1696 LOG(dout_con<<m_connection->getDesc()
1697 <<" UDP processing CONCMD_ACK"<<std::endl);
1698 sendAsPacket(c.peer_id,c.channelnum,c.data,true);
1700 case CONCMD_CREATE_PEER:
1701 FATAL_ERROR("Got command that should be reliable as unreliable command");
1703 LOG(dout_con<<m_connection->getDesc()
1704 <<" Invalid command type: " << c.type <<std::endl);
1708 void ConnectionSendThread::serve(Address bind_address)
1710 LOG(dout_con<<m_connection->getDesc()
1711 <<"UDP serving at port " << bind_address.serializeString() <<std::endl);
1713 m_connection->m_udpSocket.Bind(bind_address);
1714 m_connection->SetPeerID(PEER_ID_SERVER);
1716 catch(SocketException &e) {
1720 m_connection->putEvent(ce);
1724 void ConnectionSendThread::connect(Address address)
1726 LOG(dout_con<<m_connection->getDesc()<<" connecting to "<<address.serializeString()
1727 <<":"<<address.getPort()<<std::endl);
1729 UDPPeer *peer = m_connection->createServerPeer(address);
1733 e.peerAdded(peer->id, peer->address);
1734 m_connection->putEvent(e);
1738 if (address.isIPv6())
1739 bind_addr.setAddress((IPv6AddressBytes*) NULL);
1741 bind_addr.setAddress(0,0,0,0);
1743 m_connection->m_udpSocket.Bind(bind_addr);
1745 // Send a dummy packet to server with peer_id = PEER_ID_INEXISTENT
1746 m_connection->SetPeerID(PEER_ID_INEXISTENT);
1747 NetworkPacket pkt(0,0);
1748 m_connection->Send(PEER_ID_SERVER, 0, &pkt, true);
1751 void ConnectionSendThread::disconnect()
1753 LOG(dout_con<<m_connection->getDesc()<<" disconnecting"<<std::endl);
1755 // Create and send DISCO packet
1756 SharedBuffer<u8> data(2);
1757 writeU8(&data[0], TYPE_CONTROL);
1758 writeU8(&data[1], CONTROLTYPE_DISCO);
1762 std::list<u16> peerids = m_connection->getPeerIDs();
1764 for (std::list<u16>::iterator i = peerids.begin();
1768 sendAsPacket(*i, 0,data,false);
1772 void ConnectionSendThread::disconnect_peer(u16 peer_id)
1774 LOG(dout_con<<m_connection->getDesc()<<" disconnecting peer"<<std::endl);
1776 // Create and send DISCO packet
1777 SharedBuffer<u8> data(2);
1778 writeU8(&data[0], TYPE_CONTROL);
1779 writeU8(&data[1], CONTROLTYPE_DISCO);
1780 sendAsPacket(peer_id, 0,data,false);
1782 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
1787 if (dynamic_cast<UDPPeer*>(&peer) == 0)
1792 dynamic_cast<UDPPeer*>(&peer)->m_pending_disconnect = true;
1795 void ConnectionSendThread::send(u16 peer_id, u8 channelnum,
1796 SharedBuffer<u8> data)
1798 assert(channelnum < CHANNEL_COUNT); // Pre-condition
1800 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
1803 LOG(dout_con<<m_connection->getDesc()<<" peer: peer_id="<<peer_id
1804 << ">>>NOT<<< found on sending packet"
1805 << ", channel " << (channelnum % 0xFF)
1806 << ", size: " << data.getSize() <<std::endl);
1810 LOG(dout_con<<m_connection->getDesc()<<" sending to peer_id="<<peer_id
1811 << ", channel " << (channelnum % 0xFF)
1812 << ", size: " << data.getSize() <<std::endl);
1814 u16 split_sequence_number = peer->getNextSplitSequenceNumber(channelnum);
1816 u32 chunksize_max = m_max_packet_size - BASE_HEADER_SIZE;
1817 std::list<SharedBuffer<u8> > originals;
1819 originals = makeAutoSplitPacket(data, chunksize_max,split_sequence_number);
1821 peer->setNextSplitSequenceNumber(channelnum,split_sequence_number);
1823 for(std::list<SharedBuffer<u8> >::iterator i = originals.begin();
1824 i != originals.end(); ++i)
1826 SharedBuffer<u8> original = *i;
1827 sendAsPacket(peer_id, channelnum, original);
1831 void ConnectionSendThread::sendReliable(ConnectionCommand &c)
1833 PeerHelper peer = m_connection->getPeerNoEx(c.peer_id);
1837 peer->PutReliableSendCommand(c,m_max_packet_size);
1840 void ConnectionSendThread::sendToAll(u8 channelnum, SharedBuffer<u8> data)
1842 std::list<u16> peerids = m_connection->getPeerIDs();
1844 for (std::list<u16>::iterator i = peerids.begin();
1848 send(*i, channelnum, data);
1852 void ConnectionSendThread::sendToAllReliable(ConnectionCommand &c)
1854 std::list<u16> peerids = m_connection->getPeerIDs();
1856 for (std::list<u16>::iterator i = peerids.begin();
1860 PeerHelper peer = m_connection->getPeerNoEx(*i);
1865 peer->PutReliableSendCommand(c,m_max_packet_size);
1869 void ConnectionSendThread::sendPackets(float dtime)
1871 std::list<u16> peerIds = m_connection->getPeerIDs();
1872 std::list<u16> pendingDisconnect;
1873 std::map<u16,bool> pending_unreliable;
1875 for(std::list<u16>::iterator
1876 j = peerIds.begin();
1877 j != peerIds.end(); ++j)
1879 PeerHelper peer = m_connection->getPeerNoEx(*j);
1880 //peer may have been removed
1882 LOG(dout_con<<m_connection->getDesc()<< " Peer not found: peer_id=" << *j << std::endl);
1885 peer->m_increment_packets_remaining = m_iteration_packets_avaialble/m_connection->m_peers.size();
1887 if (dynamic_cast<UDPPeer*>(&peer) == 0)
1892 if (dynamic_cast<UDPPeer*>(&peer)->m_pending_disconnect)
1894 pendingDisconnect.push_back(*j);
1897 PROFILE(std::stringstream peerIdentifier);
1898 PROFILE(peerIdentifier << "sendPackets[" << m_connection->getDesc() << ";" << *j << ";RELIABLE]");
1899 PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier.str(), SPT_AVG));
1901 LOG(dout_con<<m_connection->getDesc()
1902 << " Handle per peer queues: peer_id=" << *j
1903 << " packet quota: " << peer->m_increment_packets_remaining << std::endl);
1904 // first send queued reliable packets for all peers (if possible)
1905 for (unsigned int i=0; i < CHANNEL_COUNT; i++)
1907 u16 next_to_ack = 0;
1908 dynamic_cast<UDPPeer*>(&peer)->channels[i].outgoing_reliables_sent.getFirstSeqnum(next_to_ack);
1909 u16 next_to_receive = 0;
1910 dynamic_cast<UDPPeer*>(&peer)->channels[i].incoming_reliables.getFirstSeqnum(next_to_receive);
1912 LOG(dout_con<<m_connection->getDesc()<< "\t channel: "
1913 << i << ", peer quota:"
1914 << peer->m_increment_packets_remaining
1916 << "\t\t\treliables on wire: "
1917 << dynamic_cast<UDPPeer*>(&peer)->channels[i].outgoing_reliables_sent.size()
1918 << ", waiting for ack for " << next_to_ack
1920 << "\t\t\tincoming_reliables: "
1921 << dynamic_cast<UDPPeer*>(&peer)->channels[i].incoming_reliables.size()
1922 << ", next reliable packet: "
1923 << dynamic_cast<UDPPeer*>(&peer)->channels[i].readNextIncomingSeqNum()
1924 << ", next queued: " << next_to_receive
1926 << "\t\t\treliables queued : "
1927 << dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.size()
1929 << "\t\t\tqueued commands : "
1930 << dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_commands.size()
1933 while ((dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.size() > 0) &&
1934 (dynamic_cast<UDPPeer*>(&peer)->channels[i].outgoing_reliables_sent.size()
1935 < dynamic_cast<UDPPeer*>(&peer)->channels[i].getWindowSize())&&
1936 (peer->m_increment_packets_remaining > 0))
1938 BufferedPacket p = dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.front();
1939 dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.pop();
1940 Channel* channel = &(dynamic_cast<UDPPeer*>(&peer)->channels[i]);
1941 LOG(dout_con<<m_connection->getDesc()
1942 <<" INFO: sending a queued reliable packet "
1944 <<", seqnum: " << readU16(&p.data[BASE_HEADER_SIZE+1])
1946 sendAsPacketReliable(p,channel);
1947 peer->m_increment_packets_remaining--;
1952 if (m_outgoing_queue.size())
1954 LOG(dout_con<<m_connection->getDesc()
1955 << " Handle non reliable queue ("
1956 << m_outgoing_queue.size() << " pkts)" << std::endl);
1959 unsigned int initial_queuesize = m_outgoing_queue.size();
1960 /* send non reliable packets*/
1961 for(unsigned int i=0;i < initial_queuesize;i++) {
1962 OutgoingPacket packet = m_outgoing_queue.front();
1963 m_outgoing_queue.pop();
1965 if (packet.reliable)
1968 PeerHelper peer = m_connection->getPeerNoEx(packet.peer_id);
1970 LOG(dout_con<<m_connection->getDesc()
1971 <<" Outgoing queue: peer_id="<<packet.peer_id
1972 << ">>>NOT<<< found on sending packet"
1973 << ", channel " << (packet.channelnum % 0xFF)
1974 << ", size: " << packet.data.getSize() <<std::endl);
1977 /* send acks immediately */
1978 else if (packet.ack)
1980 rawSendAsPacket(packet.peer_id, packet.channelnum,
1981 packet.data, packet.reliable);
1982 peer->m_increment_packets_remaining =
1983 MYMIN(0,peer->m_increment_packets_remaining--);
1986 ( peer->m_increment_packets_remaining > 0) ||
1987 (StopRequested())) {
1988 rawSendAsPacket(packet.peer_id, packet.channelnum,
1989 packet.data, packet.reliable);
1990 peer->m_increment_packets_remaining--;
1993 m_outgoing_queue.push(packet);
1994 pending_unreliable[packet.peer_id] = true;
1998 for(std::list<u16>::iterator
1999 k = pendingDisconnect.begin();
2000 k != pendingDisconnect.end(); ++k)
2002 if (!pending_unreliable[*k])
2004 m_connection->deletePeer(*k,false);
2009 void ConnectionSendThread::sendAsPacket(u16 peer_id, u8 channelnum,
2010 SharedBuffer<u8> data, bool ack)
2012 OutgoingPacket packet(peer_id, channelnum, data, false, ack);
2013 m_outgoing_queue.push(packet);
2016 ConnectionReceiveThread::ConnectionReceiveThread(unsigned int max_packet_size) :
2021 void * ConnectionReceiveThread::Thread()
2023 assert(m_connection != NULL);
2025 log_register_thread("ConnectionReceive");
2027 LOG(dout_con<<m_connection->getDesc()
2028 <<"ConnectionReceive thread started"<<std::endl);
2030 PROFILE(std::stringstream ThreadIdentifier);
2031 PROFILE(ThreadIdentifier << "ConnectionReceive: [" << m_connection->getDesc() << "]");
2033 porting::setThreadName("ConnectionReceive");
2035 #ifdef DEBUG_CONNECTION_KBPS
2036 u32 curtime = porting::getTimeMs();
2037 u32 lasttime = curtime;
2038 float debug_print_timer = 0.0;
2041 while(!StopRequested()) {
2042 BEGIN_DEBUG_EXCEPTION_HANDLER
2043 PROFILE(ScopeProfiler sp(g_profiler, ThreadIdentifier.str(), SPT_AVG));
2045 #ifdef DEBUG_CONNECTION_KBPS
2047 curtime = porting::getTimeMs();
2048 float dtime = CALC_DTIME(lasttime,curtime);
2051 /* receive packets */
2054 #ifdef DEBUG_CONNECTION_KBPS
2055 debug_print_timer += dtime;
2056 if (debug_print_timer > 20.0) {
2057 debug_print_timer -= 20.0;
2059 std::list<u16> peerids = m_connection->getPeerIDs();
2061 for (std::list<u16>::iterator i = peerids.begin();
2065 PeerHelper peer = m_connection->getPeerNoEx(*i);
2069 float peer_current = 0.0;
2070 float peer_loss = 0.0;
2071 float avg_rate = 0.0;
2072 float avg_loss = 0.0;
2074 for(u16 j=0; j<CHANNEL_COUNT; j++)
2076 peer_current +=peer->channels[j].getCurrentDownloadRateKB();
2077 peer_loss += peer->channels[j].getCurrentLossRateKB();
2078 avg_rate += peer->channels[j].getAvgDownloadRateKB();
2079 avg_loss += peer->channels[j].getAvgLossRateKB();
2082 std::stringstream output;
2083 output << std::fixed << std::setprecision(1);
2084 output << "OUT to Peer " << *i << " RATES (good / loss) " << std::endl;
2085 output << "\tcurrent (sum): " << peer_current << "kb/s "<< peer_loss << "kb/s" << std::endl;
2086 output << "\taverage (sum): " << avg_rate << "kb/s "<< avg_loss << "kb/s" << std::endl;
2087 output << std::setfill(' ');
2088 for(u16 j=0; j<CHANNEL_COUNT; j++)
2090 output << "\tcha " << j << ":"
2091 << " CUR: " << std::setw(6) << peer->channels[j].getCurrentDownloadRateKB() <<"kb/s"
2092 << " AVG: " << std::setw(6) << peer->channels[j].getAvgDownloadRateKB() <<"kb/s"
2093 << " MAX: " << std::setw(6) << peer->channels[j].getMaxDownloadRateKB() <<"kb/s"
2095 << " CUR: " << std::setw(6) << peer->channels[j].getCurrentLossRateKB() <<"kb/s"
2096 << " AVG: " << std::setw(6) << peer->channels[j].getAvgLossRateKB() <<"kb/s"
2097 << " MAX: " << std::setw(6) << peer->channels[j].getMaxLossRateKB() <<"kb/s"
2098 << " / WS: " << peer->channels[j].getWindowSize()
2102 fprintf(stderr,"%s\n",output.str().c_str());
2106 END_DEBUG_EXCEPTION_HANDLER(errorstream);
2108 PROFILE(g_profiler->remove(ThreadIdentifier.str()));
2112 // Receive packets from the network and buffers and create ConnectionEvents
2113 void ConnectionReceiveThread::receive()
2115 // use IPv6 minimum allowed MTU as receive buffer size as this is
2116 // theoretical reliable upper boundary of a udp packet for all IPv6 enabled
2118 unsigned int packet_maxsize = 1500;
2119 SharedBuffer<u8> packetdata(packet_maxsize);
2121 bool packet_queued = true;
2123 unsigned int loop_count = 0;
2125 /* first of all read packets from socket */
2126 /* check for incoming data available */
2127 while( (loop_count < 10) &&
2128 (m_connection->m_udpSocket.WaitData(50))) {
2131 if (packet_queued) {
2132 bool data_left = true;
2134 SharedBuffer<u8> resultdata;
2137 data_left = getFromBuffers(peer_id, resultdata);
2140 e.dataReceived(peer_id, resultdata);
2141 m_connection->putEvent(e);
2144 catch(ProcessedSilentlyException &e) {
2145 /* try reading again */
2148 packet_queued = false;
2152 s32 received_size = m_connection->m_udpSocket.Receive(sender, *packetdata, packet_maxsize);
2154 if ((received_size < BASE_HEADER_SIZE) ||
2155 (readU32(&packetdata[0]) != m_connection->GetProtocolID()))
2157 LOG(derr_con<<m_connection->getDesc()
2158 <<"Receive(): Invalid incoming packet, "
2159 <<"size: " << received_size
2161 << ((received_size >= 4) ? readU32(&packetdata[0]) : -1)
2166 u16 peer_id = readPeerId(*packetdata);
2167 u8 channelnum = readChannel(*packetdata);
2169 if (channelnum > CHANNEL_COUNT-1) {
2170 LOG(derr_con<<m_connection->getDesc()
2171 <<"Receive(): Invalid channel "<<channelnum<<std::endl);
2172 throw InvalidIncomingDataException("Channel doesn't exist");
2175 /* preserve original peer_id for later usage */
2176 u16 packet_peer_id = peer_id;
2178 /* Try to identify peer by sender address (may happen on join) */
2179 if (peer_id == PEER_ID_INEXISTENT) {
2180 peer_id = m_connection->lookupPeer(sender);
2183 /* The peer was not found in our lists. Add it. */
2184 if (peer_id == PEER_ID_INEXISTENT) {
2185 peer_id = m_connection->createPeer(sender, MTP_MINETEST_RELIABLE_UDP, 0);
2188 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
2191 LOG(dout_con<<m_connection->getDesc()
2192 <<" got packet from unknown peer_id: "
2193 <<peer_id<<" Ignoring."<<std::endl);
2197 // Validate peer address
2199 Address peer_address;
2201 if (peer->getAddress(MTP_UDP, peer_address)) {
2202 if (peer_address != sender) {
2203 LOG(derr_con<<m_connection->getDesc()
2204 <<m_connection->getDesc()
2205 <<" Peer "<<peer_id<<" sending from different address."
2206 " Ignoring."<<std::endl);
2212 bool invalid_address = true;
2213 if (invalid_address) {
2214 LOG(derr_con<<m_connection->getDesc()
2215 <<m_connection->getDesc()
2216 <<" Peer "<<peer_id<<" unknown."
2217 " Ignoring."<<std::endl);
2223 /* mark peer as seen with id */
2224 if (!(packet_peer_id == PEER_ID_INEXISTENT))
2225 peer->setSentWithID();
2227 peer->ResetTimeout();
2229 Channel *channel = 0;
2231 if (dynamic_cast<UDPPeer*>(&peer) != 0)
2233 channel = &(dynamic_cast<UDPPeer*>(&peer)->channels[channelnum]);
2237 channel->UpdateBytesReceived(received_size);
2240 // Throw the received packet to channel->processPacket()
2242 // Make a new SharedBuffer from the data without the base headers
2243 SharedBuffer<u8> strippeddata(received_size - BASE_HEADER_SIZE);
2244 memcpy(*strippeddata, &packetdata[BASE_HEADER_SIZE],
2245 strippeddata.getSize());
2248 // Process it (the result is some data with no headers made by us)
2249 SharedBuffer<u8> resultdata = processPacket
2250 (channel, strippeddata, peer_id, channelnum, false);
2252 LOG(dout_con<<m_connection->getDesc()
2253 <<" ProcessPacket from peer_id: " << peer_id
2254 << ",channel: " << (channelnum & 0xFF) << ", returned "
2255 << resultdata.getSize() << " bytes" <<std::endl);
2258 e.dataReceived(peer_id, resultdata);
2259 m_connection->putEvent(e);
2261 catch(ProcessedSilentlyException &e) {
2263 catch(ProcessedQueued &e) {
2264 packet_queued = true;
2267 catch(InvalidIncomingDataException &e) {
2269 catch(ProcessedSilentlyException &e) {
2274 bool ConnectionReceiveThread::getFromBuffers(u16 &peer_id, SharedBuffer<u8> &dst)
2276 std::list<u16> peerids = m_connection->getPeerIDs();
2278 for(std::list<u16>::iterator j = peerids.begin();
2279 j != peerids.end(); ++j)
2281 PeerHelper peer = m_connection->getPeerNoEx(*j);
2285 if (dynamic_cast<UDPPeer*>(&peer) == 0)
2288 for(u16 i=0; i<CHANNEL_COUNT; i++)
2290 Channel *channel = &(dynamic_cast<UDPPeer*>(&peer))->channels[i];
2292 if (checkIncomingBuffers(channel, peer_id, dst)) {
2300 bool ConnectionReceiveThread::checkIncomingBuffers(Channel *channel,
2301 u16 &peer_id, SharedBuffer<u8> &dst)
2303 u16 firstseqnum = 0;
2304 if (channel->incoming_reliables.getFirstSeqnum(firstseqnum))
2306 if (firstseqnum == channel->readNextIncomingSeqNum())
2308 BufferedPacket p = channel->incoming_reliables.popFirst();
2309 peer_id = readPeerId(*p.data);
2310 u8 channelnum = readChannel(*p.data);
2311 u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]);
2313 LOG(dout_con<<m_connection->getDesc()
2314 <<"UNBUFFERING TYPE_RELIABLE"
2315 <<" seqnum="<<seqnum
2316 <<" peer_id="<<peer_id
2317 <<" channel="<<((int)channelnum&0xff)
2320 channel->incNextIncomingSeqNum();
2322 u32 headers_size = BASE_HEADER_SIZE + RELIABLE_HEADER_SIZE;
2323 // Get out the inside packet and re-process it
2324 SharedBuffer<u8> payload(p.data.getSize() - headers_size);
2325 memcpy(*payload, &p.data[headers_size], payload.getSize());
2327 dst = processPacket(channel, payload, peer_id, channelnum, true);
2334 SharedBuffer<u8> ConnectionReceiveThread::processPacket(Channel *channel,
2335 SharedBuffer<u8> packetdata, u16 peer_id, u8 channelnum, bool reliable)
2337 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
2340 errorstream << "Peer not found (possible timeout)" << std::endl;
2341 throw ProcessedSilentlyException("Peer not found (possible timeout)");
2344 if (packetdata.getSize() < 1)
2345 throw InvalidIncomingDataException("packetdata.getSize() < 1");
2347 u8 type = readU8(&(packetdata[0]));
2349 if (MAX_UDP_PEERS <= 65535 && peer_id >= MAX_UDP_PEERS) {
2350 std::string errmsg = "Invalid peer_id=" + itos(peer_id);
2351 errorstream << errmsg << std::endl;
2352 throw InvalidIncomingDataException(errmsg.c_str());
2355 if (type == TYPE_CONTROL)
2357 if (packetdata.getSize() < 2)
2358 throw InvalidIncomingDataException("packetdata.getSize() < 2");
2360 u8 controltype = readU8(&(packetdata[1]));
2362 if (controltype == CONTROLTYPE_ACK)
2364 assert(channel != NULL);
2366 if (packetdata.getSize() < 4) {
2367 throw InvalidIncomingDataException(
2368 "packetdata.getSize() < 4 (ACK header size)");
2371 u16 seqnum = readU16(&packetdata[2]);
2372 LOG(dout_con<<m_connection->getDesc()
2373 <<" [ CONTROLTYPE_ACK: channelnum="
2374 <<((int)channelnum&0xff)<<", peer_id="<<peer_id
2375 <<", seqnum="<<seqnum<< " ]"<<std::endl);
2379 channel->outgoing_reliables_sent.popSeqnum(seqnum);
2381 // only calculate rtt from straight sent packets
2382 if (p.resend_count == 0) {
2383 // Get round trip time
2384 unsigned int current_time = porting::getTimeMs();
2386 // a overflow is quite unlikely but as it'd result in major
2387 // rtt miscalculation we handle it here
2388 if (current_time > p.absolute_send_time)
2390 float rtt = (current_time - p.absolute_send_time) / 1000.0;
2392 // Let peer calculate stuff according to it
2393 // (avg_rtt and resend_timeout)
2394 dynamic_cast<UDPPeer*>(&peer)->reportRTT(rtt);
2396 else if (p.totaltime > 0)
2398 float rtt = p.totaltime;
2400 // Let peer calculate stuff according to it
2401 // (avg_rtt and resend_timeout)
2402 dynamic_cast<UDPPeer*>(&peer)->reportRTT(rtt);
2405 //put bytes for max bandwidth calculation
2406 channel->UpdateBytesSent(p.data.getSize(),1);
2407 if (channel->outgoing_reliables_sent.size() == 0)
2409 m_connection->TriggerSend();
2412 catch(NotFoundException &e) {
2413 LOG(derr_con<<m_connection->getDesc()
2414 <<"WARNING: ACKed packet not "
2417 channel->UpdatePacketTooLateCounter();
2419 throw ProcessedSilentlyException("Got an ACK");
2421 else if (controltype == CONTROLTYPE_SET_PEER_ID) {
2422 // Got a packet to set our peer id
2423 if (packetdata.getSize() < 4)
2424 throw InvalidIncomingDataException
2425 ("packetdata.getSize() < 4 (SET_PEER_ID header size)");
2426 u16 peer_id_new = readU16(&packetdata[2]);
2427 LOG(dout_con<<m_connection->getDesc()
2428 <<"Got new peer id: "<<peer_id_new<<"... "<<std::endl);
2430 if (m_connection->GetPeerID() != PEER_ID_INEXISTENT)
2432 LOG(derr_con<<m_connection->getDesc()
2433 <<"WARNING: Not changing"
2434 " existing peer id."<<std::endl);
2438 LOG(dout_con<<m_connection->getDesc()<<"changing own peer id"<<std::endl);
2439 m_connection->SetPeerID(peer_id_new);
2442 ConnectionCommand cmd;
2444 SharedBuffer<u8> reply(2);
2445 writeU8(&reply[0], TYPE_CONTROL);
2446 writeU8(&reply[1], CONTROLTYPE_ENABLE_BIG_SEND_WINDOW);
2447 cmd.disableLegacy(PEER_ID_SERVER,reply);
2448 m_connection->putCommand(cmd);
2450 throw ProcessedSilentlyException("Got a SET_PEER_ID");
2452 else if (controltype == CONTROLTYPE_PING)
2454 // Just ignore it, the incoming data already reset
2455 // the timeout counter
2456 LOG(dout_con<<m_connection->getDesc()<<"PING"<<std::endl);
2457 throw ProcessedSilentlyException("Got a PING");
2459 else if (controltype == CONTROLTYPE_DISCO)
2461 // Just ignore it, the incoming data already reset
2462 // the timeout counter
2463 LOG(dout_con<<m_connection->getDesc()
2464 <<"DISCO: Removing peer "<<(peer_id)<<std::endl);
2466 if (m_connection->deletePeer(peer_id, false) == false)
2468 derr_con<<m_connection->getDesc()
2469 <<"DISCO: Peer not found"<<std::endl;
2472 throw ProcessedSilentlyException("Got a DISCO");
2474 else if (controltype == CONTROLTYPE_ENABLE_BIG_SEND_WINDOW)
2476 dynamic_cast<UDPPeer*>(&peer)->setNonLegacyPeer();
2477 throw ProcessedSilentlyException("Got non legacy control");
2480 LOG(derr_con<<m_connection->getDesc()
2481 <<"INVALID TYPE_CONTROL: invalid controltype="
2482 <<((int)controltype&0xff)<<std::endl);
2483 throw InvalidIncomingDataException("Invalid control type");
2486 else if (type == TYPE_ORIGINAL)
2488 if (packetdata.getSize() <= ORIGINAL_HEADER_SIZE)
2489 throw InvalidIncomingDataException
2490 ("packetdata.getSize() <= ORIGINAL_HEADER_SIZE");
2491 LOG(dout_con<<m_connection->getDesc()
2492 <<"RETURNING TYPE_ORIGINAL to user"
2494 // Get the inside packet out and return it
2495 SharedBuffer<u8> payload(packetdata.getSize() - ORIGINAL_HEADER_SIZE);
2496 memcpy(*payload, &(packetdata[ORIGINAL_HEADER_SIZE]), payload.getSize());
2499 else if (type == TYPE_SPLIT)
2501 Address peer_address;
2503 if (peer->getAddress(MTP_UDP, peer_address)) {
2505 // We have to create a packet again for buffering
2506 // This isn't actually too bad an idea.
2507 BufferedPacket packet = makePacket(
2510 m_connection->GetProtocolID(),
2514 // Buffer the packet
2515 SharedBuffer<u8> data =
2516 peer->addSpiltPacket(channelnum,packet,reliable);
2518 if (data.getSize() != 0)
2520 LOG(dout_con<<m_connection->getDesc()
2521 <<"RETURNING TYPE_SPLIT: Constructed full data, "
2522 <<"size="<<data.getSize()<<std::endl);
2525 LOG(dout_con<<m_connection->getDesc()<<"BUFFERED TYPE_SPLIT"<<std::endl);
2526 throw ProcessedSilentlyException("Buffered a split packet chunk");
2529 //TODO throw some error
2532 else if (type == TYPE_RELIABLE)
2534 assert(channel != NULL);
2536 // Recursive reliable packets not allowed
2538 throw InvalidIncomingDataException("Found nested reliable packets");
2540 if (packetdata.getSize() < RELIABLE_HEADER_SIZE)
2541 throw InvalidIncomingDataException
2542 ("packetdata.getSize() < RELIABLE_HEADER_SIZE");
2544 u16 seqnum = readU16(&packetdata[1]);
2545 bool is_future_packet = false;
2546 bool is_old_packet = false;
2548 /* packet is within our receive window send ack */
2549 if (seqnum_in_window(seqnum, channel->readNextIncomingSeqNum(),MAX_RELIABLE_WINDOW_SIZE))
2551 m_connection->sendAck(peer_id,channelnum,seqnum);
2554 is_future_packet = seqnum_higher(seqnum, channel->readNextIncomingSeqNum());
2555 is_old_packet = seqnum_higher(channel->readNextIncomingSeqNum(), seqnum);
2558 /* packet is not within receive window, don't send ack. *
2559 * if this was a valid packet it's gonna be retransmitted */
2560 if (is_future_packet)
2562 throw ProcessedSilentlyException("Received packet newer then expected, not sending ack");
2565 /* seems like our ack was lost, send another one for a old packet */
2568 LOG(dout_con<<m_connection->getDesc()
2569 << "RE-SENDING ACK: peer_id: " << peer_id
2570 << ", channel: " << (channelnum&0xFF)
2571 << ", seqnum: " << seqnum << std::endl;)
2572 m_connection->sendAck(peer_id,channelnum,seqnum);
2574 // we already have this packet so this one was on wire at least
2575 // the current timeout
2576 // we don't know how long this packet was on wire don't do silly guessing
2577 // dynamic_cast<UDPPeer*>(&peer)->reportRTT(dynamic_cast<UDPPeer*>(&peer)->getResendTimeout());
2579 throw ProcessedSilentlyException("Retransmitting ack for old packet");
2583 if (seqnum != channel->readNextIncomingSeqNum())
2585 Address peer_address;
2587 // this is a reliable packet so we have a udp address for sure
2588 peer->getAddress(MTP_MINETEST_RELIABLE_UDP, peer_address);
2589 // This one comes later, buffer it.
2590 // Actually we have to make a packet to buffer one.
2591 // Well, we have all the ingredients, so just do it.
2592 BufferedPacket packet = con::makePacket(
2595 m_connection->GetProtocolID(),
2599 channel->incoming_reliables.insert(packet,channel->readNextIncomingSeqNum());
2601 LOG(dout_con<<m_connection->getDesc()
2602 << "BUFFERING, TYPE_RELIABLE peer_id: " << peer_id
2603 << ", channel: " << (channelnum&0xFF)
2604 << ", seqnum: " << seqnum << std::endl;)
2606 throw ProcessedQueued("Buffered future reliable packet");
2608 catch(AlreadyExistsException &e)
2611 catch(IncomingDataCorruption &e)
2613 ConnectionCommand discon;
2614 discon.disconnect_peer(peer_id);
2615 m_connection->putCommand(discon);
2617 LOG(derr_con<<m_connection->getDesc()
2618 << "INVALID, TYPE_RELIABLE peer_id: " << peer_id
2619 << ", channel: " << (channelnum&0xFF)
2620 << ", seqnum: " << seqnum
2621 << "DROPPING CLIENT!" << std::endl;)
2625 /* we got a packet to process right now */
2626 LOG(dout_con<<m_connection->getDesc()
2627 << "RECURSIVE, TYPE_RELIABLE peer_id: " << peer_id
2628 << ", channel: " << (channelnum&0xFF)
2629 << ", seqnum: " << seqnum << std::endl;)
2632 /* check for resend case */
2633 u16 queued_seqnum = 0;
2634 if (channel->incoming_reliables.getFirstSeqnum(queued_seqnum))
2636 if (queued_seqnum == seqnum)
2638 BufferedPacket queued_packet = channel->incoming_reliables.popFirst();
2639 /** TODO find a way to verify the new against the old packet */
2643 channel->incNextIncomingSeqNum();
2645 // Get out the inside packet and re-process it
2646 SharedBuffer<u8> payload(packetdata.getSize() - RELIABLE_HEADER_SIZE);
2647 memcpy(*payload, &packetdata[RELIABLE_HEADER_SIZE], payload.getSize());
2649 return processPacket(channel, payload, peer_id, channelnum, true);
2653 derr_con<<m_connection->getDesc()
2654 <<"Got invalid type="<<((int)type&0xff)<<std::endl;
2655 throw InvalidIncomingDataException("Invalid packet type");
2658 // We should never get here.
2659 FATAL_ERROR("Invalid execution point");
2666 Connection::Connection(u32 protocol_id, u32 max_packet_size, float timeout,
2667 bool ipv6, PeerHandler *peerhandler) :
2672 m_protocol_id(protocol_id),
2673 m_sendThread(max_packet_size, timeout),
2674 m_receiveThread(max_packet_size),
2676 m_bc_peerhandler(peerhandler),
2677 m_bc_receive_timeout(0),
2678 m_shutting_down(false),
2679 m_next_remote_peer_id(2)
2682 m_udpSocket.setTimeoutMs(5);
2684 m_sendThread.setParent(this);
2685 m_receiveThread.setParent(this);
2687 m_sendThread.Start();
2688 m_receiveThread.Start();
2693 Connection::~Connection()
2695 m_shutting_down = true;
2696 // request threads to stop
2697 m_sendThread.Stop();
2698 m_receiveThread.Stop();
2700 //TODO for some unkonwn reason send/receive threads do not exit as they're
2701 // supposed to be but wait on peer timeout. To speed up shutdown we reduce
2702 // timeout to half a second.
2703 m_sendThread.setPeerTimeout(0.5);
2705 // wait for threads to finish
2706 m_sendThread.Wait();
2707 m_receiveThread.Wait();
2710 for(std::map<u16, Peer*>::iterator
2711 j = m_peers.begin();
2712 j != m_peers.end(); ++j)
2718 /* Internal stuff */
2719 void Connection::putEvent(ConnectionEvent &e)
2721 assert(e.type != CONNEVENT_NONE); // Pre-condition
2722 m_event_queue.push_back(e);
2725 PeerHelper Connection::getPeer(u16 peer_id)
2727 JMutexAutoLock peerlock(m_peers_mutex);
2728 std::map<u16, Peer*>::iterator node = m_peers.find(peer_id);
2730 if (node == m_peers.end()) {
2731 throw PeerNotFoundException("GetPeer: Peer not found (possible timeout)");
2735 FATAL_ERROR_IF(node->second->id != peer_id, "Invalid peer id");
2737 return PeerHelper(node->second);
2740 PeerHelper Connection::getPeerNoEx(u16 peer_id)
2742 JMutexAutoLock peerlock(m_peers_mutex);
2743 std::map<u16, Peer*>::iterator node = m_peers.find(peer_id);
2745 if (node == m_peers.end()) {
2746 return PeerHelper(NULL);
2750 FATAL_ERROR_IF(node->second->id != peer_id, "Invalid peer id");
2752 return PeerHelper(node->second);
2755 /* find peer_id for address */
2756 u16 Connection::lookupPeer(Address& sender)
2758 JMutexAutoLock peerlock(m_peers_mutex);
2759 std::map<u16, Peer*>::iterator j;
2760 j = m_peers.begin();
2761 for(; j != m_peers.end(); ++j)
2763 Peer *peer = j->second;
2764 if (peer->isActive())
2769 if ((peer->getAddress(MTP_MINETEST_RELIABLE_UDP, tocheck)) && (tocheck == sender))
2772 if ((peer->getAddress(MTP_UDP, tocheck)) && (tocheck == sender))
2776 return PEER_ID_INEXISTENT;
2779 std::list<Peer*> Connection::getPeers()
2781 std::list<Peer*> list;
2782 for(std::map<u16, Peer*>::iterator j = m_peers.begin();
2783 j != m_peers.end(); ++j)
2785 Peer *peer = j->second;
2786 list.push_back(peer);
2791 bool Connection::deletePeer(u16 peer_id, bool timeout)
2795 /* lock list as short as possible */
2797 JMutexAutoLock peerlock(m_peers_mutex);
2798 if (m_peers.find(peer_id) == m_peers.end())
2800 peer = m_peers[peer_id];
2801 m_peers.erase(peer_id);
2802 m_peer_ids.remove(peer_id);
2805 Address peer_address;
2806 //any peer has a primary address this never fails!
2807 peer->getAddress(MTP_PRIMARY, peer_address);
2810 e.peerRemoved(peer_id, timeout, peer_address);
2820 ConnectionEvent Connection::getEvent()
2822 if (m_event_queue.empty()) {
2824 e.type = CONNEVENT_NONE;
2827 return m_event_queue.pop_frontNoEx();
2830 ConnectionEvent Connection::waitEvent(u32 timeout_ms)
2833 return m_event_queue.pop_front(timeout_ms);
2834 } catch(ItemNotFoundException &ex) {
2836 e.type = CONNEVENT_NONE;
2841 void Connection::putCommand(ConnectionCommand &c)
2843 if (!m_shutting_down) {
2844 m_command_queue.push_back(c);
2845 m_sendThread.Trigger();
2849 void Connection::Serve(Address bind_addr)
2851 ConnectionCommand c;
2856 void Connection::Connect(Address address)
2858 ConnectionCommand c;
2863 bool Connection::Connected()
2865 JMutexAutoLock peerlock(m_peers_mutex);
2867 if (m_peers.size() != 1)
2870 std::map<u16, Peer*>::iterator node = m_peers.find(PEER_ID_SERVER);
2871 if (node == m_peers.end())
2874 if (m_peer_id == PEER_ID_INEXISTENT)
2880 void Connection::Disconnect()
2882 ConnectionCommand c;
2887 void Connection::Receive(NetworkPacket* pkt)
2890 ConnectionEvent e = waitEvent(m_bc_receive_timeout);
2891 if (e.type != CONNEVENT_NONE)
2892 LOG(dout_con << getDesc() << ": Receive: got event: "
2893 << e.describe() << std::endl);
2895 case CONNEVENT_NONE:
2896 throw NoIncomingDataException("No incoming data");
2897 case CONNEVENT_DATA_RECEIVED:
2898 // Data size is lesser than command size, ignoring packet
2899 if (e.data.getSize() < 2) {
2903 pkt->putRawPacket(*e.data, e.data.getSize(), e.peer_id);
2905 case CONNEVENT_PEER_ADDED: {
2906 UDPPeer tmp(e.peer_id, e.address, this);
2907 if (m_bc_peerhandler)
2908 m_bc_peerhandler->peerAdded(&tmp);
2911 case CONNEVENT_PEER_REMOVED: {
2912 UDPPeer tmp(e.peer_id, e.address, this);
2913 if (m_bc_peerhandler)
2914 m_bc_peerhandler->deletingPeer(&tmp, e.timeout);
2917 case CONNEVENT_BIND_FAILED:
2918 throw ConnectionBindFailed("Failed to bind socket "
2919 "(port already in use?)");
2922 throw NoIncomingDataException("No incoming data");
2925 void Connection::Send(u16 peer_id, u8 channelnum,
2926 NetworkPacket* pkt, bool reliable)
2928 assert(channelnum < CHANNEL_COUNT); // Pre-condition
2930 ConnectionCommand c;
2932 c.send(peer_id, channelnum, pkt, reliable);
2936 Address Connection::GetPeerAddress(u16 peer_id)
2938 PeerHelper peer = getPeerNoEx(peer_id);
2941 throw PeerNotFoundException("No address for peer found!");
2942 Address peer_address;
2943 peer->getAddress(MTP_PRIMARY, peer_address);
2944 return peer_address;
2947 float Connection::getPeerStat(u16 peer_id, rtt_stat_type type)
2949 PeerHelper peer = getPeerNoEx(peer_id);
2950 if (!peer) return -1;
2951 return peer->getStat(type);
2954 float Connection::getLocalStat(rate_stat_type type)
2956 PeerHelper peer = getPeerNoEx(PEER_ID_SERVER);
2958 FATAL_ERROR_IF(!peer, "Connection::getLocalStat we couldn't get our own peer? are you serious???");
2962 for (u16 j=0; j<CHANNEL_COUNT; j++) {
2965 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getCurrentDownloadRateKB();
2968 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getAvgDownloadRateKB();
2971 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getCurrentIncomingRateKB();
2974 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getAvgIncomingRateKB();
2977 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getAvgLossRateKB();
2980 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getCurrentLossRateKB();
2983 FATAL_ERROR("Connection::getLocalStat Invalid stat type");
2989 u16 Connection::createPeer(Address& sender, MTProtocols protocol, int fd)
2991 // Somebody wants to make a new connection
2993 // Get a unique peer id (2 or higher)
2994 u16 peer_id_new = m_next_remote_peer_id;
2995 u16 overflow = MAX_UDP_PEERS;
2998 Find an unused peer id
3000 JMutexAutoLock lock(m_peers_mutex);
3001 bool out_of_ids = false;
3004 if (m_peers.find(peer_id_new) == m_peers.end())
3007 // Check for overflow
3008 if (peer_id_new == overflow) {
3016 errorstream << getDesc() << " ran out of peer ids" << std::endl;
3017 return PEER_ID_INEXISTENT;
3022 peer = new UDPPeer(peer_id_new, sender, this);
3024 m_peers[peer->id] = peer;
3025 m_peer_ids.push_back(peer->id);
3027 m_next_remote_peer_id = (peer_id_new +1 ) % MAX_UDP_PEERS;
3029 LOG(dout_con << getDesc()
3030 << "createPeer(): giving peer_id=" << peer_id_new << std::endl);
3032 ConnectionCommand cmd;
3033 SharedBuffer<u8> reply(4);
3034 writeU8(&reply[0], TYPE_CONTROL);
3035 writeU8(&reply[1], CONTROLTYPE_SET_PEER_ID);
3036 writeU16(&reply[2], peer_id_new);
3037 cmd.createPeer(peer_id_new,reply);
3040 // Create peer addition event
3042 e.peerAdded(peer_id_new, sender);
3045 // We're now talking to a valid peer_id
3049 void Connection::PrintInfo(std::ostream &out)
3051 m_info_mutex.Lock();
3052 out<<getDesc()<<": ";
3053 m_info_mutex.Unlock();
3056 void Connection::PrintInfo()
3058 PrintInfo(dout_con);
3061 const std::string Connection::getDesc()
3063 return std::string("con(")+
3064 itos(m_udpSocket.GetHandle())+"/"+itos(m_peer_id)+")";
3067 void Connection::DisconnectPeer(u16 peer_id)
3069 ConnectionCommand discon;
3070 discon.disconnect_peer(peer_id);
3074 void Connection::sendAck(u16 peer_id, u8 channelnum, u16 seqnum)
3076 assert(channelnum < CHANNEL_COUNT); // Pre-condition
3078 LOG(dout_con<<getDesc()
3079 <<" Queuing ACK command to peer_id: " << peer_id <<
3080 " channel: " << (channelnum & 0xFF) <<
3081 " seqnum: " << seqnum << std::endl);
3083 ConnectionCommand c;
3084 SharedBuffer<u8> ack(4);
3085 writeU8(&ack[0], TYPE_CONTROL);
3086 writeU8(&ack[1], CONTROLTYPE_ACK);
3087 writeU16(&ack[2], seqnum);
3089 c.ack(peer_id, channelnum, ack);
3091 m_sendThread.Trigger();
3094 UDPPeer* Connection::createServerPeer(Address& address)
3096 if (getPeerNoEx(PEER_ID_SERVER) != 0)
3098 throw ConnectionException("Already connected to a server");
3101 UDPPeer *peer = new UDPPeer(PEER_ID_SERVER, address, this);
3104 JMutexAutoLock lock(m_peers_mutex);
3105 m_peers[peer->id] = peer;
3106 m_peer_ids.push_back(peer->id);