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"
24 #include "serialization.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 assert(p.data.getSize() >= BASE_HEADER_SIZE+3);
316 u8 type = readU8(&p.data[BASE_HEADER_SIZE+0]);
317 assert(type == TYPE_RELIABLE);
318 u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]);
320 assert(seqnum_in_window(seqnum,next_expected,MAX_RELIABLE_WINDOW_SIZE));
321 assert(seqnum != next_expected);
324 assert(m_list_size <= SEQNUM_MAX+1);
326 // Find the right place for the packet and insert it there
327 // If list is empty, just add it
331 m_oldest_non_answered_ack = seqnum;
336 // Otherwise find the right place
337 std::list<BufferedPacket>::iterator i = m_list.begin();
338 // Find the first packet in the list which has a higher seqnum
339 u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
341 /* case seqnum is smaller then next_expected seqnum */
342 /* this is true e.g. on wrap around */
343 if (seqnum < next_expected) {
344 while(((s < seqnum) || (s >= next_expected)) && (i != m_list.end())) {
346 if (i != m_list.end())
347 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
350 /* non wrap around case (at least for incoming and next_expected */
353 while(((s < seqnum) && (s >= next_expected)) && (i != m_list.end())) {
355 if (i != m_list.end())
356 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
362 (readU16(&(i->data[BASE_HEADER_SIZE+1])) != seqnum) ||
363 (i->data.getSize() != p.data.getSize()) ||
364 (i->address != p.address)
367 /* if this happens your maximum transfer window may be to big */
369 "Duplicated seqnum %d non matching packet detected:\n",
371 fprintf(stderr, "Old: seqnum: %05d size: %04d, address: %s\n",
372 readU16(&(i->data[BASE_HEADER_SIZE+1])),i->data.getSize(),
373 i->address.serializeString().c_str());
374 fprintf(stderr, "New: seqnum: %05d size: %04u, address: %s\n",
375 readU16(&(p.data[BASE_HEADER_SIZE+1])),p.data.getSize(),
376 p.address.serializeString().c_str());
377 throw IncomingDataCorruption("duplicated packet isn't same as original one");
380 assert(readU16(&(i->data[BASE_HEADER_SIZE+1])) == seqnum);
381 assert(i->data.getSize() == p.data.getSize());
382 assert(i->address == p.address);
384 /* nothing to do this seems to be a resent packet */
385 /* for paranoia reason data should be compared */
388 /* insert or push back */
389 else if (i != m_list.end()) {
396 /* update last packet number */
397 m_oldest_non_answered_ack = readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]);
400 void ReliablePacketBuffer::incrementTimeouts(float dtime)
402 JMutexAutoLock listlock(m_list_mutex);
403 for(std::list<BufferedPacket>::iterator i = m_list.begin();
404 i != m_list.end(); ++i)
407 i->totaltime += dtime;
411 std::list<BufferedPacket> ReliablePacketBuffer::getTimedOuts(float timeout,
412 unsigned int max_packets)
414 JMutexAutoLock listlock(m_list_mutex);
415 std::list<BufferedPacket> timed_outs;
416 for(std::list<BufferedPacket>::iterator i = m_list.begin();
417 i != m_list.end(); ++i)
419 if (i->time >= timeout) {
420 timed_outs.push_back(*i);
422 //this packet will be sent right afterwards reset timeout here
424 if (timed_outs.size() >= max_packets)
435 IncomingSplitBuffer::~IncomingSplitBuffer()
437 JMutexAutoLock listlock(m_map_mutex);
438 for(std::map<u16, IncomingSplitPacket*>::iterator i = m_buf.begin();
439 i != m_buf.end(); ++i)
445 This will throw a GotSplitPacketException when a full
446 split packet is constructed.
448 SharedBuffer<u8> IncomingSplitBuffer::insert(BufferedPacket &p, bool reliable)
450 JMutexAutoLock listlock(m_map_mutex);
451 u32 headersize = BASE_HEADER_SIZE + 7;
452 assert(p.data.getSize() >= headersize);
453 u8 type = readU8(&p.data[BASE_HEADER_SIZE+0]);
454 assert(type == TYPE_SPLIT);
455 u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]);
456 u16 chunk_count = readU16(&p.data[BASE_HEADER_SIZE+3]);
457 u16 chunk_num = readU16(&p.data[BASE_HEADER_SIZE+5]);
459 // Add if doesn't exist
460 if (m_buf.find(seqnum) == m_buf.end())
462 IncomingSplitPacket *sp = new IncomingSplitPacket();
463 sp->chunk_count = chunk_count;
464 sp->reliable = reliable;
468 IncomingSplitPacket *sp = m_buf[seqnum];
470 // TODO: These errors should be thrown or something? Dunno.
471 if (chunk_count != sp->chunk_count)
472 LOG(derr_con<<"Connection: WARNING: chunk_count="<<chunk_count
473 <<" != sp->chunk_count="<<sp->chunk_count
475 if (reliable != sp->reliable)
476 LOG(derr_con<<"Connection: WARNING: reliable="<<reliable
477 <<" != sp->reliable="<<sp->reliable
480 // If chunk already exists, ignore it.
481 // Sometimes two identical packets may arrive when there is network
482 // lag and the server re-sends stuff.
483 if (sp->chunks.find(chunk_num) != sp->chunks.end())
484 return SharedBuffer<u8>();
486 // Cut chunk data out of packet
487 u32 chunkdatasize = p.data.getSize() - headersize;
488 SharedBuffer<u8> chunkdata(chunkdatasize);
489 memcpy(*chunkdata, &(p.data[headersize]), chunkdatasize);
491 // Set chunk data in buffer
492 sp->chunks[chunk_num] = chunkdata;
494 // If not all chunks are received, return empty buffer
495 if (sp->allReceived() == false)
496 return SharedBuffer<u8>();
498 // Calculate total size
500 for(std::map<u16, SharedBuffer<u8> >::iterator i = sp->chunks.begin();
501 i != sp->chunks.end(); ++i)
503 totalsize += i->second.getSize();
506 SharedBuffer<u8> fulldata(totalsize);
508 // Copy chunks to data buffer
510 for(u32 chunk_i=0; chunk_i<sp->chunk_count;
513 SharedBuffer<u8> buf = sp->chunks[chunk_i];
514 u16 chunkdatasize = buf.getSize();
515 memcpy(&fulldata[start], *buf, chunkdatasize);
516 start += chunkdatasize;;
519 // Remove sp from buffer
525 void IncomingSplitBuffer::removeUnreliableTimedOuts(float dtime, float timeout)
527 std::list<u16> remove_queue;
529 JMutexAutoLock listlock(m_map_mutex);
530 for(std::map<u16, IncomingSplitPacket*>::iterator i = m_buf.begin();
531 i != m_buf.end(); ++i)
533 IncomingSplitPacket *p = i->second;
534 // Reliable ones are not removed by timeout
535 if (p->reliable == true)
538 if (p->time >= timeout)
539 remove_queue.push_back(i->first);
542 for(std::list<u16>::iterator j = remove_queue.begin();
543 j != remove_queue.end(); ++j)
545 JMutexAutoLock listlock(m_map_mutex);
546 LOG(dout_con<<"NOTE: Removing timed out unreliable split packet"<<std::endl);
557 window_size(MIN_RELIABLE_WINDOW_SIZE),
558 next_incoming_seqnum(SEQNUM_INITIAL),
559 next_outgoing_seqnum(SEQNUM_INITIAL),
560 next_outgoing_split_seqnum(SEQNUM_INITIAL),
561 current_packet_loss(0),
562 current_packet_too_late(0),
563 current_packet_successfull(0),
564 packet_loss_counter(0),
565 current_bytes_transfered(0),
566 current_bytes_received(0),
567 current_bytes_lost(0),
571 max_incoming_kbps(0.0),
572 cur_incoming_kbps(0.0),
573 avg_incoming_kbps(0.0),
586 u16 Channel::readNextIncomingSeqNum()
588 JMutexAutoLock internal(m_internal_mutex);
589 return next_incoming_seqnum;
592 u16 Channel::incNextIncomingSeqNum()
594 JMutexAutoLock internal(m_internal_mutex);
595 u16 retval = next_incoming_seqnum;
596 next_incoming_seqnum++;
600 u16 Channel::readNextSplitSeqNum()
602 JMutexAutoLock internal(m_internal_mutex);
603 return next_outgoing_split_seqnum;
605 void Channel::setNextSplitSeqNum(u16 seqnum)
607 JMutexAutoLock internal(m_internal_mutex);
608 next_outgoing_split_seqnum = seqnum;
611 u16 Channel::getOutgoingSequenceNumber(bool& successfull)
613 JMutexAutoLock internal(m_internal_mutex);
614 u16 retval = next_outgoing_seqnum;
615 u16 lowest_unacked_seqnumber;
617 /* shortcut if there ain't any packet in outgoing list */
618 if (outgoing_reliables_sent.empty())
620 next_outgoing_seqnum++;
624 if (outgoing_reliables_sent.getFirstSeqnum(lowest_unacked_seqnumber))
626 if (lowest_unacked_seqnumber < next_outgoing_seqnum) {
627 // ugly cast but this one is required in order to tell compiler we
628 // know about difference of two unsigned may be negative in general
629 // but we already made sure it won't happen in this case
630 if (((u16)(next_outgoing_seqnum - lowest_unacked_seqnumber)) > window_size) {
636 // ugly cast but this one is required in order to tell compiler we
637 // know about difference of two unsigned may be negative in general
638 // but we already made sure it won't happen in this case
639 if ((next_outgoing_seqnum + (u16)(SEQNUM_MAX - lowest_unacked_seqnumber)) >
647 next_outgoing_seqnum++;
651 u16 Channel::readOutgoingSequenceNumber()
653 JMutexAutoLock internal(m_internal_mutex);
654 return next_outgoing_seqnum;
657 bool Channel::putBackSequenceNumber(u16 seqnum)
659 if (((seqnum + 1) % (SEQNUM_MAX+1)) == next_outgoing_seqnum) {
661 next_outgoing_seqnum = seqnum;
667 void Channel::UpdateBytesSent(unsigned int bytes, unsigned int packets)
669 JMutexAutoLock internal(m_internal_mutex);
670 current_bytes_transfered += bytes;
671 current_packet_successfull += packets;
674 void Channel::UpdateBytesReceived(unsigned int bytes) {
675 JMutexAutoLock internal(m_internal_mutex);
676 current_bytes_received += bytes;
679 void Channel::UpdateBytesLost(unsigned int bytes)
681 JMutexAutoLock internal(m_internal_mutex);
682 current_bytes_lost += bytes;
686 void Channel::UpdatePacketLossCounter(unsigned int count)
688 JMutexAutoLock internal(m_internal_mutex);
689 current_packet_loss += count;
692 void Channel::UpdatePacketTooLateCounter()
694 JMutexAutoLock internal(m_internal_mutex);
695 current_packet_too_late++;
698 void Channel::UpdateTimers(float dtime,bool legacy_peer)
700 bpm_counter += dtime;
701 packet_loss_counter += dtime;
703 if (packet_loss_counter > 1.0)
705 packet_loss_counter -= 1.0;
707 unsigned int packet_loss = 11; /* use a neutral value for initialization */
708 unsigned int packets_successfull = 0;
709 //unsigned int packet_too_late = 0;
711 bool reasonable_amount_of_data_transmitted = false;
714 JMutexAutoLock internal(m_internal_mutex);
715 packet_loss = current_packet_loss;
716 //packet_too_late = current_packet_too_late;
717 packets_successfull = current_packet_successfull;
719 if (current_bytes_transfered > (unsigned int) (window_size*512/2))
721 reasonable_amount_of_data_transmitted = true;
723 current_packet_loss = 0;
724 current_packet_too_late = 0;
725 current_packet_successfull = 0;
728 /* dynamic window size is only available for non legacy peers */
730 float successfull_to_lost_ratio = 0.0;
733 if (packets_successfull > 0) {
734 successfull_to_lost_ratio = packet_loss/packets_successfull;
736 else if (packet_loss > 0)
740 MIN_RELIABLE_WINDOW_SIZE);
746 if ((successfull_to_lost_ratio < 0.01) &&
747 (window_size < MAX_RELIABLE_WINDOW_SIZE))
749 /* don't even think about increasing if we didn't even
750 * use major parts of our window */
751 if (reasonable_amount_of_data_transmitted)
754 MAX_RELIABLE_WINDOW_SIZE);
756 else if ((successfull_to_lost_ratio < 0.05) &&
757 (window_size < MAX_RELIABLE_WINDOW_SIZE))
759 /* don't even think about increasing if we didn't even
760 * use major parts of our window */
761 if (reasonable_amount_of_data_transmitted)
764 MAX_RELIABLE_WINDOW_SIZE);
766 else if (successfull_to_lost_ratio > 0.15)
770 MIN_RELIABLE_WINDOW_SIZE);
772 else if (successfull_to_lost_ratio > 0.1)
776 MIN_RELIABLE_WINDOW_SIZE);
782 if (bpm_counter > 10.0)
785 JMutexAutoLock internal(m_internal_mutex);
787 (((float) current_bytes_transfered)/bpm_counter)/1024.0;
788 current_bytes_transfered = 0;
790 (((float) current_bytes_lost)/bpm_counter)/1024.0;
791 current_bytes_lost = 0;
793 (((float) current_bytes_received)/bpm_counter)/1024.0;
794 current_bytes_received = 0;
798 if (cur_kbps > max_kbps)
803 if (cur_kbps_lost > max_kbps_lost)
805 max_kbps_lost = cur_kbps_lost;
808 if (cur_incoming_kbps > max_incoming_kbps) {
809 max_incoming_kbps = cur_incoming_kbps;
812 rate_samples = MYMIN(rate_samples+1,10);
813 float old_fraction = ((float) (rate_samples-1) )/( (float) rate_samples);
814 avg_kbps = avg_kbps * old_fraction +
815 cur_kbps * (1.0 - old_fraction);
816 avg_kbps_lost = avg_kbps_lost * old_fraction +
817 cur_kbps_lost * (1.0 - old_fraction);
818 avg_incoming_kbps = avg_incoming_kbps * old_fraction +
819 cur_incoming_kbps * (1.0 - old_fraction);
828 PeerHelper::PeerHelper() :
832 PeerHelper::PeerHelper(Peer* peer) :
837 if (!peer->IncUseCount())
844 PeerHelper::~PeerHelper()
847 m_peer->DecUseCount();
852 PeerHelper& PeerHelper::operator=(Peer* peer)
857 if (!peer->IncUseCount())
865 Peer* PeerHelper::operator->() const
870 Peer* PeerHelper::operator&() const
875 bool PeerHelper::operator!() {
879 bool PeerHelper::operator!=(void* ptr)
881 return ((void*) m_peer != ptr);
884 bool Peer::IncUseCount()
886 JMutexAutoLock lock(m_exclusive_access_mutex);
888 if (!m_pending_deletion)
897 void Peer::DecUseCount()
900 JMutexAutoLock lock(m_exclusive_access_mutex);
904 if (!((m_pending_deletion) && (m_usage == 0)))
910 void Peer::RTTStatistics(float rtt, std::string profiler_id,
911 unsigned int num_samples) {
913 if (m_last_rtt > 0) {
914 /* set min max values */
915 if (rtt < m_rtt.min_rtt)
917 if (rtt >= m_rtt.max_rtt)
920 /* do average calculation */
921 if (m_rtt.avg_rtt < 0.0)
924 m_rtt.avg_rtt = m_rtt.avg_rtt * (num_samples/(num_samples-1)) +
925 rtt * (1/num_samples);
927 /* do jitter calculation */
929 //just use some neutral value at beginning
930 float jitter = m_rtt.jitter_min;
932 if (rtt > m_last_rtt)
933 jitter = rtt-m_last_rtt;
935 if (rtt <= m_last_rtt)
936 jitter = m_last_rtt - rtt;
938 if (jitter < m_rtt.jitter_min)
939 m_rtt.jitter_min = jitter;
940 if (jitter >= m_rtt.jitter_max)
941 m_rtt.jitter_max = jitter;
943 if (m_rtt.jitter_avg < 0.0)
944 m_rtt.jitter_avg = jitter;
946 m_rtt.jitter_avg = m_rtt.jitter_avg * (num_samples/(num_samples-1)) +
947 jitter * (1/num_samples);
949 if (profiler_id != "")
951 g_profiler->graphAdd(profiler_id + "_rtt", rtt);
952 g_profiler->graphAdd(profiler_id + "_jitter", jitter);
955 /* save values required for next loop */
959 bool Peer::isTimedOut(float timeout)
961 JMutexAutoLock lock(m_exclusive_access_mutex);
962 u32 current_time = porting::getTimeMs();
964 float dtime = CALC_DTIME(m_last_timeout_check,current_time);
965 m_last_timeout_check = current_time;
967 m_timeout_counter += dtime;
969 return m_timeout_counter > timeout;
975 JMutexAutoLock usage_lock(m_exclusive_access_mutex);
976 m_pending_deletion = true;
981 PROFILE(std::stringstream peerIdentifier1);
982 PROFILE(peerIdentifier1 << "runTimeouts[" << m_connection->getDesc()
983 << ";" << id << ";RELIABLE]");
984 PROFILE(g_profiler->remove(peerIdentifier1.str()));
985 PROFILE(std::stringstream peerIdentifier2);
986 PROFILE(peerIdentifier2 << "sendPackets[" << m_connection->getDesc()
987 << ";" << id << ";RELIABLE]");
988 PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier2.str(), SPT_AVG));
993 UDPPeer::UDPPeer(u16 a_id, Address a_address, Connection* connection) :
994 Peer(a_address,a_id,connection),
995 m_pending_disconnect(false),
1001 bool UDPPeer::getAddress(MTProtocols type,Address& toset)
1003 if ((type == MTP_UDP) || (type == MTP_MINETEST_RELIABLE_UDP) || (type == MTP_PRIMARY))
1012 void UDPPeer::setNonLegacyPeer()
1014 m_legacy_peer = false;
1015 for(unsigned int i=0; i< CHANNEL_COUNT; i++)
1017 channels->setWindowSize(g_settings->getU16("max_packets_per_iteration"));
1021 void UDPPeer::reportRTT(float rtt)
1026 RTTStatistics(rtt,"rudp",MAX_RELIABLE_WINDOW_SIZE*10);
1028 float timeout = getStat(AVG_RTT) * RESEND_TIMEOUT_FACTOR;
1029 if (timeout < RESEND_TIMEOUT_MIN)
1030 timeout = RESEND_TIMEOUT_MIN;
1031 if (timeout > RESEND_TIMEOUT_MAX)
1032 timeout = RESEND_TIMEOUT_MAX;
1034 JMutexAutoLock usage_lock(m_exclusive_access_mutex);
1035 resend_timeout = timeout;
1038 bool UDPPeer::Ping(float dtime,SharedBuffer<u8>& data)
1040 m_ping_timer += dtime;
1041 if (m_ping_timer >= PING_TIMEOUT)
1043 // Create and send PING packet
1044 writeU8(&data[0], TYPE_CONTROL);
1045 writeU8(&data[1], CONTROLTYPE_PING);
1052 void UDPPeer::PutReliableSendCommand(ConnectionCommand &c,
1053 unsigned int max_packet_size)
1055 if (m_pending_disconnect)
1058 if ( channels[c.channelnum].queued_commands.empty() &&
1059 /* don't queue more packets then window size */
1060 (channels[c.channelnum].queued_reliables.size()
1061 < (channels[c.channelnum].getWindowSize()/2)))
1063 LOG(dout_con<<m_connection->getDesc()
1064 <<" processing reliable command for peer id: " << c.peer_id
1065 <<" data size: " << c.data.getSize() << std::endl);
1066 if (!processReliableSendCommand(c,max_packet_size))
1068 channels[c.channelnum].queued_commands.push_back(c);
1073 LOG(dout_con<<m_connection->getDesc()
1074 <<" Queueing reliable command for peer id: " << c.peer_id
1075 <<" data size: " << c.data.getSize() <<std::endl);
1076 channels[c.channelnum].queued_commands.push_back(c);
1080 bool UDPPeer::processReliableSendCommand(
1081 ConnectionCommand &c,
1082 unsigned int max_packet_size)
1084 if (m_pending_disconnect)
1087 u32 chunksize_max = max_packet_size
1089 - RELIABLE_HEADER_SIZE;
1091 assert(c.data.getSize() < MAX_RELIABLE_WINDOW_SIZE*512);
1093 std::list<SharedBuffer<u8> > originals;
1094 u16 split_sequence_number = channels[c.channelnum].readNextSplitSeqNum();
1098 originals.push_back(c.data);
1101 originals = makeAutoSplitPacket(c.data, chunksize_max,split_sequence_number);
1102 channels[c.channelnum].setNextSplitSeqNum(split_sequence_number);
1105 bool have_sequence_number = true;
1106 bool have_initial_sequence_number = false;
1107 Queue<BufferedPacket> toadd;
1108 volatile u16 initial_sequence_number = 0;
1110 for(std::list<SharedBuffer<u8> >::iterator i = originals.begin();
1111 i != originals.end(); ++i)
1113 u16 seqnum = channels[c.channelnum].getOutgoingSequenceNumber(have_sequence_number);
1115 /* oops, we don't have enough sequence numbers to send this packet */
1116 if (!have_sequence_number)
1119 if (!have_initial_sequence_number)
1121 initial_sequence_number = seqnum;
1122 have_initial_sequence_number = true;
1125 SharedBuffer<u8> reliable = makeReliablePacket(*i, seqnum);
1127 // Add base headers and make a packet
1128 BufferedPacket p = con::makePacket(address, reliable,
1129 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1135 if (have_sequence_number) {
1136 volatile u16 pcount = 0;
1137 while(toadd.size() > 0) {
1138 BufferedPacket p = toadd.pop_front();
1139 // LOG(dout_con<<connection->getDesc()
1140 // << " queuing reliable packet for peer_id: " << c.peer_id
1141 // << " channel: " << (c.channelnum&0xFF)
1142 // << " seqnum: " << readU16(&p.data[BASE_HEADER_SIZE+1])
1144 channels[c.channelnum].queued_reliables.push_back(p);
1147 assert(channels[c.channelnum].queued_reliables.size() < 0xFFFF);
1151 volatile u16 packets_available = toadd.size();
1152 /* we didn't get a single sequence number no need to fill queue */
1153 if (!have_initial_sequence_number)
1157 while(toadd.size() > 0) {
1161 bool successfully_put_back_sequence_number
1162 = channels[c.channelnum].putBackSequenceNumber(
1163 (initial_sequence_number+toadd.size() % (SEQNUM_MAX+1)));
1165 assert(successfully_put_back_sequence_number);
1167 LOG(dout_con<<m_connection->getDesc()
1168 << " Windowsize exceeded on reliable sending "
1169 << c.data.getSize() << " bytes"
1170 << std::endl << "\t\tinitial_sequence_number: "
1171 << initial_sequence_number
1172 << std::endl << "\t\tgot at most : "
1173 << packets_available << " packets"
1174 << std::endl << "\t\tpackets queued : "
1175 << channels[c.channelnum].outgoing_reliables_sent.size()
1181 void UDPPeer::RunCommandQueues(
1182 unsigned int max_packet_size,
1183 unsigned int maxcommands,
1184 unsigned int maxtransfer)
1187 for (unsigned int i = 0; i < CHANNEL_COUNT; i++)
1189 unsigned int commands_processed = 0;
1191 if ((channels[i].queued_commands.size() > 0) &&
1192 (channels[i].queued_reliables.size() < maxtransfer) &&
1193 (commands_processed < maxcommands))
1196 ConnectionCommand c = channels[i].queued_commands.pop_front();
1197 LOG(dout_con<<m_connection->getDesc()
1198 <<" processing queued reliable command "<<std::endl);
1199 if (!processReliableSendCommand(c,max_packet_size)) {
1200 LOG(dout_con<<m_connection->getDesc()
1201 << " Failed to queue packets for peer_id: " << c.peer_id
1202 << ", delaying sending of " << c.data.getSize()
1203 << " bytes" << std::endl);
1204 channels[i].queued_commands.push_front(c);
1207 catch (ItemNotFoundException &e) {
1208 // intentionally empty
1214 u16 UDPPeer::getNextSplitSequenceNumber(u8 channel)
1216 assert(channel < CHANNEL_COUNT);
1217 return channels[channel].readNextIncomingSeqNum();
1220 void UDPPeer::setNextSplitSequenceNumber(u8 channel, u16 seqnum)
1222 assert(channel < CHANNEL_COUNT);
1223 channels[channel].setNextSplitSeqNum(seqnum);
1226 SharedBuffer<u8> UDPPeer::addSpiltPacket(u8 channel,
1227 BufferedPacket toadd,
1230 assert(channel < CHANNEL_COUNT);
1231 return channels[channel].incoming_splits.insert(toadd,reliable);
1234 /******************************************************************************/
1235 /* Connection Threads */
1236 /******************************************************************************/
1238 ConnectionSendThread::ConnectionSendThread( unsigned int max_packet_size,
1241 m_max_packet_size(max_packet_size),
1243 m_max_commands_per_iteration(1),
1244 m_max_data_packets_per_iteration(g_settings->getU16("max_packets_per_iteration")),
1245 m_max_packets_requeued(256)
1249 void * ConnectionSendThread::Thread()
1251 assert(m_connection != NULL);
1253 log_register_thread("ConnectionSend");
1255 LOG(dout_con<<m_connection->getDesc()
1256 <<"ConnectionSend thread started"<<std::endl);
1258 u32 curtime = porting::getTimeMs();
1259 u32 lasttime = curtime;
1261 PROFILE(std::stringstream ThreadIdentifier);
1262 PROFILE(ThreadIdentifier << "ConnectionSend: [" << m_connection->getDesc() << "]");
1264 porting::setThreadName("ConnectionSend");
1266 /* if stop is requested don't stop immediately but try to send all */
1268 while(!StopRequested() || packetsQueued()) {
1269 BEGIN_DEBUG_EXCEPTION_HANDLER
1270 PROFILE(ScopeProfiler sp(g_profiler, ThreadIdentifier.str(), SPT_AVG));
1272 m_iteration_packets_avaialble = m_max_data_packets_per_iteration;
1274 /* wait for trigger or timeout */
1275 m_send_sleep_semaphore.Wait(50);
1277 /* remove all triggers */
1278 while(m_send_sleep_semaphore.Wait(0)) {}
1281 curtime = porting::getTimeMs();
1282 float dtime = CALC_DTIME(lasttime,curtime);
1284 /* first do all the reliable stuff */
1287 /* translate commands to packets */
1288 ConnectionCommand c = m_connection->m_command_queue.pop_frontNoEx(0);
1289 while(c.type != CONNCMD_NONE)
1292 processReliableCommand(c);
1294 processNonReliableCommand(c);
1296 c = m_connection->m_command_queue.pop_frontNoEx(0);
1299 /* send non reliable packets */
1302 END_DEBUG_EXCEPTION_HANDLER(errorstream);
1305 PROFILE(g_profiler->remove(ThreadIdentifier.str()));
1309 void ConnectionSendThread::Trigger()
1311 m_send_sleep_semaphore.Post();
1314 bool ConnectionSendThread::packetsQueued()
1316 std::list<u16> peerIds = m_connection->getPeerIDs();
1318 if (!m_outgoing_queue.empty() && !peerIds.empty())
1321 for(std::list<u16>::iterator j = peerIds.begin();
1322 j != peerIds.end(); ++j)
1324 PeerHelper peer = m_connection->getPeerNoEx(*j);
1329 if (dynamic_cast<UDPPeer*>(&peer) == 0)
1332 for(u16 i=0; i<CHANNEL_COUNT; i++)
1334 Channel *channel = &(dynamic_cast<UDPPeer*>(&peer))->channels[i];
1336 if (channel->queued_commands.size() > 0)
1347 void ConnectionSendThread::runTimeouts(float dtime)
1349 std::list<u16> timeouted_peers;
1350 std::list<u16> peerIds = m_connection->getPeerIDs();
1352 for(std::list<u16>::iterator j = peerIds.begin();
1353 j != peerIds.end(); ++j)
1355 PeerHelper peer = m_connection->getPeerNoEx(*j);
1360 if (dynamic_cast<UDPPeer*>(&peer) == 0)
1363 PROFILE(std::stringstream peerIdentifier);
1364 PROFILE(peerIdentifier << "runTimeouts[" << m_connection->getDesc()
1365 << ";" << *j << ";RELIABLE]");
1366 PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier.str(), SPT_AVG));
1368 SharedBuffer<u8> data(2); // data for sending ping, required here because of goto
1373 if (peer->isTimedOut(m_timeout))
1375 infostream<<m_connection->getDesc()
1376 <<"RunTimeouts(): Peer "<<peer->id
1378 <<" (source=peer->timeout_counter)"
1380 // Add peer to the list
1381 timeouted_peers.push_back(peer->id);
1382 // Don't bother going through the buffers of this one
1386 float resend_timeout = dynamic_cast<UDPPeer*>(&peer)->getResendTimeout();
1387 for(u16 i=0; i<CHANNEL_COUNT; i++)
1389 std::list<BufferedPacket> timed_outs;
1390 Channel *channel = &(dynamic_cast<UDPPeer*>(&peer))->channels[i];
1392 if (dynamic_cast<UDPPeer*>(&peer)->getLegacyPeer())
1393 channel->setWindowSize(g_settings->getU16("workaround_window_size"));
1395 // Remove timed out incomplete unreliable split packets
1396 channel->incoming_splits.removeUnreliableTimedOuts(dtime, m_timeout);
1398 // Increment reliable packet times
1399 channel->outgoing_reliables_sent.incrementTimeouts(dtime);
1401 unsigned int numpeers = m_connection->m_peers.size();
1406 // Re-send timed out outgoing reliables
1407 timed_outs = channel->
1408 outgoing_reliables_sent.getTimedOuts(resend_timeout,
1409 (m_max_data_packets_per_iteration/numpeers));
1411 channel->UpdatePacketLossCounter(timed_outs.size());
1412 g_profiler->graphAdd("packets_lost", timed_outs.size());
1414 m_iteration_packets_avaialble -= timed_outs.size();
1416 for(std::list<BufferedPacket>::iterator k = timed_outs.begin();
1417 k != timed_outs.end(); ++k)
1419 u16 peer_id = readPeerId(*(k->data));
1420 u8 channelnum = readChannel(*(k->data));
1421 u16 seqnum = readU16(&(k->data[BASE_HEADER_SIZE+1]));
1423 channel->UpdateBytesLost(k->data.getSize());
1426 LOG(derr_con<<m_connection->getDesc()
1427 <<"RE-SENDING timed-out RELIABLE to "
1428 << k->address.serializeString()
1429 << "(t/o="<<resend_timeout<<"): "
1430 <<"from_peer_id="<<peer_id
1431 <<", channel="<<((int)channelnum&0xff)
1432 <<", seqnum="<<seqnum
1437 // do not handle rtt here as we can't decide if this packet was
1438 // lost or really takes more time to transmit
1440 channel->UpdateTimers(dtime,dynamic_cast<UDPPeer*>(&peer)->getLegacyPeer());
1443 /* send ping if necessary */
1444 if (dynamic_cast<UDPPeer*>(&peer)->Ping(dtime,data)) {
1445 LOG(dout_con<<m_connection->getDesc()
1446 <<"Sending ping for peer_id: "
1447 << dynamic_cast<UDPPeer*>(&peer)->id <<std::endl);
1448 /* this may fail if there ain't a sequence number left */
1449 if (!rawSendAsPacket(dynamic_cast<UDPPeer*>(&peer)->id, 0, data, true))
1451 //retrigger with reduced ping interval
1452 dynamic_cast<UDPPeer*>(&peer)->Ping(4.0,data);
1456 dynamic_cast<UDPPeer*>(&peer)->RunCommandQueues(m_max_packet_size,
1457 m_max_commands_per_iteration,
1458 m_max_packets_requeued);
1461 // Remove timed out peers
1462 for(std::list<u16>::iterator i = timeouted_peers.begin();
1463 i != timeouted_peers.end(); ++i)
1465 LOG(derr_con<<m_connection->getDesc()
1466 <<"RunTimeouts(): Removing peer "<<(*i)<<std::endl);
1467 m_connection->deletePeer(*i, true);
1471 void ConnectionSendThread::rawSend(const BufferedPacket &packet)
1474 m_connection->m_udpSocket.Send(packet.address, *packet.data,
1475 packet.data.getSize());
1476 LOG(dout_con <<m_connection->getDesc()
1477 << " rawSend: " << packet.data.getSize()
1478 << " bytes sent" << std::endl);
1479 } catch(SendFailedException &e) {
1480 LOG(derr_con<<m_connection->getDesc()
1481 <<"Connection::rawSend(): SendFailedException: "
1482 <<packet.address.serializeString()<<std::endl);
1486 void ConnectionSendThread::sendAsPacketReliable(BufferedPacket& p, Channel* channel)
1489 p.absolute_send_time = porting::getTimeMs();
1490 // Buffer the packet
1491 channel->outgoing_reliables_sent.insert(p,
1492 (channel->readOutgoingSequenceNumber() - MAX_RELIABLE_WINDOW_SIZE)
1493 % (MAX_RELIABLE_WINDOW_SIZE+1));
1495 catch(AlreadyExistsException &e)
1497 LOG(derr_con<<m_connection->getDesc()
1498 <<"WARNING: Going to send a reliable packet"
1499 <<" in outgoing buffer" <<std::endl);
1507 bool ConnectionSendThread::rawSendAsPacket(u16 peer_id, u8 channelnum,
1508 SharedBuffer<u8> data, bool reliable)
1510 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
1512 LOG(dout_con<<m_connection->getDesc()
1513 <<" INFO: dropped packet for non existent peer_id: "
1514 << peer_id << std::endl);
1515 assert(reliable && "trying to send raw packet reliable but no peer found!");
1518 Channel *channel = &(dynamic_cast<UDPPeer*>(&peer)->channels[channelnum]);
1522 bool have_sequence_number_for_raw_packet = true;
1524 channel->getOutgoingSequenceNumber(have_sequence_number_for_raw_packet);
1526 if (!have_sequence_number_for_raw_packet)
1529 SharedBuffer<u8> reliable = makeReliablePacket(data, seqnum);
1530 Address peer_address;
1531 peer->getAddress(MTP_MINETEST_RELIABLE_UDP, peer_address);
1533 // Add base headers and make a packet
1534 BufferedPacket p = con::makePacket(peer_address, reliable,
1535 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1538 // first check if our send window is already maxed out
1539 if (channel->outgoing_reliables_sent.size()
1540 < channel->getWindowSize()) {
1541 LOG(dout_con<<m_connection->getDesc()
1542 <<" INFO: sending a reliable packet to peer_id " << peer_id
1543 <<" channel: " << channelnum
1544 <<" seqnum: " << seqnum << std::endl);
1545 sendAsPacketReliable(p,channel);
1549 LOG(dout_con<<m_connection->getDesc()
1550 <<" INFO: queueing reliable packet for peer_id: " << peer_id
1551 <<" channel: " << channelnum
1552 <<" seqnum: " << seqnum << std::endl);
1553 channel->queued_reliables.push_back(p);
1559 Address peer_address;
1561 if (peer->getAddress(MTP_UDP, peer_address))
1563 // Add base headers and make a packet
1564 BufferedPacket p = con::makePacket(peer_address, data,
1565 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1573 LOG(dout_con<<m_connection->getDesc()
1574 <<" INFO: dropped unreliable packet for peer_id: " << peer_id
1575 <<" because of (yet) missing udp address" << std::endl);
1584 void ConnectionSendThread::processReliableCommand(ConnectionCommand &c)
1590 LOG(dout_con<<m_connection->getDesc()
1591 <<"UDP processing reliable CONNCMD_NONE"<<std::endl);
1595 LOG(dout_con<<m_connection->getDesc()
1596 <<"UDP processing reliable CONNCMD_SEND"<<std::endl);
1600 case CONNCMD_SEND_TO_ALL:
1601 LOG(dout_con<<m_connection->getDesc()
1602 <<"UDP processing CONNCMD_SEND_TO_ALL"<<std::endl);
1603 sendToAllReliable(c);
1606 case CONCMD_CREATE_PEER:
1607 LOG(dout_con<<m_connection->getDesc()
1608 <<"UDP processing reliable CONCMD_CREATE_PEER"<<std::endl);
1609 if (!rawSendAsPacket(c.peer_id,c.channelnum,c.data,c.reliable))
1611 /* put to queue if we couldn't send it immediately */
1616 case CONCMD_DISABLE_LEGACY:
1617 LOG(dout_con<<m_connection->getDesc()
1618 <<"UDP processing reliable CONCMD_DISABLE_LEGACY"<<std::endl);
1619 if (!rawSendAsPacket(c.peer_id,c.channelnum,c.data,c.reliable))
1621 /* put to queue if we couldn't send it immediately */
1627 case CONNCMD_CONNECT:
1628 case CONNCMD_DISCONNECT:
1630 assert("Got command that shouldn't be reliable as reliable command" == 0);
1632 LOG(dout_con<<m_connection->getDesc()
1633 <<" Invalid reliable command type: " << c.type <<std::endl);
1638 void ConnectionSendThread::processNonReliableCommand(ConnectionCommand &c)
1640 assert(!c.reliable);
1644 LOG(dout_con<<m_connection->getDesc()
1645 <<" UDP processing CONNCMD_NONE"<<std::endl);
1648 LOG(dout_con<<m_connection->getDesc()
1649 <<" UDP processing CONNCMD_SERVE port="
1650 <<c.address.serializeString()<<std::endl);
1653 case CONNCMD_CONNECT:
1654 LOG(dout_con<<m_connection->getDesc()
1655 <<" UDP processing CONNCMD_CONNECT"<<std::endl);
1658 case CONNCMD_DISCONNECT:
1659 LOG(dout_con<<m_connection->getDesc()
1660 <<" UDP processing CONNCMD_DISCONNECT"<<std::endl);
1663 case CONNCMD_DISCONNECT_PEER:
1664 LOG(dout_con<<m_connection->getDesc()
1665 <<" UDP processing CONNCMD_DISCONNECT_PEER"<<std::endl);
1666 disconnect_peer(c.peer_id);
1669 LOG(dout_con<<m_connection->getDesc()
1670 <<" UDP processing CONNCMD_SEND"<<std::endl);
1671 send(c.peer_id, c.channelnum, c.data);
1673 case CONNCMD_SEND_TO_ALL:
1674 LOG(dout_con<<m_connection->getDesc()
1675 <<" UDP processing CONNCMD_SEND_TO_ALL"<<std::endl);
1676 sendToAll(c.channelnum, c.data);
1679 LOG(dout_con<<m_connection->getDesc()
1680 <<" UDP processing CONCMD_ACK"<<std::endl);
1681 sendAsPacket(c.peer_id,c.channelnum,c.data,true);
1683 case CONCMD_CREATE_PEER:
1684 assert("Got command that should be reliable as unreliable command" == 0);
1686 LOG(dout_con<<m_connection->getDesc()
1687 <<" Invalid command type: " << c.type <<std::endl);
1691 void ConnectionSendThread::serve(Address bind_address)
1693 LOG(dout_con<<m_connection->getDesc()
1694 <<"UDP serving at port " << bind_address.serializeString() <<std::endl);
1696 m_connection->m_udpSocket.Bind(bind_address);
1697 m_connection->SetPeerID(PEER_ID_SERVER);
1699 catch(SocketException &e) {
1703 m_connection->putEvent(ce);
1707 void ConnectionSendThread::connect(Address address)
1709 LOG(dout_con<<m_connection->getDesc()<<" connecting to "<<address.serializeString()
1710 <<":"<<address.getPort()<<std::endl);
1712 UDPPeer *peer = m_connection->createServerPeer(address);
1716 e.peerAdded(peer->id, peer->address);
1717 m_connection->putEvent(e);
1721 if (address.isIPv6())
1722 bind_addr.setAddress((IPv6AddressBytes*) NULL);
1724 bind_addr.setAddress(0,0,0,0);
1726 m_connection->m_udpSocket.Bind(bind_addr);
1728 // Send a dummy packet to server with peer_id = PEER_ID_INEXISTENT
1729 m_connection->SetPeerID(PEER_ID_INEXISTENT);
1730 NetworkPacket* pkt = new NetworkPacket(0,0);
1731 m_connection->Send(PEER_ID_SERVER, 0, pkt, true);
1735 void ConnectionSendThread::disconnect()
1737 LOG(dout_con<<m_connection->getDesc()<<" disconnecting"<<std::endl);
1739 // Create and send DISCO packet
1740 SharedBuffer<u8> data(2);
1741 writeU8(&data[0], TYPE_CONTROL);
1742 writeU8(&data[1], CONTROLTYPE_DISCO);
1746 std::list<u16> peerids = m_connection->getPeerIDs();
1748 for (std::list<u16>::iterator i = peerids.begin();
1752 sendAsPacket(*i, 0,data,false);
1756 void ConnectionSendThread::disconnect_peer(u16 peer_id)
1758 LOG(dout_con<<m_connection->getDesc()<<" disconnecting peer"<<std::endl);
1760 // Create and send DISCO packet
1761 SharedBuffer<u8> data(2);
1762 writeU8(&data[0], TYPE_CONTROL);
1763 writeU8(&data[1], CONTROLTYPE_DISCO);
1764 sendAsPacket(peer_id, 0,data,false);
1766 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
1771 if (dynamic_cast<UDPPeer*>(&peer) == 0)
1776 dynamic_cast<UDPPeer*>(&peer)->m_pending_disconnect = true;
1779 void ConnectionSendThread::send(u16 peer_id, u8 channelnum,
1780 SharedBuffer<u8> data)
1782 assert(channelnum < CHANNEL_COUNT);
1784 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
1787 LOG(dout_con<<m_connection->getDesc()<<" peer: peer_id="<<peer_id
1788 << ">>>NOT<<< found on sending packet"
1789 << ", channel " << (channelnum % 0xFF)
1790 << ", size: " << data.getSize() <<std::endl);
1794 LOG(dout_con<<m_connection->getDesc()<<" sending to peer_id="<<peer_id
1795 << ", channel " << (channelnum % 0xFF)
1796 << ", size: " << data.getSize() <<std::endl);
1798 u16 split_sequence_number = peer->getNextSplitSequenceNumber(channelnum);
1800 u32 chunksize_max = m_max_packet_size - BASE_HEADER_SIZE;
1801 std::list<SharedBuffer<u8> > originals;
1803 originals = makeAutoSplitPacket(data, chunksize_max,split_sequence_number);
1805 peer->setNextSplitSequenceNumber(channelnum,split_sequence_number);
1807 for(std::list<SharedBuffer<u8> >::iterator i = originals.begin();
1808 i != originals.end(); ++i)
1810 SharedBuffer<u8> original = *i;
1811 sendAsPacket(peer_id, channelnum, original);
1815 void ConnectionSendThread::sendReliable(ConnectionCommand &c)
1817 PeerHelper peer = m_connection->getPeerNoEx(c.peer_id);
1821 peer->PutReliableSendCommand(c,m_max_packet_size);
1824 void ConnectionSendThread::sendToAll(u8 channelnum, SharedBuffer<u8> data)
1826 std::list<u16> peerids = m_connection->getPeerIDs();
1828 for (std::list<u16>::iterator i = peerids.begin();
1832 send(*i, channelnum, data);
1836 void ConnectionSendThread::sendToAllReliable(ConnectionCommand &c)
1838 std::list<u16> peerids = m_connection->getPeerIDs();
1840 for (std::list<u16>::iterator i = peerids.begin();
1844 PeerHelper peer = m_connection->getPeerNoEx(*i);
1849 peer->PutReliableSendCommand(c,m_max_packet_size);
1853 void ConnectionSendThread::sendPackets(float dtime)
1855 std::list<u16> peerIds = m_connection->getPeerIDs();
1856 std::list<u16> pendingDisconnect;
1857 std::map<u16,bool> pending_unreliable;
1859 for(std::list<u16>::iterator
1860 j = peerIds.begin();
1861 j != peerIds.end(); ++j)
1863 PeerHelper peer = m_connection->getPeerNoEx(*j);
1864 //peer may have been removed
1866 LOG(dout_con<<m_connection->getDesc()<< " Peer not found: peer_id=" << *j << std::endl);
1869 peer->m_increment_packets_remaining = m_iteration_packets_avaialble/m_connection->m_peers.size();
1871 if (dynamic_cast<UDPPeer*>(&peer) == 0)
1876 if (dynamic_cast<UDPPeer*>(&peer)->m_pending_disconnect)
1878 pendingDisconnect.push_back(*j);
1881 PROFILE(std::stringstream peerIdentifier);
1882 PROFILE(peerIdentifier << "sendPackets[" << m_connection->getDesc() << ";" << *j << ";RELIABLE]");
1883 PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier.str(), SPT_AVG));
1885 LOG(dout_con<<m_connection->getDesc()
1886 << " Handle per peer queues: peer_id=" << *j
1887 << " packet quota: " << peer->m_increment_packets_remaining << std::endl);
1888 // first send queued reliable packets for all peers (if possible)
1889 for (unsigned int i=0; i < CHANNEL_COUNT; i++)
1891 u16 next_to_ack = 0;
1892 dynamic_cast<UDPPeer*>(&peer)->channels[i].outgoing_reliables_sent.getFirstSeqnum(next_to_ack);
1893 u16 next_to_receive = 0;
1894 dynamic_cast<UDPPeer*>(&peer)->channels[i].incoming_reliables.getFirstSeqnum(next_to_receive);
1896 LOG(dout_con<<m_connection->getDesc()<< "\t channel: "
1897 << i << ", peer quota:"
1898 << peer->m_increment_packets_remaining
1900 << "\t\t\treliables on wire: "
1901 << dynamic_cast<UDPPeer*>(&peer)->channels[i].outgoing_reliables_sent.size()
1902 << ", waiting for ack for " << next_to_ack
1904 << "\t\t\tincoming_reliables: "
1905 << dynamic_cast<UDPPeer*>(&peer)->channels[i].incoming_reliables.size()
1906 << ", next reliable packet: "
1907 << dynamic_cast<UDPPeer*>(&peer)->channels[i].readNextIncomingSeqNum()
1908 << ", next queued: " << next_to_receive
1910 << "\t\t\treliables queued : "
1911 << dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.size()
1913 << "\t\t\tqueued commands : "
1914 << dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_commands.size()
1917 while ((dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.size() > 0) &&
1918 (dynamic_cast<UDPPeer*>(&peer)->channels[i].outgoing_reliables_sent.size()
1919 < dynamic_cast<UDPPeer*>(&peer)->channels[i].getWindowSize())&&
1920 (peer->m_increment_packets_remaining > 0))
1922 BufferedPacket p = dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.pop_front();
1923 Channel* channel = &(dynamic_cast<UDPPeer*>(&peer)->channels[i]);
1924 LOG(dout_con<<m_connection->getDesc()
1925 <<" INFO: sending a queued reliable packet "
1927 <<", seqnum: " << readU16(&p.data[BASE_HEADER_SIZE+1])
1929 sendAsPacketReliable(p,channel);
1930 peer->m_increment_packets_remaining--;
1935 if (m_outgoing_queue.size())
1937 LOG(dout_con<<m_connection->getDesc()
1938 << " Handle non reliable queue ("
1939 << m_outgoing_queue.size() << " pkts)" << std::endl);
1942 unsigned int initial_queuesize = m_outgoing_queue.size();
1943 /* send non reliable packets*/
1944 for(unsigned int i=0;i < initial_queuesize;i++) {
1945 OutgoingPacket packet = m_outgoing_queue.pop_front();
1947 assert(!packet.reliable &&
1948 "reliable packets are not allowed in outgoing queue!");
1950 PeerHelper peer = m_connection->getPeerNoEx(packet.peer_id);
1952 LOG(dout_con<<m_connection->getDesc()
1953 <<" Outgoing queue: peer_id="<<packet.peer_id
1954 << ">>>NOT<<< found on sending packet"
1955 << ", channel " << (packet.channelnum % 0xFF)
1956 << ", size: " << packet.data.getSize() <<std::endl);
1959 /* send acks immediately */
1960 else if (packet.ack)
1962 rawSendAsPacket(packet.peer_id, packet.channelnum,
1963 packet.data, packet.reliable);
1964 peer->m_increment_packets_remaining =
1965 MYMIN(0,peer->m_increment_packets_remaining--);
1968 ( peer->m_increment_packets_remaining > 0) ||
1969 (StopRequested())) {
1970 rawSendAsPacket(packet.peer_id, packet.channelnum,
1971 packet.data, packet.reliable);
1972 peer->m_increment_packets_remaining--;
1975 m_outgoing_queue.push_back(packet);
1976 pending_unreliable[packet.peer_id] = true;
1980 for(std::list<u16>::iterator
1981 k = pendingDisconnect.begin();
1982 k != pendingDisconnect.end(); ++k)
1984 if (!pending_unreliable[*k])
1986 m_connection->deletePeer(*k,false);
1991 void ConnectionSendThread::sendAsPacket(u16 peer_id, u8 channelnum,
1992 SharedBuffer<u8> data, bool ack)
1994 OutgoingPacket packet(peer_id, channelnum, data, false, ack);
1995 m_outgoing_queue.push_back(packet);
1998 ConnectionReceiveThread::ConnectionReceiveThread(unsigned int max_packet_size) :
2003 void * ConnectionReceiveThread::Thread()
2005 assert(m_connection != NULL);
2007 log_register_thread("ConnectionReceive");
2009 LOG(dout_con<<m_connection->getDesc()
2010 <<"ConnectionReceive thread started"<<std::endl);
2012 PROFILE(std::stringstream ThreadIdentifier);
2013 PROFILE(ThreadIdentifier << "ConnectionReceive: [" << m_connection->getDesc() << "]");
2015 porting::setThreadName("ConnectionReceive");
2017 #ifdef DEBUG_CONNECTION_KBPS
2018 u32 curtime = porting::getTimeMs();
2019 u32 lasttime = curtime;
2020 float debug_print_timer = 0.0;
2023 while(!StopRequested()) {
2024 BEGIN_DEBUG_EXCEPTION_HANDLER
2025 PROFILE(ScopeProfiler sp(g_profiler, ThreadIdentifier.str(), SPT_AVG));
2027 #ifdef DEBUG_CONNECTION_KBPS
2029 curtime = porting::getTimeMs();
2030 float dtime = CALC_DTIME(lasttime,curtime);
2033 /* receive packets */
2036 #ifdef DEBUG_CONNECTION_KBPS
2037 debug_print_timer += dtime;
2038 if (debug_print_timer > 20.0) {
2039 debug_print_timer -= 20.0;
2041 std::list<u16> peerids = m_connection->getPeerIDs();
2043 for (std::list<u16>::iterator i = peerids.begin();
2047 PeerHelper peer = m_connection->getPeerNoEx(*i);
2051 float peer_current = 0.0;
2052 float peer_loss = 0.0;
2053 float avg_rate = 0.0;
2054 float avg_loss = 0.0;
2056 for(u16 j=0; j<CHANNEL_COUNT; j++)
2058 peer_current +=peer->channels[j].getCurrentDownloadRateKB();
2059 peer_loss += peer->channels[j].getCurrentLossRateKB();
2060 avg_rate += peer->channels[j].getAvgDownloadRateKB();
2061 avg_loss += peer->channels[j].getAvgLossRateKB();
2064 std::stringstream output;
2065 output << std::fixed << std::setprecision(1);
2066 output << "OUT to Peer " << *i << " RATES (good / loss) " << std::endl;
2067 output << "\tcurrent (sum): " << peer_current << "kb/s "<< peer_loss << "kb/s" << std::endl;
2068 output << "\taverage (sum): " << avg_rate << "kb/s "<< avg_loss << "kb/s" << std::endl;
2069 output << std::setfill(' ');
2070 for(u16 j=0; j<CHANNEL_COUNT; j++)
2072 output << "\tcha " << j << ":"
2073 << " CUR: " << std::setw(6) << peer->channels[j].getCurrentDownloadRateKB() <<"kb/s"
2074 << " AVG: " << std::setw(6) << peer->channels[j].getAvgDownloadRateKB() <<"kb/s"
2075 << " MAX: " << std::setw(6) << peer->channels[j].getMaxDownloadRateKB() <<"kb/s"
2077 << " CUR: " << std::setw(6) << peer->channels[j].getCurrentLossRateKB() <<"kb/s"
2078 << " AVG: " << std::setw(6) << peer->channels[j].getAvgLossRateKB() <<"kb/s"
2079 << " MAX: " << std::setw(6) << peer->channels[j].getMaxLossRateKB() <<"kb/s"
2080 << " / WS: " << peer->channels[j].getWindowSize()
2084 fprintf(stderr,"%s\n",output.str().c_str());
2088 END_DEBUG_EXCEPTION_HANDLER(errorstream);
2090 PROFILE(g_profiler->remove(ThreadIdentifier.str()));
2094 // Receive packets from the network and buffers and create ConnectionEvents
2095 void ConnectionReceiveThread::receive()
2097 // use IPv6 minimum allowed MTU as receive buffer size as this is
2098 // theoretical reliable upper boundary of a udp packet for all IPv6 enabled
2100 unsigned int packet_maxsize = 1500;
2101 SharedBuffer<u8> packetdata(packet_maxsize);
2103 bool packet_queued = true;
2105 unsigned int loop_count = 0;
2107 /* first of all read packets from socket */
2108 /* check for incoming data available */
2109 while( (loop_count < 10) &&
2110 (m_connection->m_udpSocket.WaitData(50))) {
2113 if (packet_queued) {
2114 bool data_left = true;
2116 SharedBuffer<u8> resultdata;
2119 data_left = getFromBuffers(peer_id, resultdata);
2122 e.dataReceived(peer_id, resultdata);
2123 m_connection->putEvent(e);
2126 catch(ProcessedSilentlyException &e) {
2127 /* try reading again */
2130 packet_queued = false;
2134 s32 received_size = m_connection->m_udpSocket.Receive(sender, *packetdata, packet_maxsize);
2136 if ((received_size < BASE_HEADER_SIZE) ||
2137 (readU32(&packetdata[0]) != m_connection->GetProtocolID()))
2139 LOG(derr_con<<m_connection->getDesc()
2140 <<"Receive(): Invalid incoming packet, "
2141 <<"size: " << received_size
2143 << ((received_size >= 4) ? readU32(&packetdata[0]) : -1)
2148 u16 peer_id = readPeerId(*packetdata);
2149 u8 channelnum = readChannel(*packetdata);
2151 if (channelnum > CHANNEL_COUNT-1) {
2152 LOG(derr_con<<m_connection->getDesc()
2153 <<"Receive(): Invalid channel "<<channelnum<<std::endl);
2154 throw InvalidIncomingDataException("Channel doesn't exist");
2157 /* preserve original peer_id for later usage */
2158 u16 packet_peer_id = peer_id;
2160 /* Try to identify peer by sender address (may happen on join) */
2161 if (peer_id == PEER_ID_INEXISTENT) {
2162 peer_id = m_connection->lookupPeer(sender);
2165 /* The peer was not found in our lists. Add it. */
2166 if (peer_id == PEER_ID_INEXISTENT) {
2167 peer_id = m_connection->createPeer(sender, MTP_MINETEST_RELIABLE_UDP, 0);
2170 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
2173 LOG(dout_con<<m_connection->getDesc()
2174 <<" got packet from unknown peer_id: "
2175 <<peer_id<<" Ignoring."<<std::endl);
2179 // Validate peer address
2181 Address peer_address;
2183 if (peer->getAddress(MTP_UDP, peer_address)) {
2184 if (peer_address != sender) {
2185 LOG(derr_con<<m_connection->getDesc()
2186 <<m_connection->getDesc()
2187 <<" Peer "<<peer_id<<" sending from different address."
2188 " Ignoring."<<std::endl);
2194 bool invalid_address = true;
2195 if (invalid_address) {
2196 LOG(derr_con<<m_connection->getDesc()
2197 <<m_connection->getDesc()
2198 <<" Peer "<<peer_id<<" unknown."
2199 " Ignoring."<<std::endl);
2205 /* mark peer as seen with id */
2206 if (!(packet_peer_id == PEER_ID_INEXISTENT))
2207 peer->setSentWithID();
2209 peer->ResetTimeout();
2211 Channel *channel = 0;
2213 if (dynamic_cast<UDPPeer*>(&peer) != 0)
2215 channel = &(dynamic_cast<UDPPeer*>(&peer)->channels[channelnum]);
2219 channel->UpdateBytesReceived(received_size);
2222 // Throw the received packet to channel->processPacket()
2224 // Make a new SharedBuffer from the data without the base headers
2225 SharedBuffer<u8> strippeddata(received_size - BASE_HEADER_SIZE);
2226 memcpy(*strippeddata, &packetdata[BASE_HEADER_SIZE],
2227 strippeddata.getSize());
2230 // Process it (the result is some data with no headers made by us)
2231 SharedBuffer<u8> resultdata = processPacket
2232 (channel, strippeddata, peer_id, channelnum, false);
2234 LOG(dout_con<<m_connection->getDesc()
2235 <<" ProcessPacket from peer_id: " << peer_id
2236 << ",channel: " << (channelnum & 0xFF) << ", returned "
2237 << resultdata.getSize() << " bytes" <<std::endl);
2240 e.dataReceived(peer_id, resultdata);
2241 m_connection->putEvent(e);
2243 catch(ProcessedSilentlyException &e) {
2245 catch(ProcessedQueued &e) {
2246 packet_queued = true;
2249 catch(InvalidIncomingDataException &e) {
2251 catch(ProcessedSilentlyException &e) {
2256 bool ConnectionReceiveThread::getFromBuffers(u16 &peer_id, SharedBuffer<u8> &dst)
2258 std::list<u16> peerids = m_connection->getPeerIDs();
2260 for(std::list<u16>::iterator j = peerids.begin();
2261 j != peerids.end(); ++j)
2263 PeerHelper peer = m_connection->getPeerNoEx(*j);
2267 if (dynamic_cast<UDPPeer*>(&peer) == 0)
2270 for(u16 i=0; i<CHANNEL_COUNT; i++)
2272 Channel *channel = &(dynamic_cast<UDPPeer*>(&peer))->channels[i];
2274 if (checkIncomingBuffers(channel, peer_id, dst)) {
2282 bool ConnectionReceiveThread::checkIncomingBuffers(Channel *channel,
2283 u16 &peer_id, SharedBuffer<u8> &dst)
2285 u16 firstseqnum = 0;
2286 if (channel->incoming_reliables.getFirstSeqnum(firstseqnum))
2288 if (firstseqnum == channel->readNextIncomingSeqNum())
2290 BufferedPacket p = channel->incoming_reliables.popFirst();
2291 peer_id = readPeerId(*p.data);
2292 u8 channelnum = readChannel(*p.data);
2293 u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]);
2295 LOG(dout_con<<m_connection->getDesc()
2296 <<"UNBUFFERING TYPE_RELIABLE"
2297 <<" seqnum="<<seqnum
2298 <<" peer_id="<<peer_id
2299 <<" channel="<<((int)channelnum&0xff)
2302 channel->incNextIncomingSeqNum();
2304 u32 headers_size = BASE_HEADER_SIZE + RELIABLE_HEADER_SIZE;
2305 // Get out the inside packet and re-process it
2306 SharedBuffer<u8> payload(p.data.getSize() - headers_size);
2307 memcpy(*payload, &p.data[headers_size], payload.getSize());
2309 dst = processPacket(channel, payload, peer_id, channelnum, true);
2316 SharedBuffer<u8> ConnectionReceiveThread::processPacket(Channel *channel,
2317 SharedBuffer<u8> packetdata, u16 peer_id, u8 channelnum, bool reliable)
2319 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
2322 errorstream << "Peer not found (possible timeout)" << std::endl;
2323 throw ProcessedSilentlyException("Peer not found (possible timeout)");
2326 if (packetdata.getSize() < 1)
2327 throw InvalidIncomingDataException("packetdata.getSize() < 1");
2329 u8 type = readU8(&(packetdata[0]));
2331 if (MAX_UDP_PEERS <= 65535 && peer_id >= MAX_UDP_PEERS) {
2332 errorstream << "Something is wrong with peer_id" << std::endl;
2336 if (type == TYPE_CONTROL)
2338 if (packetdata.getSize() < 2)
2339 throw InvalidIncomingDataException("packetdata.getSize() < 2");
2341 u8 controltype = readU8(&(packetdata[1]));
2343 if (controltype == CONTROLTYPE_ACK)
2345 assert(channel != 0);
2346 if (packetdata.getSize() < 4)
2347 throw InvalidIncomingDataException
2348 ("packetdata.getSize() < 4 (ACK header size)");
2350 u16 seqnum = readU16(&packetdata[2]);
2351 LOG(dout_con<<m_connection->getDesc()
2352 <<" [ CONTROLTYPE_ACK: channelnum="
2353 <<((int)channelnum&0xff)<<", peer_id="<<peer_id
2354 <<", seqnum="<<seqnum<< " ]"<<std::endl);
2358 channel->outgoing_reliables_sent.popSeqnum(seqnum);
2360 // only calculate rtt from straight sent packets
2361 if (p.resend_count == 0) {
2362 // Get round trip time
2363 unsigned int current_time = porting::getTimeMs();
2365 // a overflow is quite unlikely but as it'd result in major
2366 // rtt miscalculation we handle it here
2367 if (current_time > p.absolute_send_time)
2369 float rtt = (current_time - p.absolute_send_time) / 1000.0;
2371 // Let peer calculate stuff according to it
2372 // (avg_rtt and resend_timeout)
2373 dynamic_cast<UDPPeer*>(&peer)->reportRTT(rtt);
2375 else if (p.totaltime > 0)
2377 float rtt = p.totaltime;
2379 // Let peer calculate stuff according to it
2380 // (avg_rtt and resend_timeout)
2381 dynamic_cast<UDPPeer*>(&peer)->reportRTT(rtt);
2384 //put bytes for max bandwidth calculation
2385 channel->UpdateBytesSent(p.data.getSize(),1);
2386 if (channel->outgoing_reliables_sent.size() == 0)
2388 m_connection->TriggerSend();
2391 catch(NotFoundException &e) {
2392 LOG(derr_con<<m_connection->getDesc()
2393 <<"WARNING: ACKed packet not "
2396 channel->UpdatePacketTooLateCounter();
2398 throw ProcessedSilentlyException("Got an ACK");
2400 else if (controltype == CONTROLTYPE_SET_PEER_ID) {
2401 // Got a packet to set our peer id
2402 if (packetdata.getSize() < 4)
2403 throw InvalidIncomingDataException
2404 ("packetdata.getSize() < 4 (SET_PEER_ID header size)");
2405 u16 peer_id_new = readU16(&packetdata[2]);
2406 LOG(dout_con<<m_connection->getDesc()
2407 <<"Got new peer id: "<<peer_id_new<<"... "<<std::endl);
2409 if (m_connection->GetPeerID() != PEER_ID_INEXISTENT)
2411 LOG(derr_con<<m_connection->getDesc()
2412 <<"WARNING: Not changing"
2413 " existing peer id."<<std::endl);
2417 LOG(dout_con<<m_connection->getDesc()<<"changing own peer id"<<std::endl);
2418 m_connection->SetPeerID(peer_id_new);
2421 ConnectionCommand cmd;
2423 SharedBuffer<u8> reply(2);
2424 writeU8(&reply[0], TYPE_CONTROL);
2425 writeU8(&reply[1], CONTROLTYPE_ENABLE_BIG_SEND_WINDOW);
2426 cmd.disableLegacy(PEER_ID_SERVER,reply);
2427 m_connection->putCommand(cmd);
2429 throw ProcessedSilentlyException("Got a SET_PEER_ID");
2431 else if (controltype == CONTROLTYPE_PING)
2433 // Just ignore it, the incoming data already reset
2434 // the timeout counter
2435 LOG(dout_con<<m_connection->getDesc()<<"PING"<<std::endl);
2436 throw ProcessedSilentlyException("Got a PING");
2438 else if (controltype == CONTROLTYPE_DISCO)
2440 // Just ignore it, the incoming data already reset
2441 // the timeout counter
2442 LOG(dout_con<<m_connection->getDesc()
2443 <<"DISCO: Removing peer "<<(peer_id)<<std::endl);
2445 if (m_connection->deletePeer(peer_id, false) == false)
2447 derr_con<<m_connection->getDesc()
2448 <<"DISCO: Peer not found"<<std::endl;
2451 throw ProcessedSilentlyException("Got a DISCO");
2453 else if (controltype == CONTROLTYPE_ENABLE_BIG_SEND_WINDOW)
2455 dynamic_cast<UDPPeer*>(&peer)->setNonLegacyPeer();
2456 throw ProcessedSilentlyException("Got non legacy control");
2459 LOG(derr_con<<m_connection->getDesc()
2460 <<"INVALID TYPE_CONTROL: invalid controltype="
2461 <<((int)controltype&0xff)<<std::endl);
2462 throw InvalidIncomingDataException("Invalid control type");
2465 else if (type == TYPE_ORIGINAL)
2467 if (packetdata.getSize() <= ORIGINAL_HEADER_SIZE)
2468 throw InvalidIncomingDataException
2469 ("packetdata.getSize() <= ORIGINAL_HEADER_SIZE");
2470 LOG(dout_con<<m_connection->getDesc()
2471 <<"RETURNING TYPE_ORIGINAL to user"
2473 // Get the inside packet out and return it
2474 SharedBuffer<u8> payload(packetdata.getSize() - ORIGINAL_HEADER_SIZE);
2475 memcpy(*payload, &(packetdata[ORIGINAL_HEADER_SIZE]), payload.getSize());
2478 else if (type == TYPE_SPLIT)
2480 Address peer_address;
2482 if (peer->getAddress(MTP_UDP, peer_address)) {
2484 // We have to create a packet again for buffering
2485 // This isn't actually too bad an idea.
2486 BufferedPacket packet = makePacket(
2489 m_connection->GetProtocolID(),
2493 // Buffer the packet
2494 SharedBuffer<u8> data =
2495 peer->addSpiltPacket(channelnum,packet,reliable);
2497 if (data.getSize() != 0)
2499 LOG(dout_con<<m_connection->getDesc()
2500 <<"RETURNING TYPE_SPLIT: Constructed full data, "
2501 <<"size="<<data.getSize()<<std::endl);
2504 LOG(dout_con<<m_connection->getDesc()<<"BUFFERED TYPE_SPLIT"<<std::endl);
2505 throw ProcessedSilentlyException("Buffered a split packet chunk");
2508 //TODO throw some error
2511 else if (type == TYPE_RELIABLE)
2513 assert(channel != 0);
2514 // Recursive reliable packets not allowed
2516 throw InvalidIncomingDataException("Found nested reliable packets");
2518 if (packetdata.getSize() < RELIABLE_HEADER_SIZE)
2519 throw InvalidIncomingDataException
2520 ("packetdata.getSize() < RELIABLE_HEADER_SIZE");
2522 u16 seqnum = readU16(&packetdata[1]);
2523 bool is_future_packet = false;
2524 bool is_old_packet = false;
2526 /* packet is within our receive window send ack */
2527 if (seqnum_in_window(seqnum, channel->readNextIncomingSeqNum(),MAX_RELIABLE_WINDOW_SIZE))
2529 m_connection->sendAck(peer_id,channelnum,seqnum);
2532 is_future_packet = seqnum_higher(seqnum, channel->readNextIncomingSeqNum());
2533 is_old_packet = seqnum_higher(channel->readNextIncomingSeqNum(), seqnum);
2536 /* packet is not within receive window, don't send ack. *
2537 * if this was a valid packet it's gonna be retransmitted */
2538 if (is_future_packet)
2540 throw ProcessedSilentlyException("Received packet newer then expected, not sending ack");
2543 /* seems like our ack was lost, send another one for a old packet */
2546 LOG(dout_con<<m_connection->getDesc()
2547 << "RE-SENDING ACK: peer_id: " << peer_id
2548 << ", channel: " << (channelnum&0xFF)
2549 << ", seqnum: " << seqnum << std::endl;)
2550 m_connection->sendAck(peer_id,channelnum,seqnum);
2552 // we already have this packet so this one was on wire at least
2553 // the current timeout
2554 // we don't know how long this packet was on wire don't do silly guessing
2555 // dynamic_cast<UDPPeer*>(&peer)->reportRTT(dynamic_cast<UDPPeer*>(&peer)->getResendTimeout());
2557 throw ProcessedSilentlyException("Retransmitting ack for old packet");
2561 if (seqnum != channel->readNextIncomingSeqNum())
2563 Address peer_address;
2565 // this is a reliable packet so we have a udp address for sure
2566 peer->getAddress(MTP_MINETEST_RELIABLE_UDP, peer_address);
2567 // This one comes later, buffer it.
2568 // Actually we have to make a packet to buffer one.
2569 // Well, we have all the ingredients, so just do it.
2570 BufferedPacket packet = con::makePacket(
2573 m_connection->GetProtocolID(),
2577 channel->incoming_reliables.insert(packet,channel->readNextIncomingSeqNum());
2579 LOG(dout_con<<m_connection->getDesc()
2580 << "BUFFERING, TYPE_RELIABLE peer_id: " << peer_id
2581 << ", channel: " << (channelnum&0xFF)
2582 << ", seqnum: " << seqnum << std::endl;)
2584 throw ProcessedQueued("Buffered future reliable packet");
2586 catch(AlreadyExistsException &e)
2589 catch(IncomingDataCorruption &e)
2591 ConnectionCommand discon;
2592 discon.disconnect_peer(peer_id);
2593 m_connection->putCommand(discon);
2595 LOG(derr_con<<m_connection->getDesc()
2596 << "INVALID, TYPE_RELIABLE peer_id: " << peer_id
2597 << ", channel: " << (channelnum&0xFF)
2598 << ", seqnum: " << seqnum
2599 << "DROPPING CLIENT!" << std::endl;)
2603 /* we got a packet to process right now */
2604 LOG(dout_con<<m_connection->getDesc()
2605 << "RECURSIVE, TYPE_RELIABLE peer_id: " << peer_id
2606 << ", channel: " << (channelnum&0xFF)
2607 << ", seqnum: " << seqnum << std::endl;)
2610 /* check for resend case */
2611 u16 queued_seqnum = 0;
2612 if (channel->incoming_reliables.getFirstSeqnum(queued_seqnum))
2614 if (queued_seqnum == seqnum)
2616 BufferedPacket queued_packet = channel->incoming_reliables.popFirst();
2617 /** TODO find a way to verify the new against the old packet */
2621 channel->incNextIncomingSeqNum();
2623 // Get out the inside packet and re-process it
2624 SharedBuffer<u8> payload(packetdata.getSize() - RELIABLE_HEADER_SIZE);
2625 memcpy(*payload, &packetdata[RELIABLE_HEADER_SIZE], payload.getSize());
2627 return processPacket(channel, payload, peer_id, channelnum, true);
2631 derr_con<<m_connection->getDesc()
2632 <<"Got invalid type="<<((int)type&0xff)<<std::endl;
2633 throw InvalidIncomingDataException("Invalid packet type");
2636 // We should never get here.
2637 // If you get here, add an exception or a return to some of the
2638 // above conditionals.
2640 throw BaseException("Error in Channel::ProcessPacket()");
2647 Connection::Connection(u32 protocol_id, u32 max_packet_size, float timeout,
2653 m_protocol_id(protocol_id),
2654 m_sendThread(max_packet_size, timeout),
2655 m_receiveThread(max_packet_size),
2657 m_bc_peerhandler(0),
2658 m_bc_receive_timeout(0),
2659 m_shutting_down(false),
2660 m_next_remote_peer_id(2)
2662 m_udpSocket.setTimeoutMs(5);
2664 m_sendThread.setParent(this);
2665 m_receiveThread.setParent(this);
2667 m_sendThread.Start();
2668 m_receiveThread.Start();
2671 Connection::Connection(u32 protocol_id, u32 max_packet_size, float timeout,
2672 bool ipv6, PeerHandler *peerhandler) :
2677 m_protocol_id(protocol_id),
2678 m_sendThread(max_packet_size, timeout),
2679 m_receiveThread(max_packet_size),
2681 m_bc_peerhandler(peerhandler),
2682 m_bc_receive_timeout(0),
2683 m_shutting_down(false),
2684 m_next_remote_peer_id(2)
2687 m_udpSocket.setTimeoutMs(5);
2689 m_sendThread.setParent(this);
2690 m_receiveThread.setParent(this);
2692 m_sendThread.Start();
2693 m_receiveThread.Start();
2698 Connection::~Connection()
2700 m_shutting_down = true;
2701 // request threads to stop
2702 m_sendThread.Stop();
2703 m_receiveThread.Stop();
2705 //TODO for some unkonwn reason send/receive threads do not exit as they're
2706 // supposed to be but wait on peer timeout. To speed up shutdown we reduce
2707 // timeout to half a second.
2708 m_sendThread.setPeerTimeout(0.5);
2710 // wait for threads to finish
2711 m_sendThread.Wait();
2712 m_receiveThread.Wait();
2715 for(std::map<u16, Peer*>::iterator
2716 j = m_peers.begin();
2717 j != m_peers.end(); ++j)
2723 /* Internal stuff */
2724 void Connection::putEvent(ConnectionEvent &e)
2726 assert(e.type != CONNEVENT_NONE);
2727 m_event_queue.push_back(e);
2730 PeerHelper Connection::getPeer(u16 peer_id)
2732 JMutexAutoLock peerlock(m_peers_mutex);
2733 std::map<u16, Peer*>::iterator node = m_peers.find(peer_id);
2735 if (node == m_peers.end()) {
2736 throw PeerNotFoundException("GetPeer: Peer not found (possible timeout)");
2740 assert(node->second->id == peer_id);
2742 return PeerHelper(node->second);
2745 PeerHelper Connection::getPeerNoEx(u16 peer_id)
2747 JMutexAutoLock peerlock(m_peers_mutex);
2748 std::map<u16, Peer*>::iterator node = m_peers.find(peer_id);
2750 if (node == m_peers.end()) {
2751 return PeerHelper(NULL);
2755 assert(node->second->id == peer_id);
2757 return PeerHelper(node->second);
2760 /* find peer_id for address */
2761 u16 Connection::lookupPeer(Address& sender)
2763 JMutexAutoLock peerlock(m_peers_mutex);
2764 std::map<u16, Peer*>::iterator j;
2765 j = m_peers.begin();
2766 for(; j != m_peers.end(); ++j)
2768 Peer *peer = j->second;
2769 if (peer->isActive())
2774 if ((peer->getAddress(MTP_MINETEST_RELIABLE_UDP, tocheck)) && (tocheck == sender))
2777 if ((peer->getAddress(MTP_UDP, tocheck)) && (tocheck == sender))
2781 return PEER_ID_INEXISTENT;
2784 std::list<Peer*> Connection::getPeers()
2786 std::list<Peer*> list;
2787 for(std::map<u16, Peer*>::iterator j = m_peers.begin();
2788 j != m_peers.end(); ++j)
2790 Peer *peer = j->second;
2791 list.push_back(peer);
2796 bool Connection::deletePeer(u16 peer_id, bool timeout)
2800 /* lock list as short as possible */
2802 JMutexAutoLock peerlock(m_peers_mutex);
2803 if (m_peers.find(peer_id) == m_peers.end())
2805 peer = m_peers[peer_id];
2806 m_peers.erase(peer_id);
2807 m_peer_ids.remove(peer_id);
2810 Address peer_address;
2811 //any peer has a primary address this never fails!
2812 peer->getAddress(MTP_PRIMARY, peer_address);
2815 e.peerRemoved(peer_id, timeout, peer_address);
2825 ConnectionEvent Connection::getEvent()
2827 if (m_event_queue.empty()) {
2829 e.type = CONNEVENT_NONE;
2832 return m_event_queue.pop_frontNoEx();
2835 ConnectionEvent Connection::waitEvent(u32 timeout_ms)
2838 return m_event_queue.pop_front(timeout_ms);
2839 } catch(ItemNotFoundException &ex) {
2841 e.type = CONNEVENT_NONE;
2846 void Connection::putCommand(ConnectionCommand &c)
2848 if (!m_shutting_down) {
2849 m_command_queue.push_back(c);
2850 m_sendThread.Trigger();
2854 void Connection::Serve(Address bind_addr)
2856 ConnectionCommand c;
2861 void Connection::Connect(Address address)
2863 ConnectionCommand c;
2868 bool Connection::Connected()
2870 JMutexAutoLock peerlock(m_peers_mutex);
2872 if (m_peers.size() != 1)
2875 std::map<u16, Peer*>::iterator node = m_peers.find(PEER_ID_SERVER);
2876 if (node == m_peers.end())
2879 if (m_peer_id == PEER_ID_INEXISTENT)
2885 void Connection::Disconnect()
2887 ConnectionCommand c;
2892 u32 Connection::Receive(u16 &peer_id, SharedBuffer<u8> &data)
2895 ConnectionEvent e = waitEvent(m_bc_receive_timeout);
2896 if (e.type != CONNEVENT_NONE)
2897 LOG(dout_con<<getDesc()<<": Receive: got event: "
2898 <<e.describe()<<std::endl);
2900 case CONNEVENT_NONE:
2901 throw NoIncomingDataException("No incoming data");
2902 case CONNEVENT_DATA_RECEIVED:
2903 peer_id = e.peer_id;
2904 data = SharedBuffer<u8>(e.data);
2905 return e.data.getSize();
2906 case CONNEVENT_PEER_ADDED: {
2907 UDPPeer tmp(e.peer_id, e.address, this);
2908 if (m_bc_peerhandler)
2909 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);
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);
2929 ConnectionCommand c;
2931 c.send(peer_id, channelnum, pkt->oldForgePacket(), 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);
2958 assert("Connection::getLocalStat we couldn't get our own peer? are you serious???" == 0);
2963 for (u16 j=0; j<CHANNEL_COUNT; j++) {
2966 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getCurrentDownloadRateKB();
2969 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getAvgDownloadRateKB();
2972 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getCurrentIncomingRateKB();
2975 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getAvgIncomingRateKB();
2978 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getAvgLossRateKB();
2981 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getCurrentLossRateKB();
2984 assert("Connection::getLocalStat Invalid stat type" == 0);
2990 u16 Connection::createPeer(Address& sender, MTProtocols protocol, int fd)
2992 // Somebody wants to make a new connection
2994 // Get a unique peer id (2 or higher)
2995 u16 peer_id_new = m_next_remote_peer_id;
2996 u16 overflow = MAX_UDP_PEERS;
2999 Find an unused peer id
3001 JMutexAutoLock lock(m_peers_mutex);
3002 bool out_of_ids = false;
3005 if (m_peers.find(peer_id_new) == m_peers.end())
3008 // Check for overflow
3009 if (peer_id_new == overflow) {
3017 errorstream << getDesc() << " ran out of peer ids" << std::endl;
3018 return PEER_ID_INEXISTENT;
3023 peer = new UDPPeer(peer_id_new, sender, this);
3025 m_peers[peer->id] = peer;
3026 m_peer_ids.push_back(peer->id);
3028 m_next_remote_peer_id = (peer_id_new +1 ) % MAX_UDP_PEERS;
3030 LOG(dout_con << getDesc()
3031 << "createPeer(): giving peer_id=" << peer_id_new << std::endl);
3033 ConnectionCommand cmd;
3034 SharedBuffer<u8> reply(4);
3035 writeU8(&reply[0], TYPE_CONTROL);
3036 writeU8(&reply[1], CONTROLTYPE_SET_PEER_ID);
3037 writeU16(&reply[2], peer_id_new);
3038 cmd.createPeer(peer_id_new,reply);
3041 // Create peer addition event
3043 e.peerAdded(peer_id_new, sender);
3046 // We're now talking to a valid peer_id
3050 void Connection::PrintInfo(std::ostream &out)
3052 m_info_mutex.Lock();
3053 out<<getDesc()<<": ";
3054 m_info_mutex.Unlock();
3057 void Connection::PrintInfo()
3059 PrintInfo(dout_con);
3062 const std::string Connection::getDesc()
3064 return std::string("con(")+
3065 itos(m_udpSocket.GetHandle())+"/"+itos(m_peer_id)+")";
3068 void Connection::DisconnectPeer(u16 peer_id)
3070 ConnectionCommand discon;
3071 discon.disconnect_peer(peer_id);
3075 void Connection::sendAck(u16 peer_id, u8 channelnum, u16 seqnum)
3077 assert(channelnum < CHANNEL_COUNT);
3079 LOG(dout_con<<getDesc()
3080 <<" Queuing ACK command to peer_id: " << peer_id <<
3081 " channel: " << (channelnum & 0xFF) <<
3082 " seqnum: " << seqnum << std::endl);
3084 ConnectionCommand c;
3085 SharedBuffer<u8> ack(4);
3086 writeU8(&ack[0], TYPE_CONTROL);
3087 writeU8(&ack[1], CONTROLTYPE_ACK);
3088 writeU16(&ack[2], seqnum);
3090 c.ack(peer_id, channelnum, ack);
3092 m_sendThread.Trigger();
3095 UDPPeer* Connection::createServerPeer(Address& address)
3097 if (getPeerNoEx(PEER_ID_SERVER) != 0)
3099 throw ConnectionException("Already connected to a server");
3102 UDPPeer *peer = new UDPPeer(PEER_ID_SERVER, address, this);
3105 JMutexAutoLock lock(m_peers_mutex);
3106 m_peers[peer->id] = peer;
3107 m_peer_ids.push_back(peer->id);