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"
32 #include "main.h" // for profiling
37 /******************************************************************************/
38 /* defines used for debugging and profiling */
39 /******************************************************************************/
43 #undef DEBUG_CONNECTION_KBPS
45 /* this mutex is used to achieve log message consistency */
46 JMutex log_message_mutex;
49 JMutexAutoLock loglock(log_message_mutex); \
53 //#define DEBUG_CONNECTION_KBPS
54 #undef DEBUG_CONNECTION_KBPS
58 static inline float CALC_DTIME(unsigned int lasttime, unsigned int curtime) {
59 float value = ( curtime - lasttime) / 1000.0;
60 return MYMAX(MYMIN(value,0.1),0.0);
63 /* maximum window size to use, 0xFFFF is theoretical maximum don't think about
64 * touching it, the less you're away from it the more likely data corruption
67 #define MAX_RELIABLE_WINDOW_SIZE 0x8000
68 /* starting value for window size */
69 #define MIN_RELIABLE_WINDOW_SIZE 0x40
71 #define MAX_UDP_PEERS 65535
73 #define PING_TIMEOUT 5.0
75 static u16 readPeerId(u8 *packetdata)
77 return readU16(&packetdata[4]);
79 static u8 readChannel(u8 *packetdata)
81 return readU8(&packetdata[6]);
84 BufferedPacket makePacket(Address &address, u8 *data, u32 datasize,
85 u32 protocol_id, u16 sender_peer_id, u8 channel)
87 u32 packet_size = datasize + BASE_HEADER_SIZE;
88 BufferedPacket p(packet_size);
91 writeU32(&p.data[0], protocol_id);
92 writeU16(&p.data[4], sender_peer_id);
93 writeU8(&p.data[6], channel);
95 memcpy(&p.data[BASE_HEADER_SIZE], data, datasize);
100 BufferedPacket makePacket(Address &address, SharedBuffer<u8> &data,
101 u32 protocol_id, u16 sender_peer_id, u8 channel)
103 return makePacket(address, *data, data.getSize(),
104 protocol_id, sender_peer_id, channel);
107 SharedBuffer<u8> makeOriginalPacket(
108 SharedBuffer<u8> data)
111 u32 packet_size = data.getSize() + header_size;
112 SharedBuffer<u8> b(packet_size);
114 writeU8(&(b[0]), TYPE_ORIGINAL);
115 if (data.getSize() > 0) {
116 memcpy(&(b[header_size]), *data, data.getSize());
121 std::list<SharedBuffer<u8> > makeSplitPacket(
122 SharedBuffer<u8> data,
126 // Chunk packets, containing the TYPE_SPLIT header
127 std::list<SharedBuffer<u8> > chunks;
129 u32 chunk_header_size = 7;
130 u32 maximum_data_size = chunksize_max - chunk_header_size;
136 end = start + maximum_data_size - 1;
137 if(end > data.getSize() - 1)
138 end = data.getSize() - 1;
140 u32 payload_size = end - start + 1;
141 u32 packet_size = chunk_header_size + payload_size;
143 SharedBuffer<u8> chunk(packet_size);
145 writeU8(&chunk[0], TYPE_SPLIT);
146 writeU16(&chunk[1], seqnum);
147 // [3] u16 chunk_count is written at next stage
148 writeU16(&chunk[5], chunk_num);
149 memcpy(&chunk[chunk_header_size], &data[start], payload_size);
151 chunks.push_back(chunk);
157 while(end != data.getSize() - 1);
159 for(std::list<SharedBuffer<u8> >::iterator i = chunks.begin();
160 i != chunks.end(); ++i)
163 writeU16(&((*i)[3]), chunk_count);
169 std::list<SharedBuffer<u8> > makeAutoSplitPacket(
170 SharedBuffer<u8> data,
174 u32 original_header_size = 1;
175 std::list<SharedBuffer<u8> > list;
176 if(data.getSize() + original_header_size > chunksize_max)
178 list = makeSplitPacket(data, chunksize_max, split_seqnum);
184 list.push_back(makeOriginalPacket(data));
189 SharedBuffer<u8> makeReliablePacket(
190 SharedBuffer<u8> data,
194 u32 packet_size = data.getSize() + header_size;
195 SharedBuffer<u8> b(packet_size);
197 writeU8(&b[0], TYPE_RELIABLE);
198 writeU16(&b[1], seqnum);
200 memcpy(&b[header_size], *data, data.getSize());
209 ReliablePacketBuffer::ReliablePacketBuffer(): m_list_size(0) {}
211 void ReliablePacketBuffer::print()
213 JMutexAutoLock listlock(m_list_mutex);
214 LOG(dout_con<<"Dump of ReliablePacketBuffer:" << std::endl);
215 unsigned int index = 0;
216 for(std::list<BufferedPacket>::iterator i = m_list.begin();
220 u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
221 LOG(dout_con<<index<< ":" << s << std::endl);
225 bool ReliablePacketBuffer::empty()
227 JMutexAutoLock listlock(m_list_mutex);
228 return m_list.empty();
231 u32 ReliablePacketBuffer::size()
236 bool ReliablePacketBuffer::containsPacket(u16 seqnum)
238 return !(findPacket(seqnum) == m_list.end());
241 RPBSearchResult ReliablePacketBuffer::findPacket(u16 seqnum)
243 std::list<BufferedPacket>::iterator i = m_list.begin();
244 for(; i != m_list.end(); ++i)
246 u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
247 /*dout_con<<"findPacket(): finding seqnum="<<seqnum
248 <<", comparing to s="<<s<<std::endl;*/
254 RPBSearchResult ReliablePacketBuffer::notFound()
258 bool ReliablePacketBuffer::getFirstSeqnum(u16& result)
260 JMutexAutoLock listlock(m_list_mutex);
263 BufferedPacket p = *m_list.begin();
264 result = readU16(&p.data[BASE_HEADER_SIZE+1]);
268 BufferedPacket ReliablePacketBuffer::popFirst()
270 JMutexAutoLock listlock(m_list_mutex);
272 throw NotFoundException("Buffer is empty");
273 BufferedPacket p = *m_list.begin();
274 m_list.erase(m_list.begin());
277 if (m_list_size == 0) {
278 m_oldest_non_answered_ack = 0;
280 m_oldest_non_answered_ack =
281 readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]);
285 BufferedPacket ReliablePacketBuffer::popSeqnum(u16 seqnum)
287 JMutexAutoLock listlock(m_list_mutex);
288 RPBSearchResult r = findPacket(seqnum);
290 LOG(dout_con<<"Sequence number: " << seqnum
291 << " not found in reliable buffer"<<std::endl);
292 throw NotFoundException("seqnum not found in buffer");
294 BufferedPacket p = *r;
297 RPBSearchResult next = r;
299 if (next != notFound()) {
300 u16 s = readU16(&(next->data[BASE_HEADER_SIZE+1]));
301 m_oldest_non_answered_ack = s;
307 if (m_list_size == 0)
308 { m_oldest_non_answered_ack = 0; }
310 { m_oldest_non_answered_ack = readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]); }
313 void ReliablePacketBuffer::insert(BufferedPacket &p,u16 next_expected)
315 JMutexAutoLock listlock(m_list_mutex);
316 assert(p.data.getSize() >= BASE_HEADER_SIZE+3);
317 u8 type = readU8(&p.data[BASE_HEADER_SIZE+0]);
318 assert(type == TYPE_RELIABLE);
319 u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]);
321 assert(seqnum_in_window(seqnum,next_expected,MAX_RELIABLE_WINDOW_SIZE));
322 assert(seqnum != next_expected);
325 assert(m_list_size <= SEQNUM_MAX+1);
327 // Find the right place for the packet and insert it there
328 // If list is empty, just add it
332 m_oldest_non_answered_ack = seqnum;
337 // Otherwise find the right place
338 std::list<BufferedPacket>::iterator i = m_list.begin();
339 // Find the first packet in the list which has a higher seqnum
340 u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
342 /* case seqnum is smaller then next_expected seqnum */
343 /* this is true e.g. on wrap around */
344 if (seqnum < next_expected) {
345 while(((s < seqnum) || (s >= next_expected)) && (i != m_list.end())) {
347 if (i != m_list.end())
348 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
351 /* non wrap around case (at least for incoming and next_expected */
354 while(((s < seqnum) && (s >= next_expected)) && (i != m_list.end())) {
356 if (i != m_list.end())
357 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
363 (readU16(&(i->data[BASE_HEADER_SIZE+1])) != seqnum) ||
364 (i->data.getSize() != p.data.getSize()) ||
365 (i->address != p.address)
368 /* if this happens your maximum transfer window may be to big */
370 "Duplicated seqnum %d non matching packet detected:\n",
372 fprintf(stderr, "Old: seqnum: %05d size: %04d, address: %s\n",
373 readU16(&(i->data[BASE_HEADER_SIZE+1])),i->data.getSize(),
374 i->address.serializeString().c_str());
375 fprintf(stderr, "New: seqnum: %05d size: %04d, address: %s\n",
376 readU16(&(p.data[BASE_HEADER_SIZE+1])),p.data.getSize(),
377 p.address.serializeString().c_str());
378 throw IncomingDataCorruption("duplicated packet isn't same as original one");
381 assert(readU16(&(i->data[BASE_HEADER_SIZE+1])) == seqnum);
382 assert(i->data.getSize() == p.data.getSize());
383 assert(i->address == p.address);
385 /* nothing to do this seems to be a resent packet */
386 /* for paranoia reason data should be compared */
389 /* insert or push back */
390 else if (i != m_list.end()) {
397 /* update last packet number */
398 m_oldest_non_answered_ack = readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]);
401 void ReliablePacketBuffer::incrementTimeouts(float dtime)
403 JMutexAutoLock listlock(m_list_mutex);
404 for(std::list<BufferedPacket>::iterator i = m_list.begin();
405 i != m_list.end(); ++i)
408 i->totaltime += dtime;
412 std::list<BufferedPacket> ReliablePacketBuffer::getTimedOuts(float timeout,
413 unsigned int max_packets)
415 JMutexAutoLock listlock(m_list_mutex);
416 std::list<BufferedPacket> timed_outs;
417 for(std::list<BufferedPacket>::iterator i = m_list.begin();
418 i != m_list.end(); ++i)
420 if(i->time >= timeout) {
421 timed_outs.push_back(*i);
423 //this packet will be sent right afterwards reset timeout here
425 if (timed_outs.size() >= max_packets)
436 IncomingSplitBuffer::~IncomingSplitBuffer()
438 JMutexAutoLock listlock(m_map_mutex);
439 for(std::map<u16, IncomingSplitPacket*>::iterator i = m_buf.begin();
440 i != m_buf.end(); ++i)
446 This will throw a GotSplitPacketException when a full
447 split packet is constructed.
449 SharedBuffer<u8> IncomingSplitBuffer::insert(BufferedPacket &p, bool reliable)
451 JMutexAutoLock listlock(m_map_mutex);
452 u32 headersize = BASE_HEADER_SIZE + 7;
453 assert(p.data.getSize() >= headersize);
454 u8 type = readU8(&p.data[BASE_HEADER_SIZE+0]);
455 assert(type == TYPE_SPLIT);
456 u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]);
457 u16 chunk_count = readU16(&p.data[BASE_HEADER_SIZE+3]);
458 u16 chunk_num = readU16(&p.data[BASE_HEADER_SIZE+5]);
460 // Add if doesn't exist
461 if(m_buf.find(seqnum) == m_buf.end())
463 IncomingSplitPacket *sp = new IncomingSplitPacket();
464 sp->chunk_count = chunk_count;
465 sp->reliable = reliable;
469 IncomingSplitPacket *sp = m_buf[seqnum];
471 // TODO: These errors should be thrown or something? Dunno.
472 if(chunk_count != sp->chunk_count)
473 LOG(derr_con<<"Connection: WARNING: chunk_count="<<chunk_count
474 <<" != sp->chunk_count="<<sp->chunk_count
476 if(reliable != sp->reliable)
477 LOG(derr_con<<"Connection: WARNING: reliable="<<reliable
478 <<" != sp->reliable="<<sp->reliable
481 // If chunk already exists, ignore it.
482 // Sometimes two identical packets may arrive when there is network
483 // lag and the server re-sends stuff.
484 if(sp->chunks.find(chunk_num) != sp->chunks.end())
485 return SharedBuffer<u8>();
487 // Cut chunk data out of packet
488 u32 chunkdatasize = p.data.getSize() - headersize;
489 SharedBuffer<u8> chunkdata(chunkdatasize);
490 memcpy(*chunkdata, &(p.data[headersize]), chunkdatasize);
492 // Set chunk data in buffer
493 sp->chunks[chunk_num] = chunkdata;
495 // If not all chunks are received, return empty buffer
496 if(sp->allReceived() == false)
497 return SharedBuffer<u8>();
499 // Calculate total size
501 for(std::map<u16, SharedBuffer<u8> >::iterator i = sp->chunks.begin();
502 i != sp->chunks.end(); ++i)
504 totalsize += i->second.getSize();
507 SharedBuffer<u8> fulldata(totalsize);
509 // Copy chunks to data buffer
511 for(u32 chunk_i=0; chunk_i<sp->chunk_count;
514 SharedBuffer<u8> buf = sp->chunks[chunk_i];
515 u16 chunkdatasize = buf.getSize();
516 memcpy(&fulldata[start], *buf, chunkdatasize);
517 start += chunkdatasize;;
520 // Remove sp from buffer
526 void IncomingSplitBuffer::removeUnreliableTimedOuts(float dtime, float timeout)
528 std::list<u16> remove_queue;
530 JMutexAutoLock listlock(m_map_mutex);
531 for(std::map<u16, IncomingSplitPacket*>::iterator i = m_buf.begin();
532 i != m_buf.end(); ++i)
534 IncomingSplitPacket *p = i->second;
535 // Reliable ones are not removed by timeout
536 if(p->reliable == true)
539 if(p->time >= timeout)
540 remove_queue.push_back(i->first);
543 for(std::list<u16>::iterator j = remove_queue.begin();
544 j != remove_queue.end(); ++j)
546 JMutexAutoLock listlock(m_map_mutex);
547 LOG(dout_con<<"NOTE: Removing timed out unreliable split packet"<<std::endl);
558 window_size(MIN_RELIABLE_WINDOW_SIZE),
559 next_incoming_seqnum(SEQNUM_INITIAL),
560 next_outgoing_seqnum(SEQNUM_INITIAL),
561 next_outgoing_split_seqnum(SEQNUM_INITIAL),
562 current_packet_loss(0),
563 current_packet_too_late(0),
564 current_packet_successfull(0),
565 packet_loss_counter(0),
566 current_bytes_transfered(0),
567 current_bytes_received(0),
568 current_bytes_lost(0),
572 max_incoming_kbps(0.0),
573 cur_incoming_kbps(0.0),
574 avg_incoming_kbps(0.0),
587 u16 Channel::readNextIncomingSeqNum()
589 JMutexAutoLock internal(m_internal_mutex);
590 return next_incoming_seqnum;
593 u16 Channel::incNextIncomingSeqNum()
595 JMutexAutoLock internal(m_internal_mutex);
596 u16 retval = next_incoming_seqnum;
597 next_incoming_seqnum++;
601 u16 Channel::readNextSplitSeqNum()
603 JMutexAutoLock internal(m_internal_mutex);
604 return next_outgoing_split_seqnum;
606 void Channel::setNextSplitSeqNum(u16 seqnum)
608 JMutexAutoLock internal(m_internal_mutex);
609 next_outgoing_split_seqnum = seqnum;
612 u16 Channel::getOutgoingSequenceNumber(bool& successfull)
614 JMutexAutoLock internal(m_internal_mutex);
615 u16 retval = next_outgoing_seqnum;
616 u16 lowest_unacked_seqnumber;
618 /* shortcut if there ain't any packet in outgoing list */
619 if (outgoing_reliables_sent.empty())
621 next_outgoing_seqnum++;
625 if (outgoing_reliables_sent.getFirstSeqnum(lowest_unacked_seqnumber))
627 if (lowest_unacked_seqnumber < next_outgoing_seqnum) {
628 // ugly cast but this one is required in order to tell compiler we
629 // know about difference of two unsigned may be negative in general
630 // but we already made sure it won't happen in this case
631 if (((u16)(next_outgoing_seqnum - lowest_unacked_seqnumber)) > window_size) {
637 // ugly cast but this one is required in order to tell compiler we
638 // know about difference of two unsigned may be negative in general
639 // but we already made sure it won't happen in this case
640 if ((next_outgoing_seqnum + (u16)(SEQNUM_MAX - lowest_unacked_seqnumber)) >
648 next_outgoing_seqnum++;
652 u16 Channel::readOutgoingSequenceNumber()
654 JMutexAutoLock internal(m_internal_mutex);
655 return next_outgoing_seqnum;
658 bool Channel::putBackSequenceNumber(u16 seqnum)
660 if (((seqnum + 1) % (SEQNUM_MAX+1)) == next_outgoing_seqnum) {
662 next_outgoing_seqnum = seqnum;
668 void Channel::UpdateBytesSent(unsigned int bytes, unsigned int packets)
670 JMutexAutoLock internal(m_internal_mutex);
671 current_bytes_transfered += bytes;
672 current_packet_successfull += packets;
675 void Channel::UpdateBytesReceived(unsigned int bytes) {
676 JMutexAutoLock internal(m_internal_mutex);
677 current_bytes_received += bytes;
680 void Channel::UpdateBytesLost(unsigned int bytes)
682 JMutexAutoLock internal(m_internal_mutex);
683 current_bytes_lost += bytes;
687 void Channel::UpdatePacketLossCounter(unsigned int count)
689 JMutexAutoLock internal(m_internal_mutex);
690 current_packet_loss += count;
693 void Channel::UpdatePacketTooLateCounter()
695 JMutexAutoLock internal(m_internal_mutex);
696 current_packet_too_late++;
699 void Channel::UpdateTimers(float dtime,bool legacy_peer)
701 bpm_counter += dtime;
702 packet_loss_counter += dtime;
704 if (packet_loss_counter > 1.0)
706 packet_loss_counter -= 1.0;
708 unsigned int packet_loss = 11; /* use a neutral value for initialization */
709 unsigned int packets_successfull = 0;
710 unsigned int packet_too_late = 0;
712 bool reasonable_amount_of_data_transmitted = false;
715 JMutexAutoLock internal(m_internal_mutex);
716 packet_loss = current_packet_loss;
717 packet_too_late = current_packet_too_late;
718 packets_successfull = current_packet_successfull;
720 if (current_bytes_transfered > (unsigned int) (window_size*512/2))
722 reasonable_amount_of_data_transmitted = true;
724 current_packet_loss = 0;
725 current_packet_too_late = 0;
726 current_packet_successfull = 0;
729 /* dynamic window size is only available for non legacy peers */
731 float successfull_to_lost_ratio = 0.0;
734 if (packets_successfull > 0) {
735 successfull_to_lost_ratio = packet_loss/packets_successfull;
737 else if (packet_loss > 0)
741 MIN_RELIABLE_WINDOW_SIZE);
747 if ((successfull_to_lost_ratio < 0.01) &&
748 (window_size < MAX_RELIABLE_WINDOW_SIZE))
750 /* don't even think about increasing if we didn't even
751 * use major parts of our window */
752 if (reasonable_amount_of_data_transmitted)
755 MAX_RELIABLE_WINDOW_SIZE);
757 else if ((successfull_to_lost_ratio < 0.05) &&
758 (window_size < MAX_RELIABLE_WINDOW_SIZE))
760 /* don't even think about increasing if we didn't even
761 * use major parts of our window */
762 if (reasonable_amount_of_data_transmitted)
765 MAX_RELIABLE_WINDOW_SIZE);
767 else if (successfull_to_lost_ratio > 0.15)
771 MIN_RELIABLE_WINDOW_SIZE);
773 else if (successfull_to_lost_ratio > 0.1)
777 MIN_RELIABLE_WINDOW_SIZE);
783 if (bpm_counter > 10.0)
786 JMutexAutoLock internal(m_internal_mutex);
788 (((float) current_bytes_transfered)/bpm_counter)/1024.0;
789 current_bytes_transfered = 0;
791 (((float) current_bytes_lost)/bpm_counter)/1024.0;
792 current_bytes_lost = 0;
794 (((float) current_bytes_received)/bpm_counter)/1024.0;
795 current_bytes_received = 0;
799 if (cur_kbps > max_kbps)
804 if (cur_kbps_lost > max_kbps_lost)
806 max_kbps_lost = cur_kbps_lost;
809 if (cur_incoming_kbps > max_incoming_kbps) {
810 max_incoming_kbps = cur_incoming_kbps;
813 rate_samples = MYMIN(rate_samples+1,10);
814 float old_fraction = ((float) (rate_samples-1) )/( (float) rate_samples);
815 avg_kbps = avg_kbps * old_fraction +
816 cur_kbps * (1.0 - old_fraction);
817 avg_kbps_lost = avg_kbps_lost * old_fraction +
818 cur_kbps_lost * (1.0 - old_fraction);
819 avg_incoming_kbps = avg_incoming_kbps * old_fraction +
820 cur_incoming_kbps * (1.0 - old_fraction);
829 PeerHelper::PeerHelper() :
833 PeerHelper::PeerHelper(Peer* peer) :
838 if (!peer->IncUseCount())
845 PeerHelper::~PeerHelper()
848 m_peer->DecUseCount();
853 PeerHelper& PeerHelper::operator=(Peer* peer)
858 if (!peer->IncUseCount())
866 Peer* PeerHelper::operator->() const
871 Peer* PeerHelper::operator&() const
876 bool PeerHelper::operator!() {
880 bool PeerHelper::operator!=(void* ptr)
882 return ((void*) m_peer != ptr);
885 bool Peer::IncUseCount()
887 JMutexAutoLock lock(m_exclusive_access_mutex);
889 if (!m_pending_deletion)
898 void Peer::DecUseCount()
901 JMutexAutoLock lock(m_exclusive_access_mutex);
905 if (!((m_pending_deletion) && (m_usage == 0)))
911 void Peer::RTTStatistics(float rtt, std::string profiler_id,
912 unsigned int num_samples) {
914 if (m_last_rtt > 0) {
915 /* set min max values */
916 if (rtt < m_rtt.min_rtt)
918 if (rtt >= m_rtt.max_rtt)
921 /* do average calculation */
922 if(m_rtt.avg_rtt < 0.0)
925 m_rtt.avg_rtt = m_rtt.avg_rtt * (num_samples/(num_samples-1)) +
926 rtt * (1/num_samples);
928 /* do jitter calculation */
930 //just use some neutral value at beginning
931 float jitter = m_rtt.jitter_min;
933 if (rtt > m_last_rtt)
934 jitter = rtt-m_last_rtt;
936 if (rtt <= m_last_rtt)
937 jitter = m_last_rtt - rtt;
939 if (jitter < m_rtt.jitter_min)
940 m_rtt.jitter_min = jitter;
941 if (jitter >= m_rtt.jitter_max)
942 m_rtt.jitter_max = jitter;
944 if(m_rtt.jitter_avg < 0.0)
945 m_rtt.jitter_avg = jitter;
947 m_rtt.jitter_avg = m_rtt.jitter_avg * (num_samples/(num_samples-1)) +
948 jitter * (1/num_samples);
950 if (profiler_id != "")
952 g_profiler->graphAdd(profiler_id + "_rtt", rtt);
953 g_profiler->graphAdd(profiler_id + "_jitter", jitter);
956 /* save values required for next loop */
960 bool Peer::isTimedOut(float timeout)
962 JMutexAutoLock lock(m_exclusive_access_mutex);
963 u32 current_time = porting::getTimeMs();
965 float dtime = CALC_DTIME(m_last_timeout_check,current_time);
966 m_last_timeout_check = current_time;
968 m_timeout_counter += dtime;
970 return m_timeout_counter > timeout;
976 JMutexAutoLock usage_lock(m_exclusive_access_mutex);
977 m_pending_deletion = true;
982 PROFILE(std::stringstream peerIdentifier1);
983 PROFILE(peerIdentifier1 << "runTimeouts[" << m_connection->getDesc()
984 << ";" << id << ";RELIABLE]");
985 PROFILE(g_profiler->remove(peerIdentifier1.str()));
986 PROFILE(std::stringstream peerIdentifier2);
987 PROFILE(peerIdentifier2 << "sendPackets[" << m_connection->getDesc()
988 << ";" << id << ";RELIABLE]");
989 PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier2.str(), SPT_AVG));
994 UDPPeer::UDPPeer(u16 a_id, Address a_address, Connection* connection) :
995 Peer(a_address,a_id,connection),
996 m_pending_disconnect(false),
1002 bool UDPPeer::getAddress(MTProtocols type,Address& toset)
1004 if ((type == MTP_UDP) || (type == MTP_MINETEST_RELIABLE_UDP) || (type == MTP_PRIMARY))
1013 void UDPPeer::setNonLegacyPeer()
1015 m_legacy_peer = false;
1016 for(unsigned int i=0; i< CHANNEL_COUNT; i++)
1018 channels->setWindowSize(g_settings->getU16("max_packets_per_iteration"));
1022 void UDPPeer::reportRTT(float rtt)
1027 RTTStatistics(rtt,"rudp",MAX_RELIABLE_WINDOW_SIZE*10);
1029 float timeout = getStat(AVG_RTT) * RESEND_TIMEOUT_FACTOR;
1030 if(timeout < RESEND_TIMEOUT_MIN)
1031 timeout = RESEND_TIMEOUT_MIN;
1032 if(timeout > RESEND_TIMEOUT_MAX)
1033 timeout = RESEND_TIMEOUT_MAX;
1035 JMutexAutoLock usage_lock(m_exclusive_access_mutex);
1036 resend_timeout = timeout;
1039 bool UDPPeer::Ping(float dtime,SharedBuffer<u8>& data)
1041 m_ping_timer += dtime;
1042 if(m_ping_timer >= PING_TIMEOUT)
1044 // Create and send PING packet
1045 writeU8(&data[0], TYPE_CONTROL);
1046 writeU8(&data[1], CONTROLTYPE_PING);
1053 void UDPPeer::PutReliableSendCommand(ConnectionCommand &c,
1054 unsigned int max_packet_size)
1056 if (m_pending_disconnect)
1059 if ( channels[c.channelnum].queued_commands.empty() &&
1060 /* don't queue more packets then window size */
1061 (channels[c.channelnum].queued_reliables.size()
1062 < (channels[c.channelnum].getWindowSize()/2)))
1064 LOG(dout_con<<m_connection->getDesc()
1065 <<" processing reliable command for peer id: " << c.peer_id
1066 <<" data size: " << c.data.getSize() << std::endl);
1067 if (!processReliableSendCommand(c,max_packet_size))
1069 channels[c.channelnum].queued_commands.push_back(c);
1074 LOG(dout_con<<m_connection->getDesc()
1075 <<" Queueing reliable command for peer id: " << c.peer_id
1076 <<" data size: " << c.data.getSize() <<std::endl);
1077 channels[c.channelnum].queued_commands.push_back(c);
1081 bool UDPPeer::processReliableSendCommand(
1082 ConnectionCommand &c,
1083 unsigned int max_packet_size)
1085 if (m_pending_disconnect)
1088 u32 chunksize_max = max_packet_size
1090 - RELIABLE_HEADER_SIZE;
1092 assert(c.data.getSize() < MAX_RELIABLE_WINDOW_SIZE*512);
1094 std::list<SharedBuffer<u8> > originals;
1095 u16 split_sequence_number = channels[c.channelnum].readNextSplitSeqNum();
1099 originals.push_back(c.data);
1102 originals = makeAutoSplitPacket(c.data, chunksize_max,split_sequence_number);
1103 channels[c.channelnum].setNextSplitSeqNum(split_sequence_number);
1106 bool have_sequence_number = true;
1107 bool have_initial_sequence_number = false;
1108 Queue<BufferedPacket> toadd;
1109 volatile u16 initial_sequence_number = 0;
1111 for(std::list<SharedBuffer<u8> >::iterator i = originals.begin();
1112 i != originals.end(); ++i)
1114 u16 seqnum = channels[c.channelnum].getOutgoingSequenceNumber(have_sequence_number);
1116 /* oops, we don't have enough sequence numbers to send this packet */
1117 if (!have_sequence_number)
1120 if (!have_initial_sequence_number)
1122 initial_sequence_number = seqnum;
1123 have_initial_sequence_number = true;
1126 SharedBuffer<u8> reliable = makeReliablePacket(*i, seqnum);
1128 // Add base headers and make a packet
1129 BufferedPacket p = con::makePacket(address, reliable,
1130 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1136 if (have_sequence_number) {
1137 volatile u16 pcount = 0;
1138 while(toadd.size() > 0) {
1139 BufferedPacket p = toadd.pop_front();
1140 // LOG(dout_con<<connection->getDesc()
1141 // << " queuing reliable packet for peer_id: " << c.peer_id
1142 // << " channel: " << (c.channelnum&0xFF)
1143 // << " seqnum: " << readU16(&p.data[BASE_HEADER_SIZE+1])
1145 channels[c.channelnum].queued_reliables.push_back(p);
1148 assert(channels[c.channelnum].queued_reliables.size() < 0xFFFF);
1152 volatile u16 packets_available = toadd.size();
1153 /* we didn't get a single sequence number no need to fill queue */
1154 if (!have_initial_sequence_number)
1158 while(toadd.size() > 0) {
1162 bool successfully_put_back_sequence_number
1163 = channels[c.channelnum].putBackSequenceNumber(
1164 (initial_sequence_number+toadd.size() % (SEQNUM_MAX+1)));
1166 assert(successfully_put_back_sequence_number);
1168 LOG(dout_con<<m_connection->getDesc()
1169 << " Windowsize exceeded on reliable sending "
1170 << c.data.getSize() << " bytes"
1171 << std::endl << "\t\tinitial_sequence_number: "
1172 << initial_sequence_number
1173 << std::endl << "\t\tgot at most : "
1174 << packets_available << " packets"
1175 << std::endl << "\t\tpackets queued : "
1176 << channels[c.channelnum].outgoing_reliables_sent.size()
1182 void UDPPeer::RunCommandQueues(
1183 unsigned int max_packet_size,
1184 unsigned int maxcommands,
1185 unsigned int maxtransfer)
1188 for (unsigned int i = 0; i < CHANNEL_COUNT; i++)
1190 unsigned int commands_processed = 0;
1192 if ((channels[i].queued_commands.size() > 0) &&
1193 (channels[i].queued_reliables.size() < maxtransfer) &&
1194 (commands_processed < maxcommands))
1197 ConnectionCommand c = channels[i].queued_commands.pop_front();
1198 LOG(dout_con<<m_connection->getDesc()
1199 <<" processing queued reliable command "<<std::endl);
1200 if (!processReliableSendCommand(c,max_packet_size)) {
1201 LOG(dout_con<<m_connection->getDesc()
1202 << " Failed to queue packets for peer_id: " << c.peer_id
1203 << ", delaying sending of " << c.data.getSize()
1204 << " bytes" << std::endl);
1205 channels[i].queued_commands.push_front(c);
1208 catch (ItemNotFoundException &e) {
1209 // intentionally empty
1215 u16 UDPPeer::getNextSplitSequenceNumber(u8 channel)
1217 assert(channel < CHANNEL_COUNT);
1218 return channels[channel].readNextIncomingSeqNum();
1221 void UDPPeer::setNextSplitSequenceNumber(u8 channel, u16 seqnum)
1223 assert(channel < CHANNEL_COUNT);
1224 channels[channel].setNextSplitSeqNum(seqnum);
1227 SharedBuffer<u8> UDPPeer::addSpiltPacket(u8 channel,
1228 BufferedPacket toadd,
1231 assert(channel < CHANNEL_COUNT);
1232 return channels[channel].incoming_splits.insert(toadd,reliable);
1235 /******************************************************************************/
1236 /* Connection Threads */
1237 /******************************************************************************/
1239 ConnectionSendThread::ConnectionSendThread(Connection* parent,
1240 unsigned int max_packet_size,
1242 m_connection(parent),
1243 m_max_packet_size(max_packet_size),
1245 m_max_commands_per_iteration(1),
1246 m_max_data_packets_per_iteration(g_settings->getU16("max_packets_per_iteration")),
1247 m_max_packets_requeued(256)
1251 void * ConnectionSendThread::Thread()
1254 log_register_thread("ConnectionSend");
1256 LOG(dout_con<<m_connection->getDesc()
1257 <<"ConnectionSend thread started"<<std::endl);
1259 u32 curtime = porting::getTimeMs();
1260 u32 lasttime = curtime;
1262 PROFILE(std::stringstream ThreadIdentifier);
1263 PROFILE(ThreadIdentifier << "ConnectionSend: [" << m_connection->getDesc() << "]");
1265 porting::setThreadName("ConnectionSend");
1267 /* if stop is requested don't stop immediately but try to send all */
1269 while(!StopRequested() || packetsQueued()) {
1270 BEGIN_DEBUG_EXCEPTION_HANDLER
1271 PROFILE(ScopeProfiler sp(g_profiler, ThreadIdentifier.str(), SPT_AVG));
1273 m_iteration_packets_avaialble = m_max_data_packets_per_iteration;
1275 /* wait for trigger or timeout */
1276 m_send_sleep_semaphore.Wait(50);
1278 /* remove all triggers */
1279 while(m_send_sleep_semaphore.Wait(0)) {}
1282 curtime = porting::getTimeMs();
1283 float dtime = CALC_DTIME(lasttime,curtime);
1285 /* first do all the reliable stuff */
1288 /* translate commands to packets */
1289 ConnectionCommand c = m_connection->m_command_queue.pop_frontNoEx(0);
1290 while(c.type != CONNCMD_NONE)
1293 processReliableCommand(c);
1295 processNonReliableCommand(c);
1297 c = m_connection->m_command_queue.pop_frontNoEx(0);
1300 /* send non reliable packets */
1303 END_DEBUG_EXCEPTION_HANDLER(errorstream);
1306 PROFILE(g_profiler->remove(ThreadIdentifier.str()));
1310 void ConnectionSendThread::Trigger()
1312 m_send_sleep_semaphore.Post();
1315 bool ConnectionSendThread::packetsQueued()
1317 std::list<u16> peerIds = m_connection->getPeerIDs();
1319 if ((this->m_outgoing_queue.size() > 0) && (peerIds.size() > 0))
1322 for(std::list<u16>::iterator j = peerIds.begin();
1323 j != peerIds.end(); ++j)
1325 PeerHelper peer = m_connection->getPeerNoEx(*j);
1330 if (dynamic_cast<UDPPeer*>(&peer) == 0)
1333 for(u16 i=0; i<CHANNEL_COUNT; i++)
1335 Channel *channel = &(dynamic_cast<UDPPeer*>(&peer))->channels[i];
1337 if (channel->queued_commands.size() > 0)
1348 void ConnectionSendThread::runTimeouts(float dtime)
1350 std::list<u16> timeouted_peers;
1351 std::list<u16> peerIds = m_connection->getPeerIDs();
1353 for(std::list<u16>::iterator j = peerIds.begin();
1354 j != peerIds.end(); ++j)
1356 PeerHelper peer = m_connection->getPeerNoEx(*j);
1361 if(dynamic_cast<UDPPeer*>(&peer) == 0)
1364 PROFILE(std::stringstream peerIdentifier);
1365 PROFILE(peerIdentifier << "runTimeouts[" << m_connection->getDesc()
1366 << ";" << *j << ";RELIABLE]");
1367 PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier.str(), SPT_AVG));
1369 SharedBuffer<u8> data(2); // data for sending ping, required here because of goto
1374 if(peer->isTimedOut(m_timeout))
1376 infostream<<m_connection->getDesc()
1377 <<"RunTimeouts(): Peer "<<peer->id
1379 <<" (source=peer->timeout_counter)"
1381 // Add peer to the list
1382 timeouted_peers.push_back(peer->id);
1383 // Don't bother going through the buffers of this one
1387 float resend_timeout = dynamic_cast<UDPPeer*>(&peer)->getResendTimeout();
1388 for(u16 i=0; i<CHANNEL_COUNT; i++)
1390 std::list<BufferedPacket> timed_outs;
1391 Channel *channel = &(dynamic_cast<UDPPeer*>(&peer))->channels[i];
1393 if (dynamic_cast<UDPPeer*>(&peer)->getLegacyPeer())
1394 channel->setWindowSize(g_settings->getU16("workaround_window_size"));
1396 // Remove timed out incomplete unreliable split packets
1397 channel->incoming_splits.removeUnreliableTimedOuts(dtime, m_timeout);
1399 // Increment reliable packet times
1400 channel->outgoing_reliables_sent.incrementTimeouts(dtime);
1402 unsigned int numpeers = m_connection->m_peers.size();
1407 // Re-send timed out outgoing reliables
1408 timed_outs = channel->
1409 outgoing_reliables_sent.getTimedOuts(resend_timeout,
1410 (m_max_data_packets_per_iteration/numpeers));
1412 channel->UpdatePacketLossCounter(timed_outs.size());
1413 g_profiler->graphAdd("packets_lost", timed_outs.size());
1415 m_iteration_packets_avaialble -= timed_outs.size();
1417 for(std::list<BufferedPacket>::iterator k = timed_outs.begin();
1418 k != timed_outs.end(); ++k)
1420 u16 peer_id = readPeerId(*(k->data));
1421 u8 channelnum = readChannel(*(k->data));
1422 u16 seqnum = readU16(&(k->data[BASE_HEADER_SIZE+1]));
1424 channel->UpdateBytesLost(k->data.getSize());
1427 LOG(derr_con<<m_connection->getDesc()
1428 <<"RE-SENDING timed-out RELIABLE to "
1429 << k->address.serializeString()
1430 << "(t/o="<<resend_timeout<<"): "
1431 <<"from_peer_id="<<peer_id
1432 <<", channel="<<((int)channelnum&0xff)
1433 <<", seqnum="<<seqnum
1438 // do not handle rtt here as we can't decide if this packet was
1439 // lost or really takes more time to transmit
1441 channel->UpdateTimers(dtime,dynamic_cast<UDPPeer*>(&peer)->getLegacyPeer());
1444 /* send ping if necessary */
1445 if (dynamic_cast<UDPPeer*>(&peer)->Ping(dtime,data)) {
1446 LOG(dout_con<<m_connection->getDesc()
1447 <<"Sending ping for peer_id: "
1448 << dynamic_cast<UDPPeer*>(&peer)->id <<std::endl);
1449 /* this may fail if there ain't a sequence number left */
1450 if (!rawSendAsPacket(dynamic_cast<UDPPeer*>(&peer)->id, 0, data, true))
1452 //retrigger with reduced ping interval
1453 dynamic_cast<UDPPeer*>(&peer)->Ping(4.0,data);
1457 dynamic_cast<UDPPeer*>(&peer)->RunCommandQueues(m_max_packet_size,
1458 m_max_commands_per_iteration,
1459 m_max_packets_requeued);
1462 // Remove timed out peers
1463 for(std::list<u16>::iterator i = timeouted_peers.begin();
1464 i != timeouted_peers.end(); ++i)
1466 LOG(derr_con<<m_connection->getDesc()
1467 <<"RunTimeouts(): Removing peer "<<(*i)<<std::endl);
1468 m_connection->deletePeer(*i, true);
1472 void ConnectionSendThread::rawSend(const BufferedPacket &packet)
1475 m_connection->m_udpSocket.Send(packet.address, *packet.data,
1476 packet.data.getSize());
1477 LOG(dout_con <<m_connection->getDesc()
1478 << " rawSend: " << packet.data.getSize()
1479 << " bytes sent" << std::endl);
1480 } catch(SendFailedException &e){
1481 LOG(derr_con<<m_connection->getDesc()
1482 <<"Connection::rawSend(): SendFailedException: "
1483 <<packet.address.serializeString()<<std::endl);
1487 void ConnectionSendThread::sendAsPacketReliable(BufferedPacket& p, Channel* channel)
1490 p.absolute_send_time = porting::getTimeMs();
1491 // Buffer the packet
1492 channel->outgoing_reliables_sent.insert(p,
1493 (channel->readOutgoingSequenceNumber() - MAX_RELIABLE_WINDOW_SIZE)
1494 % (MAX_RELIABLE_WINDOW_SIZE+1));
1496 catch(AlreadyExistsException &e)
1498 LOG(derr_con<<m_connection->getDesc()
1499 <<"WARNING: Going to send a reliable packet"
1500 <<" in outgoing buffer" <<std::endl);
1508 bool ConnectionSendThread::rawSendAsPacket(u16 peer_id, u8 channelnum,
1509 SharedBuffer<u8> data, bool reliable)
1511 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
1513 LOG(dout_con<<m_connection->getDesc()
1514 <<" INFO: dropped packet for non existent peer_id: "
1515 << peer_id << std::endl);
1516 assert(reliable && "trying to send raw packet reliable but no peer found!");
1519 Channel *channel = &(dynamic_cast<UDPPeer*>(&peer)->channels[channelnum]);
1523 bool have_sequence_number_for_raw_packet = true;
1525 channel->getOutgoingSequenceNumber(have_sequence_number_for_raw_packet);
1527 if (!have_sequence_number_for_raw_packet)
1530 SharedBuffer<u8> reliable = makeReliablePacket(data, seqnum);
1531 Address peer_address;
1532 peer->getAddress(MTP_MINETEST_RELIABLE_UDP, peer_address);
1534 // Add base headers and make a packet
1535 BufferedPacket p = con::makePacket(peer_address, reliable,
1536 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1539 // first check if our send window is already maxed out
1540 if (channel->outgoing_reliables_sent.size()
1541 < channel->getWindowSize()) {
1542 LOG(dout_con<<m_connection->getDesc()
1543 <<" INFO: sending a reliable packet to peer_id " << peer_id
1544 <<" channel: " << channelnum
1545 <<" seqnum: " << seqnum << std::endl);
1546 sendAsPacketReliable(p,channel);
1550 LOG(dout_con<<m_connection->getDesc()
1551 <<" INFO: queueing reliable packet for peer_id: " << peer_id
1552 <<" channel: " << channelnum
1553 <<" seqnum: " << seqnum << std::endl);
1554 channel->queued_reliables.push_back(p);
1560 Address peer_address;
1562 if (peer->getAddress(MTP_UDP, peer_address))
1564 // Add base headers and make a packet
1565 BufferedPacket p = con::makePacket(peer_address, data,
1566 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1574 LOG(dout_con<<m_connection->getDesc()
1575 <<" INFO: dropped unreliable packet for peer_id: " << peer_id
1576 <<" because of (yet) missing udp address" << std::endl);
1585 void ConnectionSendThread::processReliableCommand(ConnectionCommand &c)
1591 LOG(dout_con<<m_connection->getDesc()
1592 <<"UDP processing reliable CONNCMD_NONE"<<std::endl);
1596 LOG(dout_con<<m_connection->getDesc()
1597 <<"UDP processing reliable CONNCMD_SEND"<<std::endl);
1601 case CONNCMD_SEND_TO_ALL:
1602 LOG(dout_con<<m_connection->getDesc()
1603 <<"UDP processing CONNCMD_SEND_TO_ALL"<<std::endl);
1604 sendToAllReliable(c);
1607 case CONCMD_CREATE_PEER:
1608 LOG(dout_con<<m_connection->getDesc()
1609 <<"UDP processing reliable CONCMD_CREATE_PEER"<<std::endl);
1610 if (!rawSendAsPacket(c.peer_id,c.channelnum,c.data,c.reliable))
1612 /* put to queue if we couldn't send it immediately */
1617 case CONCMD_DISABLE_LEGACY:
1618 LOG(dout_con<<m_connection->getDesc()
1619 <<"UDP processing reliable CONCMD_DISABLE_LEGACY"<<std::endl);
1620 if (!rawSendAsPacket(c.peer_id,c.channelnum,c.data,c.reliable))
1622 /* put to queue if we couldn't send it immediately */
1628 case CONNCMD_CONNECT:
1629 case CONNCMD_DISCONNECT:
1631 assert("Got command that shouldn't be reliable as reliable command" == 0);
1633 LOG(dout_con<<m_connection->getDesc()
1634 <<" Invalid reliable command type: " << c.type <<std::endl);
1639 void ConnectionSendThread::processNonReliableCommand(ConnectionCommand &c)
1641 assert(!c.reliable);
1645 LOG(dout_con<<m_connection->getDesc()
1646 <<" UDP processing CONNCMD_NONE"<<std::endl);
1649 LOG(dout_con<<m_connection->getDesc()
1650 <<" UDP processing CONNCMD_SERVE port="
1651 <<c.address.serializeString()<<std::endl);
1654 case CONNCMD_CONNECT:
1655 LOG(dout_con<<m_connection->getDesc()
1656 <<" UDP processing CONNCMD_CONNECT"<<std::endl);
1659 case CONNCMD_DISCONNECT:
1660 LOG(dout_con<<m_connection->getDesc()
1661 <<" UDP processing CONNCMD_DISCONNECT"<<std::endl);
1664 case CONNCMD_DISCONNECT_PEER:
1665 LOG(dout_con<<m_connection->getDesc()
1666 <<" UDP processing CONNCMD_DISCONNECT_PEER"<<std::endl);
1667 disconnect_peer(c.peer_id);
1670 LOG(dout_con<<m_connection->getDesc()
1671 <<" UDP processing CONNCMD_SEND"<<std::endl);
1672 send(c.peer_id, c.channelnum, c.data);
1674 case CONNCMD_SEND_TO_ALL:
1675 LOG(dout_con<<m_connection->getDesc()
1676 <<" UDP processing CONNCMD_SEND_TO_ALL"<<std::endl);
1677 sendToAll(c.channelnum, c.data);
1680 LOG(dout_con<<m_connection->getDesc()
1681 <<" UDP processing CONCMD_ACK"<<std::endl);
1682 sendAsPacket(c.peer_id,c.channelnum,c.data,true);
1684 case CONCMD_CREATE_PEER:
1685 assert("Got command that should be reliable as unreliable command" == 0);
1687 LOG(dout_con<<m_connection->getDesc()
1688 <<" Invalid command type: " << c.type <<std::endl);
1692 void ConnectionSendThread::serve(Address bind_address)
1694 LOG(dout_con<<m_connection->getDesc()
1695 <<"UDP serving at port " << bind_address.serializeString() <<std::endl);
1697 m_connection->m_udpSocket.Bind(bind_address);
1698 m_connection->SetPeerID(PEER_ID_SERVER);
1700 catch(SocketException &e){
1704 m_connection->putEvent(ce);
1708 void ConnectionSendThread::connect(Address address)
1710 LOG(dout_con<<m_connection->getDesc()<<" connecting to "<<address.serializeString()
1711 <<":"<<address.getPort()<<std::endl);
1713 UDPPeer *peer = m_connection->createServerPeer(address);
1717 e.peerAdded(peer->id, peer->address);
1718 m_connection->putEvent(e);
1722 if (address.isIPv6())
1723 bind_addr.setAddress((IPv6AddressBytes*) NULL);
1725 bind_addr.setAddress(0,0,0,0);
1727 m_connection->m_udpSocket.Bind(bind_addr);
1729 // Send a dummy packet to server with peer_id = PEER_ID_INEXISTENT
1730 m_connection->SetPeerID(PEER_ID_INEXISTENT);
1731 SharedBuffer<u8> data(0);
1732 m_connection->Send(PEER_ID_SERVER, 0, data, 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) ||
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(Connection* parent,
1999 unsigned int max_packet_size) :
2000 m_connection(parent)
2004 void * ConnectionReceiveThread::Thread()
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)))
2116 bool no_data_left = false;
2118 SharedBuffer<u8> resultdata;
2119 while(!no_data_left)
2122 no_data_left = !getFromBuffers(peer_id, resultdata);
2123 if (!no_data_left) {
2125 e.dataReceived(peer_id, resultdata);
2126 m_connection->putEvent(e);
2129 catch(ProcessedSilentlyException &e) {
2130 /* try reading again */
2133 packet_queued = false;
2137 s32 received_size = m_connection->m_udpSocket.Receive(sender, *packetdata, packet_maxsize);
2139 if ((received_size < 0) ||
2140 (received_size < BASE_HEADER_SIZE) ||
2141 (readU32(&packetdata[0]) != m_connection->GetProtocolID()))
2143 LOG(derr_con<<m_connection->getDesc()
2144 <<"Receive(): Invalid incoming packet, "
2145 <<"size: " << received_size
2147 << ((received_size >= 4) ? readU32(&packetdata[0]) : -1)
2152 u16 peer_id = readPeerId(*packetdata);
2153 u8 channelnum = readChannel(*packetdata);
2155 if(channelnum > CHANNEL_COUNT-1){
2156 LOG(derr_con<<m_connection->getDesc()
2157 <<"Receive(): Invalid channel "<<channelnum<<std::endl);
2158 throw InvalidIncomingDataException("Channel doesn't exist");
2161 /* preserve original peer_id for later usage */
2162 u16 packet_peer_id = peer_id;
2164 /* Try to identify peer by sender address (may happen on join) */
2165 if(peer_id == PEER_ID_INEXISTENT)
2167 peer_id = m_connection->lookupPeer(sender);
2170 /* The peer was not found in our lists. Add it. */
2171 if(peer_id == PEER_ID_INEXISTENT)
2173 peer_id = m_connection->createPeer(sender, MTP_MINETEST_RELIABLE_UDP, 0);
2176 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
2179 LOG(dout_con<<m_connection->getDesc()
2180 <<" got packet from unknown peer_id: "
2181 <<peer_id<<" Ignoring."<<std::endl);
2185 // Validate peer address
2187 Address peer_address;
2189 if (peer->getAddress(MTP_UDP, peer_address)) {
2190 if (peer_address != sender) {
2191 LOG(derr_con<<m_connection->getDesc()
2192 <<m_connection->getDesc()
2193 <<" Peer "<<peer_id<<" sending from different address."
2194 " Ignoring."<<std::endl);
2200 bool invalid_address = true;
2201 if (invalid_address) {
2202 LOG(derr_con<<m_connection->getDesc()
2203 <<m_connection->getDesc()
2204 <<" Peer "<<peer_id<<" unknown."
2205 " Ignoring."<<std::endl);
2211 /* mark peer as seen with id */
2212 if (!(packet_peer_id == PEER_ID_INEXISTENT))
2213 peer->setSentWithID();
2215 peer->ResetTimeout();
2217 Channel *channel = 0;
2219 if (dynamic_cast<UDPPeer*>(&peer) != 0)
2221 channel = &(dynamic_cast<UDPPeer*>(&peer)->channels[channelnum]);
2225 channel->UpdateBytesReceived(received_size);
2228 // Throw the received packet to channel->processPacket()
2230 // Make a new SharedBuffer from the data without the base headers
2231 SharedBuffer<u8> strippeddata(received_size - BASE_HEADER_SIZE);
2232 memcpy(*strippeddata, &packetdata[BASE_HEADER_SIZE],
2233 strippeddata.getSize());
2236 // Process it (the result is some data with no headers made by us)
2237 SharedBuffer<u8> resultdata = processPacket
2238 (channel, strippeddata, peer_id, channelnum, false);
2240 LOG(dout_con<<m_connection->getDesc()
2241 <<" ProcessPacket from peer_id: " << peer_id
2242 << ",channel: " << (channelnum & 0xFF) << ", returned "
2243 << resultdata.getSize() << " bytes" <<std::endl);
2246 e.dataReceived(peer_id, resultdata);
2247 m_connection->putEvent(e);
2248 }catch(ProcessedSilentlyException &e){
2249 }catch(ProcessedQueued &e){
2250 packet_queued = true;
2252 }catch(InvalidIncomingDataException &e){
2254 catch(ProcessedSilentlyException &e){
2259 bool ConnectionReceiveThread::getFromBuffers(u16 &peer_id, SharedBuffer<u8> &dst)
2261 std::list<u16> peerids = m_connection->getPeerIDs();
2263 for(std::list<u16>::iterator j = peerids.begin();
2264 j != peerids.end(); ++j)
2266 PeerHelper peer = m_connection->getPeerNoEx(*j);
2270 if(dynamic_cast<UDPPeer*>(&peer) == 0)
2273 for(u16 i=0; i<CHANNEL_COUNT; i++)
2275 Channel *channel = &(dynamic_cast<UDPPeer*>(&peer))->channels[i];
2277 SharedBuffer<u8> resultdata;
2278 bool got = checkIncomingBuffers(channel, peer_id, resultdata);
2288 bool ConnectionReceiveThread::checkIncomingBuffers(Channel *channel,
2289 u16 &peer_id, SharedBuffer<u8> &dst)
2291 u16 firstseqnum = 0;
2292 if (channel->incoming_reliables.getFirstSeqnum(firstseqnum))
2294 if(firstseqnum == channel->readNextIncomingSeqNum())
2296 BufferedPacket p = channel->incoming_reliables.popFirst();
2297 peer_id = readPeerId(*p.data);
2298 u8 channelnum = readChannel(*p.data);
2299 u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]);
2301 LOG(dout_con<<m_connection->getDesc()
2302 <<"UNBUFFERING TYPE_RELIABLE"
2303 <<" seqnum="<<seqnum
2304 <<" peer_id="<<peer_id
2305 <<" channel="<<((int)channelnum&0xff)
2308 channel->incNextIncomingSeqNum();
2310 u32 headers_size = BASE_HEADER_SIZE + RELIABLE_HEADER_SIZE;
2311 // Get out the inside packet and re-process it
2312 SharedBuffer<u8> payload(p.data.getSize() - headers_size);
2313 memcpy(*payload, &p.data[headers_size], payload.getSize());
2315 dst = processPacket(channel, payload, peer_id, channelnum, true);
2322 SharedBuffer<u8> ConnectionReceiveThread::processPacket(Channel *channel,
2323 SharedBuffer<u8> packetdata, u16 peer_id, u8 channelnum, bool reliable)
2325 PeerHelper peer = m_connection->getPeer(peer_id);
2327 if(packetdata.getSize() < 1)
2328 throw InvalidIncomingDataException("packetdata.getSize() < 1");
2330 u8 type = readU8(&(packetdata[0]));
2332 if(type == TYPE_CONTROL)
2334 if(packetdata.getSize() < 2)
2335 throw InvalidIncomingDataException("packetdata.getSize() < 2");
2337 u8 controltype = readU8(&(packetdata[1]));
2339 if( (controltype == CONTROLTYPE_ACK)
2340 && (peer_id <= MAX_UDP_PEERS))
2342 assert(channel != 0);
2343 if(packetdata.getSize() < 4)
2344 throw InvalidIncomingDataException
2345 ("packetdata.getSize() < 4 (ACK header size)");
2347 u16 seqnum = readU16(&packetdata[2]);
2348 LOG(dout_con<<m_connection->getDesc()
2349 <<" [ CONTROLTYPE_ACK: channelnum="
2350 <<((int)channelnum&0xff)<<", peer_id="<<peer_id
2351 <<", seqnum="<<seqnum<< " ]"<<std::endl);
2355 channel->outgoing_reliables_sent.popSeqnum(seqnum);
2357 // only calculate rtt from straight sent packets
2358 if (p.resend_count == 0) {
2359 // Get round trip time
2360 unsigned int current_time = porting::getTimeMs();
2362 // a overflow is quite unlikely but as it'd result in major
2363 // rtt miscalculation we handle it here
2364 if (current_time > p.absolute_send_time)
2366 float rtt = (current_time - p.absolute_send_time) / 1000.0;
2368 // Let peer calculate stuff according to it
2369 // (avg_rtt and resend_timeout)
2370 dynamic_cast<UDPPeer*>(&peer)->reportRTT(rtt);
2372 else if (p.totaltime > 0)
2374 float rtt = p.totaltime;
2376 // Let peer calculate stuff according to it
2377 // (avg_rtt and resend_timeout)
2378 dynamic_cast<UDPPeer*>(&peer)->reportRTT(rtt);
2381 //put bytes for max bandwidth calculation
2382 channel->UpdateBytesSent(p.data.getSize(),1);
2383 if (channel->outgoing_reliables_sent.size() == 0)
2385 m_connection->TriggerSend();
2388 catch(NotFoundException &e){
2389 LOG(derr_con<<m_connection->getDesc()
2390 <<"WARNING: ACKed packet not "
2393 channel->UpdatePacketTooLateCounter();
2395 throw ProcessedSilentlyException("Got an ACK");
2397 else if((controltype == CONTROLTYPE_SET_PEER_ID)
2398 && (peer_id <= MAX_UDP_PEERS))
2400 // Got a packet to set our peer id
2401 if(packetdata.getSize() < 4)
2402 throw InvalidIncomingDataException
2403 ("packetdata.getSize() < 4 (SET_PEER_ID header size)");
2404 u16 peer_id_new = readU16(&packetdata[2]);
2405 LOG(dout_con<<m_connection->getDesc()
2406 <<"Got new peer id: "<<peer_id_new<<"... "<<std::endl);
2408 if(m_connection->GetPeerID() != PEER_ID_INEXISTENT)
2410 LOG(derr_con<<m_connection->getDesc()
2411 <<"WARNING: Not changing"
2412 " existing peer id."<<std::endl);
2416 LOG(dout_con<<m_connection->getDesc()<<"changing own peer id"<<std::endl);
2417 m_connection->SetPeerID(peer_id_new);
2420 ConnectionCommand cmd;
2422 SharedBuffer<u8> reply(2);
2423 writeU8(&reply[0], TYPE_CONTROL);
2424 writeU8(&reply[1], CONTROLTYPE_ENABLE_BIG_SEND_WINDOW);
2425 cmd.disableLegacy(PEER_ID_SERVER,reply);
2426 m_connection->putCommand(cmd);
2428 throw ProcessedSilentlyException("Got a SET_PEER_ID");
2430 else if((controltype == CONTROLTYPE_PING)
2431 && (peer_id <= MAX_UDP_PEERS))
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)
2454 && (peer_id <= MAX_UDP_PEERS))
2456 dynamic_cast<UDPPeer*>(&peer)->setNonLegacyPeer();
2457 throw ProcessedSilentlyException("Got non legacy control");
2460 LOG(derr_con<<m_connection->getDesc()
2461 <<"INVALID TYPE_CONTROL: invalid controltype="
2462 <<((int)controltype&0xff)<<std::endl);
2463 throw InvalidIncomingDataException("Invalid control type");
2466 else if(type == TYPE_ORIGINAL)
2468 if(packetdata.getSize() <= ORIGINAL_HEADER_SIZE)
2469 throw InvalidIncomingDataException
2470 ("packetdata.getSize() <= ORIGINAL_HEADER_SIZE");
2471 LOG(dout_con<<m_connection->getDesc()
2472 <<"RETURNING TYPE_ORIGINAL to user"
2474 // Get the inside packet out and return it
2475 SharedBuffer<u8> payload(packetdata.getSize() - ORIGINAL_HEADER_SIZE);
2476 memcpy(*payload, &(packetdata[ORIGINAL_HEADER_SIZE]), payload.getSize());
2479 else if(type == TYPE_SPLIT)
2481 Address peer_address;
2483 if (peer->getAddress(MTP_UDP, peer_address)) {
2485 // We have to create a packet again for buffering
2486 // This isn't actually too bad an idea.
2487 BufferedPacket packet = makePacket(
2490 m_connection->GetProtocolID(),
2494 // Buffer the packet
2495 SharedBuffer<u8> data =
2496 peer->addSpiltPacket(channelnum,packet,reliable);
2498 if(data.getSize() != 0)
2500 LOG(dout_con<<m_connection->getDesc()
2501 <<"RETURNING TYPE_SPLIT: Constructed full data, "
2502 <<"size="<<data.getSize()<<std::endl);
2505 LOG(dout_con<<m_connection->getDesc()<<"BUFFERED TYPE_SPLIT"<<std::endl);
2506 throw ProcessedSilentlyException("Buffered a split packet chunk");
2509 //TODO throw some error
2512 else if((peer_id <= MAX_UDP_PEERS) && (type == TYPE_RELIABLE))
2514 assert(channel != 0);
2515 // Recursive reliable packets not allowed
2517 throw InvalidIncomingDataException("Found nested reliable packets");
2519 if(packetdata.getSize() < RELIABLE_HEADER_SIZE)
2520 throw InvalidIncomingDataException
2521 ("packetdata.getSize() < RELIABLE_HEADER_SIZE");
2523 u16 seqnum = readU16(&packetdata[1]);
2524 bool is_future_packet = false;
2525 bool is_old_packet = false;
2527 /* packet is within our receive window send ack */
2528 if (seqnum_in_window(seqnum, channel->readNextIncomingSeqNum(),MAX_RELIABLE_WINDOW_SIZE))
2530 m_connection->sendAck(peer_id,channelnum,seqnum);
2533 is_future_packet = seqnum_higher(seqnum, channel->readNextIncomingSeqNum());
2534 is_old_packet = seqnum_higher(channel->readNextIncomingSeqNum(), seqnum);
2537 /* packet is not within receive window, don't send ack. *
2538 * if this was a valid packet it's gonna be retransmitted */
2539 if (is_future_packet)
2541 throw ProcessedSilentlyException("Received packet newer then expected, not sending ack");
2544 /* seems like our ack was lost, send another one for a old packet */
2547 LOG(dout_con<<m_connection->getDesc()
2548 << "RE-SENDING ACK: peer_id: " << peer_id
2549 << ", channel: " << (channelnum&0xFF)
2550 << ", seqnum: " << seqnum << std::endl;)
2551 m_connection->sendAck(peer_id,channelnum,seqnum);
2553 // we already have this packet so this one was on wire at least
2554 // the current timeout
2555 // we don't know how long this packet was on wire don't do silly guessing
2556 // dynamic_cast<UDPPeer*>(&peer)->reportRTT(dynamic_cast<UDPPeer*>(&peer)->getResendTimeout());
2558 throw ProcessedSilentlyException("Retransmitting ack for old packet");
2562 if (seqnum != channel->readNextIncomingSeqNum())
2564 Address peer_address;
2566 // this is a reliable packet so we have a udp address for sure
2567 peer->getAddress(MTP_MINETEST_RELIABLE_UDP, peer_address);
2568 // This one comes later, buffer it.
2569 // Actually we have to make a packet to buffer one.
2570 // Well, we have all the ingredients, so just do it.
2571 BufferedPacket packet = con::makePacket(
2574 m_connection->GetProtocolID(),
2578 channel->incoming_reliables.insert(packet,channel->readNextIncomingSeqNum());
2580 LOG(dout_con<<m_connection->getDesc()
2581 << "BUFFERING, TYPE_RELIABLE peer_id: " << peer_id
2582 << ", channel: " << (channelnum&0xFF)
2583 << ", seqnum: " << seqnum << std::endl;)
2585 throw ProcessedQueued("Buffered future reliable packet");
2587 catch(AlreadyExistsException &e)
2590 catch(IncomingDataCorruption &e)
2592 ConnectionCommand discon;
2593 discon.disconnect_peer(peer_id);
2594 m_connection->putCommand(discon);
2596 LOG(derr_con<<m_connection->getDesc()
2597 << "INVALID, TYPE_RELIABLE peer_id: " << peer_id
2598 << ", channel: " << (channelnum&0xFF)
2599 << ", seqnum: " << seqnum
2600 << "DROPPING CLIENT!" << std::endl;)
2604 /* we got a packet to process right now */
2605 LOG(dout_con<<m_connection->getDesc()
2606 << "RECURSIVE, TYPE_RELIABLE peer_id: " << peer_id
2607 << ", channel: " << (channelnum&0xFF)
2608 << ", seqnum: " << seqnum << std::endl;)
2611 /* check for resend case */
2612 u16 queued_seqnum = 0;
2613 if (channel->incoming_reliables.getFirstSeqnum(queued_seqnum))
2615 if (queued_seqnum == seqnum)
2617 BufferedPacket queued_packet = channel->incoming_reliables.popFirst();
2618 /** TODO find a way to verify the new against the old packet */
2622 channel->incNextIncomingSeqNum();
2624 // Get out the inside packet and re-process it
2625 SharedBuffer<u8> payload(packetdata.getSize() - RELIABLE_HEADER_SIZE);
2626 memcpy(*payload, &packetdata[RELIABLE_HEADER_SIZE], payload.getSize());
2628 return processPacket(channel, payload, peer_id, channelnum, true);
2632 derr_con<<m_connection->getDesc()
2633 <<"Got invalid type="<<((int)type&0xff)<<std::endl;
2634 throw InvalidIncomingDataException("Invalid packet type");
2637 // We should never get here.
2638 // If you get here, add an exception or a return to some of the
2639 // above conditionals.
2641 throw BaseException("Error in Channel::ProcessPacket()");
2648 Connection::Connection(u32 protocol_id, u32 max_packet_size, float timeout,
2654 m_protocol_id(protocol_id),
2655 m_sendThread(this, max_packet_size, timeout),
2656 m_receiveThread(this, max_packet_size),
2658 m_bc_peerhandler(0),
2659 m_bc_receive_timeout(0),
2660 m_shutting_down(false),
2661 m_next_remote_peer_id(2)
2663 m_udpSocket.setTimeoutMs(5);
2665 m_sendThread.Start();
2666 m_receiveThread.Start();
2669 Connection::Connection(u32 protocol_id, u32 max_packet_size, float timeout,
2670 bool ipv6, PeerHandler *peerhandler) :
2675 m_protocol_id(protocol_id),
2676 m_sendThread(this, max_packet_size, timeout),
2677 m_receiveThread(this, max_packet_size),
2679 m_bc_peerhandler(peerhandler),
2680 m_bc_receive_timeout(0),
2681 m_shutting_down(false),
2682 m_next_remote_peer_id(2)
2685 m_udpSocket.setTimeoutMs(5);
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);
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 assert(node->second->id == 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 assert(node->second->id == 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);
2804 Address peer_address;
2805 //any peer has a primary address this never fails!
2806 peer->getAddress(MTP_PRIMARY, peer_address);
2809 e.peerRemoved(peer_id, timeout, peer_address);
2819 ConnectionEvent Connection::getEvent()
2821 if(m_event_queue.empty()){
2823 e.type = CONNEVENT_NONE;
2826 return m_event_queue.pop_frontNoEx();
2829 ConnectionEvent Connection::waitEvent(u32 timeout_ms)
2832 return m_event_queue.pop_front(timeout_ms);
2833 } catch(ItemNotFoundException &ex){
2835 e.type = CONNEVENT_NONE;
2840 void Connection::putCommand(ConnectionCommand &c)
2842 if (!m_shutting_down)
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 u32 Connection::Receive(u16 &peer_id, SharedBuffer<u8> &data)
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 peer_id = e.peer_id;
2899 data = SharedBuffer<u8>(e.data);
2900 return e.data.getSize();
2901 case CONNEVENT_PEER_ADDED: {
2902 UDPPeer tmp(e.peer_id, e.address, this);
2903 if(m_bc_peerhandler)
2904 m_bc_peerhandler->peerAdded(&tmp);
2906 case CONNEVENT_PEER_REMOVED: {
2907 UDPPeer tmp(e.peer_id, e.address, this);
2908 if(m_bc_peerhandler)
2909 m_bc_peerhandler->deletingPeer(&tmp, e.timeout);
2911 case CONNEVENT_BIND_FAILED:
2912 throw ConnectionBindFailed("Failed to bind socket "
2913 "(port already in use?)");
2916 throw NoIncomingDataException("No incoming data");
2919 void Connection::SendToAll(u8 channelnum, SharedBuffer<u8> data, bool reliable)
2921 assert(channelnum < CHANNEL_COUNT);
2923 ConnectionCommand c;
2924 c.sendToAll(channelnum, data, reliable);
2928 void Connection::Send(u16 peer_id, u8 channelnum,
2929 SharedBuffer<u8> data, bool reliable)
2931 assert(channelnum < CHANNEL_COUNT);
2933 ConnectionCommand c;
2934 c.send(peer_id, channelnum, data, reliable);
2938 Address Connection::GetPeerAddress(u16 peer_id)
2940 PeerHelper peer = getPeerNoEx(peer_id);
2943 throw PeerNotFoundException("No address for peer found!");
2944 Address peer_address;
2945 peer->getAddress(MTP_PRIMARY, peer_address);
2946 return peer_address;
2949 float Connection::getPeerStat(u16 peer_id, rtt_stat_type type)
2951 PeerHelper peer = getPeerNoEx(peer_id);
2952 if (!peer) return -1;
2953 return peer->getStat(type);
2956 float Connection::getLocalStat(rate_stat_type type)
2958 PeerHelper peer = getPeerNoEx(PEER_ID_SERVER);
2961 assert("Connection::getLocalStat we couldn't get our own peer? are you serious???" == 0);
2966 for (u16 j=0; j<CHANNEL_COUNT; j++) {
2969 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getCurrentDownloadRateKB();
2972 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getAvgDownloadRateKB();
2975 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getCurrentIncomingRateKB();
2978 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getAvgIncomingRateKB();
2981 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getAvgLossRateKB();
2984 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getCurrentLossRateKB();
2987 assert("Connection::getLocalStat Invalid stat type" == 0);
2993 u16 Connection::createPeer(Address& sender, MTProtocols protocol, int fd)
2995 // Somebody wants to make a new connection
2997 // Get a unique peer id (2 or higher)
2998 u16 peer_id_new = m_next_remote_peer_id;
2999 u16 overflow = MAX_UDP_PEERS;
3002 Find an unused peer id
3005 JMutexAutoLock lock(m_peers_mutex);
3006 bool out_of_ids = false;
3010 if(m_peers.find(peer_id_new) == m_peers.end())
3012 // Check for overflow
3013 if(peer_id_new == overflow){
3020 errorstream<<getDesc()<<" ran out of peer ids"<<std::endl;
3021 return PEER_ID_INEXISTENT;
3026 peer = new UDPPeer(peer_id_new, sender, this);
3028 m_peers[peer->id] = peer;
3031 m_next_remote_peer_id = (peer_id_new +1) % MAX_UDP_PEERS;
3033 LOG(dout_con<<getDesc()
3034 <<"createPeer(): giving peer_id="<<peer_id_new<<std::endl);
3036 ConnectionCommand cmd;
3037 SharedBuffer<u8> reply(4);
3038 writeU8(&reply[0], TYPE_CONTROL);
3039 writeU8(&reply[1], CONTROLTYPE_SET_PEER_ID);
3040 writeU16(&reply[2], peer_id_new);
3041 cmd.createPeer(peer_id_new,reply);
3042 this->putCommand(cmd);
3044 // Create peer addition event
3046 e.peerAdded(peer_id_new, sender);
3049 // We're now talking to a valid peer_id
3053 void Connection::PrintInfo(std::ostream &out)
3055 m_info_mutex.Lock();
3056 out<<getDesc()<<": ";
3057 m_info_mutex.Unlock();
3060 void Connection::PrintInfo()
3062 PrintInfo(dout_con);
3065 const std::string Connection::getDesc()
3067 return std::string("con(")+
3068 itos(m_udpSocket.GetHandle())+"/"+itos(m_peer_id)+")";
3071 void Connection::DisconnectPeer(u16 peer_id)
3073 ConnectionCommand discon;
3074 discon.disconnect_peer(peer_id);
3078 void Connection::sendAck(u16 peer_id, u8 channelnum, u16 seqnum)
3080 assert(channelnum < CHANNEL_COUNT);
3082 LOG(dout_con<<getDesc()
3083 <<" Queuing ACK command to peer_id: " << peer_id <<
3084 " channel: " << (channelnum & 0xFF) <<
3085 " seqnum: " << seqnum << std::endl);
3087 ConnectionCommand c;
3088 SharedBuffer<u8> ack(4);
3089 writeU8(&ack[0], TYPE_CONTROL);
3090 writeU8(&ack[1], CONTROLTYPE_ACK);
3091 writeU16(&ack[2], seqnum);
3093 c.ack(peer_id, channelnum, ack);
3095 m_sendThread.Trigger();
3098 UDPPeer* Connection::createServerPeer(Address& address)
3100 if (getPeerNoEx(PEER_ID_SERVER) != 0)
3102 throw ConnectionException("Already connected to a server");
3105 UDPPeer *peer = new UDPPeer(PEER_ID_SERVER, address, this);
3108 JMutexAutoLock lock(m_peers_mutex);
3109 m_peers[peer->id] = peer;
3115 std::list<u16> Connection::getPeerIDs()
3117 std::list<u16> retval;
3119 JMutexAutoLock lock(m_peers_mutex);
3120 for(std::map<u16, Peer*>::iterator j = m_peers.begin();
3121 j != m_peers.end(); ++j)
3123 retval.push_back(j->first);