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(derr_con);
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());
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());
1425 LOG(derr_con<<m_connection->getDesc()
1426 <<"RE-SENDING timed-out RELIABLE to "
1427 << k->address.serializeString()
1428 << "(t/o="<<resend_timeout<<"): "
1429 <<"from_peer_id="<<peer_id
1430 <<", channel="<<((int)channelnum&0xff)
1431 <<", seqnum="<<seqnum
1436 // do not handle rtt here as we can't decide if this packet was
1437 // lost or really takes more time to transmit
1439 channel->UpdateTimers(dtime,dynamic_cast<UDPPeer*>(&peer)->getLegacyPeer());
1442 /* send ping if necessary */
1443 if (dynamic_cast<UDPPeer*>(&peer)->Ping(dtime,data)) {
1444 LOG(dout_con<<m_connection->getDesc()
1445 <<"Sending ping for peer_id: "
1446 << dynamic_cast<UDPPeer*>(&peer)->id <<std::endl);
1447 /* this may fail if there ain't a sequence number left */
1448 if (!rawSendAsPacket(dynamic_cast<UDPPeer*>(&peer)->id, 0, data, true))
1450 //retrigger with reduced ping interval
1451 dynamic_cast<UDPPeer*>(&peer)->Ping(4.0,data);
1455 dynamic_cast<UDPPeer*>(&peer)->RunCommandQueues(m_max_packet_size,
1456 m_max_commands_per_iteration,
1457 m_max_packets_requeued);
1460 // Remove timed out peers
1461 for(std::list<u16>::iterator i = timeouted_peers.begin();
1462 i != timeouted_peers.end(); ++i)
1464 LOG(derr_con<<m_connection->getDesc()
1465 <<"RunTimeouts(): Removing peer "<<(*i)<<std::endl);
1466 m_connection->deletePeer(*i, true);
1470 void ConnectionSendThread::rawSend(const BufferedPacket &packet)
1473 m_connection->m_udpSocket.Send(packet.address, *packet.data,
1474 packet.data.getSize());
1475 LOG(dout_con <<m_connection->getDesc()
1476 << " rawSend: " << packet.data.getSize()
1477 << " bytes sent" << std::endl);
1478 } catch(SendFailedException &e){
1479 LOG(derr_con<<m_connection->getDesc()
1480 <<"Connection::rawSend(): SendFailedException: "
1481 <<packet.address.serializeString()<<std::endl);
1485 void ConnectionSendThread::sendAsPacketReliable(BufferedPacket& p, Channel* channel)
1488 p.absolute_send_time = porting::getTimeMs();
1489 // Buffer the packet
1490 channel->outgoing_reliables_sent.insert(p,
1491 (channel->readOutgoingSequenceNumber() - MAX_RELIABLE_WINDOW_SIZE)
1492 % (MAX_RELIABLE_WINDOW_SIZE+1));
1494 catch(AlreadyExistsException &e)
1496 LOG(derr_con<<m_connection->getDesc()
1497 <<"WARNING: Going to send a reliable packet"
1498 <<" in outgoing buffer" <<std::endl);
1506 bool ConnectionSendThread::rawSendAsPacket(u16 peer_id, u8 channelnum,
1507 SharedBuffer<u8> data, bool reliable)
1509 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
1511 LOG(dout_con<<m_connection->getDesc()
1512 <<" INFO: dropped packet for non existent peer_id: "
1513 << peer_id << std::endl);
1514 assert(reliable && "trying to send raw packet reliable but no peer found!");
1517 Channel *channel = &(dynamic_cast<UDPPeer*>(&peer)->channels[channelnum]);
1521 bool have_sequence_number_for_raw_packet = true;
1523 channel->getOutgoingSequenceNumber(have_sequence_number_for_raw_packet);
1525 if (!have_sequence_number_for_raw_packet)
1528 SharedBuffer<u8> reliable = makeReliablePacket(data, seqnum);
1529 Address peer_address;
1530 peer->getAddress(MTP_MINETEST_RELIABLE_UDP, peer_address);
1532 // Add base headers and make a packet
1533 BufferedPacket p = con::makePacket(peer_address, reliable,
1534 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1537 // first check if our send window is already maxed out
1538 if (channel->outgoing_reliables_sent.size()
1539 < channel->getWindowSize()) {
1540 LOG(dout_con<<m_connection->getDesc()
1541 <<" INFO: sending a reliable packet to peer_id " << peer_id
1542 <<" channel: " << channelnum
1543 <<" seqnum: " << seqnum << std::endl);
1544 sendAsPacketReliable(p,channel);
1548 LOG(dout_con<<m_connection->getDesc()
1549 <<" INFO: queueing reliable packet for peer_id: " << peer_id
1550 <<" channel: " << channelnum
1551 <<" seqnum: " << seqnum << std::endl);
1552 channel->queued_reliables.push_back(p);
1558 Address peer_address;
1560 if (peer->getAddress(MTP_UDP, peer_address))
1562 // Add base headers and make a packet
1563 BufferedPacket p = con::makePacket(peer_address, data,
1564 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1572 LOG(dout_con<<m_connection->getDesc()
1573 <<" INFO: dropped unreliable packet for peer_id: " << peer_id
1574 <<" because of (yet) missing udp address" << std::endl);
1583 void ConnectionSendThread::processReliableCommand(ConnectionCommand &c)
1589 LOG(dout_con<<m_connection->getDesc()
1590 <<"UDP processing reliable CONNCMD_NONE"<<std::endl);
1594 LOG(dout_con<<m_connection->getDesc()
1595 <<"UDP processing reliable CONNCMD_SEND"<<std::endl);
1599 case CONNCMD_SEND_TO_ALL:
1600 LOG(dout_con<<m_connection->getDesc()
1601 <<"UDP processing CONNCMD_SEND_TO_ALL"<<std::endl);
1602 sendToAllReliable(c);
1605 case CONCMD_CREATE_PEER:
1606 LOG(dout_con<<m_connection->getDesc()
1607 <<"UDP processing reliable CONCMD_CREATE_PEER"<<std::endl);
1608 if (!rawSendAsPacket(c.peer_id,c.channelnum,c.data,c.reliable))
1610 /* put to queue if we couldn't send it immediately */
1615 case CONCMD_DISABLE_LEGACY:
1616 LOG(dout_con<<m_connection->getDesc()
1617 <<"UDP processing reliable CONCMD_DISABLE_LEGACY"<<std::endl);
1618 if (!rawSendAsPacket(c.peer_id,c.channelnum,c.data,c.reliable))
1620 /* put to queue if we couldn't send it immediately */
1626 case CONNCMD_CONNECT:
1627 case CONNCMD_DISCONNECT:
1629 assert("Got command that shouldn't be reliable as reliable command" == 0);
1631 LOG(dout_con<<m_connection->getDesc()
1632 <<" Invalid reliable command type: " << c.type <<std::endl);
1637 void ConnectionSendThread::processNonReliableCommand(ConnectionCommand &c)
1639 assert(!c.reliable);
1643 LOG(dout_con<<m_connection->getDesc()
1644 <<" UDP processing CONNCMD_NONE"<<std::endl);
1647 LOG(dout_con<<m_connection->getDesc()
1648 <<" UDP processing CONNCMD_SERVE port="
1649 <<c.address.serializeString()<<std::endl);
1652 case CONNCMD_CONNECT:
1653 LOG(dout_con<<m_connection->getDesc()
1654 <<" UDP processing CONNCMD_CONNECT"<<std::endl);
1657 case CONNCMD_DISCONNECT:
1658 LOG(dout_con<<m_connection->getDesc()
1659 <<" UDP processing CONNCMD_DISCONNECT"<<std::endl);
1662 case CONNCMD_DISCONNECT_PEER:
1663 LOG(dout_con<<m_connection->getDesc()
1664 <<" UDP processing CONNCMD_DISCONNECT_PEER"<<std::endl);
1665 disconnect_peer(c.peer_id);
1668 LOG(dout_con<<m_connection->getDesc()
1669 <<" UDP processing CONNCMD_SEND"<<std::endl);
1670 send(c.peer_id, c.channelnum, c.data);
1672 case CONNCMD_SEND_TO_ALL:
1673 LOG(dout_con<<m_connection->getDesc()
1674 <<" UDP processing CONNCMD_SEND_TO_ALL"<<std::endl);
1675 sendToAll(c.channelnum, c.data);
1678 LOG(dout_con<<m_connection->getDesc()
1679 <<" UDP processing CONCMD_ACK"<<std::endl);
1680 sendAsPacket(c.peer_id,c.channelnum,c.data,true);
1682 case CONCMD_CREATE_PEER:
1683 assert("Got command that should be reliable as unreliable command" == 0);
1685 LOG(dout_con<<m_connection->getDesc()
1686 <<" Invalid command type: " << c.type <<std::endl);
1690 void ConnectionSendThread::serve(Address bind_address)
1692 LOG(dout_con<<m_connection->getDesc()
1693 <<"UDP serving at port " << bind_address.serializeString() <<std::endl);
1695 m_connection->m_udpSocket.Bind(bind_address);
1696 m_connection->SetPeerID(PEER_ID_SERVER);
1698 catch(SocketException &e){
1702 m_connection->putEvent(ce);
1706 void ConnectionSendThread::connect(Address address)
1708 LOG(dout_con<<m_connection->getDesc()<<" connecting to "<<address.serializeString()
1709 <<":"<<address.getPort()<<std::endl);
1711 UDPPeer *peer = m_connection->createServerPeer(address);
1715 e.peerAdded(peer->id, peer->address);
1716 m_connection->putEvent(e);
1720 if (address.isIPv6())
1721 bind_addr.setAddress((IPv6AddressBytes*) NULL);
1723 bind_addr.setAddress(0,0,0,0);
1725 m_connection->m_udpSocket.Bind(bind_addr);
1727 // Send a dummy packet to server with peer_id = PEER_ID_INEXISTENT
1728 m_connection->SetPeerID(PEER_ID_INEXISTENT);
1729 SharedBuffer<u8> data(0);
1730 m_connection->Send(PEER_ID_SERVER, 0, data, true);
1733 void ConnectionSendThread::disconnect()
1735 LOG(dout_con<<m_connection->getDesc()<<" disconnecting"<<std::endl);
1737 // Create and send DISCO packet
1738 SharedBuffer<u8> data(2);
1739 writeU8(&data[0], TYPE_CONTROL);
1740 writeU8(&data[1], CONTROLTYPE_DISCO);
1744 std::list<u16> peerids = m_connection->getPeerIDs();
1746 for (std::list<u16>::iterator i = peerids.begin();
1750 sendAsPacket(*i, 0,data,false);
1754 void ConnectionSendThread::disconnect_peer(u16 peer_id)
1756 LOG(dout_con<<m_connection->getDesc()<<" disconnecting peer"<<std::endl);
1758 // Create and send DISCO packet
1759 SharedBuffer<u8> data(2);
1760 writeU8(&data[0], TYPE_CONTROL);
1761 writeU8(&data[1], CONTROLTYPE_DISCO);
1762 sendAsPacket(peer_id, 0,data,false);
1764 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
1769 if (dynamic_cast<UDPPeer*>(&peer) == 0)
1774 dynamic_cast<UDPPeer*>(&peer)->m_pending_disconnect = true;
1777 void ConnectionSendThread::send(u16 peer_id, u8 channelnum,
1778 SharedBuffer<u8> data)
1780 assert(channelnum < CHANNEL_COUNT);
1782 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
1785 LOG(dout_con<<m_connection->getDesc()<<" peer: peer_id="<<peer_id
1786 << ">>>NOT<<< found on sending packet"
1787 << ", channel " << (channelnum % 0xFF)
1788 << ", size: " << data.getSize() <<std::endl);
1792 LOG(dout_con<<m_connection->getDesc()<<" sending to peer_id="<<peer_id
1793 << ", channel " << (channelnum % 0xFF)
1794 << ", size: " << data.getSize() <<std::endl);
1796 u16 split_sequence_number = peer->getNextSplitSequenceNumber(channelnum);
1798 u32 chunksize_max = m_max_packet_size - BASE_HEADER_SIZE;
1799 std::list<SharedBuffer<u8> > originals;
1801 originals = makeAutoSplitPacket(data, chunksize_max,split_sequence_number);
1803 peer->setNextSplitSequenceNumber(channelnum,split_sequence_number);
1805 for(std::list<SharedBuffer<u8> >::iterator i = originals.begin();
1806 i != originals.end(); ++i)
1808 SharedBuffer<u8> original = *i;
1809 sendAsPacket(peer_id, channelnum, original);
1813 void ConnectionSendThread::sendReliable(ConnectionCommand &c)
1815 PeerHelper peer = m_connection->getPeerNoEx(c.peer_id);
1819 peer->PutReliableSendCommand(c,m_max_packet_size);
1822 void ConnectionSendThread::sendToAll(u8 channelnum, SharedBuffer<u8> data)
1824 std::list<u16> peerids = m_connection->getPeerIDs();
1826 for (std::list<u16>::iterator i = peerids.begin();
1830 send(*i, channelnum, data);
1834 void ConnectionSendThread::sendToAllReliable(ConnectionCommand &c)
1836 std::list<u16> peerids = m_connection->getPeerIDs();
1838 for (std::list<u16>::iterator i = peerids.begin();
1842 PeerHelper peer = m_connection->getPeerNoEx(*i);
1847 peer->PutReliableSendCommand(c,m_max_packet_size);
1851 void ConnectionSendThread::sendPackets(float dtime)
1853 std::list<u16> peerIds = m_connection->getPeerIDs();
1854 std::list<u16> pendingDisconnect;
1855 std::map<u16,bool> pending_unreliable;
1857 for(std::list<u16>::iterator
1858 j = peerIds.begin();
1859 j != peerIds.end(); ++j)
1861 PeerHelper peer = m_connection->getPeerNoEx(*j);
1862 //peer may have been removed
1864 LOG(dout_con<<m_connection->getDesc()<< " Peer not found: peer_id=" << *j << std::endl);
1867 peer->m_increment_packets_remaining = m_iteration_packets_avaialble/m_connection->m_peers.size();
1869 if (dynamic_cast<UDPPeer*>(&peer) == 0)
1874 if (dynamic_cast<UDPPeer*>(&peer)->m_pending_disconnect)
1876 pendingDisconnect.push_back(*j);
1879 PROFILE(std::stringstream peerIdentifier);
1880 PROFILE(peerIdentifier << "sendPackets[" << m_connection->getDesc() << ";" << *j << ";RELIABLE]");
1881 PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier.str(), SPT_AVG));
1883 LOG(dout_con<<m_connection->getDesc()
1884 << " Handle per peer queues: peer_id=" << *j
1885 << " packet quota: " << peer->m_increment_packets_remaining << std::endl);
1886 // first send queued reliable packets for all peers (if possible)
1887 for (unsigned int i=0; i < CHANNEL_COUNT; i++)
1889 u16 next_to_ack = 0;
1890 dynamic_cast<UDPPeer*>(&peer)->channels[i].outgoing_reliables_sent.getFirstSeqnum(next_to_ack);
1891 u16 next_to_receive = 0;
1892 dynamic_cast<UDPPeer*>(&peer)->channels[i].incoming_reliables.getFirstSeqnum(next_to_receive);
1894 LOG(dout_con<<m_connection->getDesc()<< "\t channel: "
1895 << i << ", peer quota:"
1896 << peer->m_increment_packets_remaining
1898 << "\t\t\treliables on wire: "
1899 << dynamic_cast<UDPPeer*>(&peer)->channels[i].outgoing_reliables_sent.size()
1900 << ", waiting for ack for " << next_to_ack
1902 << "\t\t\tincoming_reliables: "
1903 << dynamic_cast<UDPPeer*>(&peer)->channels[i].incoming_reliables.size()
1904 << ", next reliable packet: "
1905 << dynamic_cast<UDPPeer*>(&peer)->channels[i].readNextIncomingSeqNum()
1906 << ", next queued: " << next_to_receive
1908 << "\t\t\treliables queued : "
1909 << dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.size()
1911 << "\t\t\tqueued commands : "
1912 << dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_commands.size()
1915 while ((dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.size() > 0) &&
1916 (dynamic_cast<UDPPeer*>(&peer)->channels[i].outgoing_reliables_sent.size()
1917 < dynamic_cast<UDPPeer*>(&peer)->channels[i].getWindowSize())&&
1918 (peer->m_increment_packets_remaining > 0))
1920 BufferedPacket p = dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.pop_front();
1921 Channel* channel = &(dynamic_cast<UDPPeer*>(&peer)->channels[i]);
1922 LOG(dout_con<<m_connection->getDesc()
1923 <<" INFO: sending a queued reliable packet "
1925 <<", seqnum: " << readU16(&p.data[BASE_HEADER_SIZE+1])
1927 sendAsPacketReliable(p,channel);
1928 peer->m_increment_packets_remaining--;
1933 if (m_outgoing_queue.size())
1935 LOG(dout_con<<m_connection->getDesc()
1936 << " Handle non reliable queue ("
1937 << m_outgoing_queue.size() << " pkts)" << std::endl);
1940 unsigned int initial_queuesize = m_outgoing_queue.size();
1941 /* send non reliable packets*/
1942 for(unsigned int i=0;i < initial_queuesize;i++) {
1943 OutgoingPacket packet = m_outgoing_queue.pop_front();
1945 assert(!packet.reliable &&
1946 "reliable packets are not allowed in outgoing queue!");
1948 PeerHelper peer = m_connection->getPeerNoEx(packet.peer_id);
1950 LOG(dout_con<<m_connection->getDesc()
1951 <<" Outgoing queue: peer_id="<<packet.peer_id
1952 << ">>>NOT<<< found on sending packet"
1953 << ", channel " << (packet.channelnum % 0xFF)
1954 << ", size: " << packet.data.getSize() <<std::endl);
1957 /* send acks immediately */
1958 else if (packet.ack)
1960 rawSendAsPacket(packet.peer_id, packet.channelnum,
1961 packet.data, packet.reliable);
1962 peer->m_increment_packets_remaining =
1963 MYMIN(0,peer->m_increment_packets_remaining--);
1966 ( peer->m_increment_packets_remaining > 0) ||
1968 rawSendAsPacket(packet.peer_id, packet.channelnum,
1969 packet.data, packet.reliable);
1970 peer->m_increment_packets_remaining--;
1973 m_outgoing_queue.push_back(packet);
1974 pending_unreliable[packet.peer_id] = true;
1978 for(std::list<u16>::iterator
1979 k = pendingDisconnect.begin();
1980 k != pendingDisconnect.end(); ++k)
1982 if (!pending_unreliable[*k])
1984 m_connection->deletePeer(*k,false);
1989 void ConnectionSendThread::sendAsPacket(u16 peer_id, u8 channelnum,
1990 SharedBuffer<u8> data, bool ack)
1992 OutgoingPacket packet(peer_id, channelnum, data, false, ack);
1993 m_outgoing_queue.push_back(packet);
1996 ConnectionReceiveThread::ConnectionReceiveThread(Connection* parent,
1997 unsigned int max_packet_size) :
1998 m_connection(parent)
2002 void * ConnectionReceiveThread::Thread()
2005 log_register_thread("ConnectionReceive");
2007 LOG(dout_con<<m_connection->getDesc()
2008 <<"ConnectionReceive thread started"<<std::endl);
2010 PROFILE(std::stringstream ThreadIdentifier);
2011 PROFILE(ThreadIdentifier << "ConnectionReceive: [" << m_connection->getDesc() << "]");
2013 porting::setThreadName("ConnectionReceive");
2015 #ifdef DEBUG_CONNECTION_KBPS
2016 u32 curtime = porting::getTimeMs();
2017 u32 lasttime = curtime;
2018 float debug_print_timer = 0.0;
2021 while(!StopRequested()) {
2022 BEGIN_DEBUG_EXCEPTION_HANDLER
2023 PROFILE(ScopeProfiler sp(g_profiler, ThreadIdentifier.str(), SPT_AVG));
2025 #ifdef DEBUG_CONNECTION_KBPS
2027 curtime = porting::getTimeMs();
2028 float dtime = CALC_DTIME(lasttime,curtime);
2031 /* receive packets */
2034 #ifdef DEBUG_CONNECTION_KBPS
2035 debug_print_timer += dtime;
2036 if (debug_print_timer > 20.0) {
2037 debug_print_timer -= 20.0;
2039 std::list<u16> peerids = m_connection->getPeerIDs();
2041 for (std::list<u16>::iterator i = peerids.begin();
2045 PeerHelper peer = m_connection->getPeerNoEx(*i);
2049 float peer_current = 0.0;
2050 float peer_loss = 0.0;
2051 float avg_rate = 0.0;
2052 float avg_loss = 0.0;
2054 for(u16 j=0; j<CHANNEL_COUNT; j++)
2056 peer_current +=peer->channels[j].getCurrentDownloadRateKB();
2057 peer_loss += peer->channels[j].getCurrentLossRateKB();
2058 avg_rate += peer->channels[j].getAvgDownloadRateKB();
2059 avg_loss += peer->channels[j].getAvgLossRateKB();
2062 std::stringstream output;
2063 output << std::fixed << std::setprecision(1);
2064 output << "OUT to Peer " << *i << " RATES (good / loss) " << std::endl;
2065 output << "\tcurrent (sum): " << peer_current << "kb/s "<< peer_loss << "kb/s" << std::endl;
2066 output << "\taverage (sum): " << avg_rate << "kb/s "<< avg_loss << "kb/s" << std::endl;
2067 output << std::setfill(' ');
2068 for(u16 j=0; j<CHANNEL_COUNT; j++)
2070 output << "\tcha " << j << ":"
2071 << " CUR: " << std::setw(6) << peer->channels[j].getCurrentDownloadRateKB() <<"kb/s"
2072 << " AVG: " << std::setw(6) << peer->channels[j].getAvgDownloadRateKB() <<"kb/s"
2073 << " MAX: " << std::setw(6) << peer->channels[j].getMaxDownloadRateKB() <<"kb/s"
2075 << " CUR: " << std::setw(6) << peer->channels[j].getCurrentLossRateKB() <<"kb/s"
2076 << " AVG: " << std::setw(6) << peer->channels[j].getAvgLossRateKB() <<"kb/s"
2077 << " MAX: " << std::setw(6) << peer->channels[j].getMaxLossRateKB() <<"kb/s"
2078 << " / WS: " << peer->channels[j].getWindowSize()
2082 fprintf(stderr,"%s\n",output.str().c_str());
2086 END_DEBUG_EXCEPTION_HANDLER(derr_con);
2088 PROFILE(g_profiler->remove(ThreadIdentifier.str()));
2092 // Receive packets from the network and buffers and create ConnectionEvents
2093 void ConnectionReceiveThread::receive()
2095 // use IPv6 minimum allowed MTU as receive buffer size as this is
2096 // theoretical reliable upper boundary of a udp packet for all IPv6 enabled
2098 unsigned int packet_maxsize = 1500;
2099 SharedBuffer<u8> packetdata(packet_maxsize);
2101 bool packet_queued = true;
2103 unsigned int loop_count = 0;
2105 /* first of all read packets from socket */
2106 /* check for incoming data available */
2107 while( (loop_count < 10) &&
2108 (m_connection->m_udpSocket.WaitData(50)))
2114 bool no_data_left = false;
2116 SharedBuffer<u8> resultdata;
2117 while(!no_data_left)
2120 no_data_left = !getFromBuffers(peer_id, resultdata);
2121 if (!no_data_left) {
2123 e.dataReceived(peer_id, resultdata);
2124 m_connection->putEvent(e);
2127 catch(ProcessedSilentlyException &e) {
2128 /* try reading again */
2131 packet_queued = false;
2135 s32 received_size = m_connection->m_udpSocket.Receive(sender, *packetdata, packet_maxsize);
2137 if ((received_size < 0) ||
2138 (received_size < BASE_HEADER_SIZE) ||
2139 (readU32(&packetdata[0]) != m_connection->GetProtocolID()))
2141 LOG(derr_con<<m_connection->getDesc()
2142 <<"Receive(): Invalid incoming packet, "
2143 <<"size: " << received_size
2144 <<", protocol: " << readU32(&packetdata[0]) <<std::endl);
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)
2163 peer_id = m_connection->lookupPeer(sender);
2166 /* The peer was not found in our lists. Add it. */
2167 if(peer_id == PEER_ID_INEXISTENT)
2169 peer_id = m_connection->createPeer(sender, MTP_MINETEST_RELIABLE_UDP, 0);
2172 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
2175 LOG(dout_con<<m_connection->getDesc()
2176 <<" got packet from unknown peer_id: "
2177 <<peer_id<<" Ignoring."<<std::endl);
2181 // Validate peer address
2183 Address peer_address;
2185 if (peer->getAddress(MTP_UDP, peer_address)) {
2186 if (peer_address != sender) {
2187 LOG(derr_con<<m_connection->getDesc()
2188 <<m_connection->getDesc()
2189 <<" Peer "<<peer_id<<" sending from different address."
2190 " Ignoring."<<std::endl);
2196 bool invalid_address = true;
2197 if (invalid_address) {
2198 LOG(derr_con<<m_connection->getDesc()
2199 <<m_connection->getDesc()
2200 <<" Peer "<<peer_id<<" unknown."
2201 " Ignoring."<<std::endl);
2207 /* mark peer as seen with id */
2208 if (!(packet_peer_id == PEER_ID_INEXISTENT))
2209 peer->setSentWithID();
2211 peer->ResetTimeout();
2213 Channel *channel = 0;
2215 if (dynamic_cast<UDPPeer*>(&peer) != 0)
2217 channel = &(dynamic_cast<UDPPeer*>(&peer)->channels[channelnum]);
2221 channel->UpdateBytesReceived(received_size);
2224 // Throw the received packet to channel->processPacket()
2226 // Make a new SharedBuffer from the data without the base headers
2227 SharedBuffer<u8> strippeddata(received_size - BASE_HEADER_SIZE);
2228 memcpy(*strippeddata, &packetdata[BASE_HEADER_SIZE],
2229 strippeddata.getSize());
2232 // Process it (the result is some data with no headers made by us)
2233 SharedBuffer<u8> resultdata = processPacket
2234 (channel, strippeddata, peer_id, channelnum, false);
2236 LOG(dout_con<<m_connection->getDesc()
2237 <<" ProcessPacket from peer_id: " << peer_id
2238 << ",channel: " << (channelnum & 0xFF) << ", returned "
2239 << resultdata.getSize() << " bytes" <<std::endl);
2242 e.dataReceived(peer_id, resultdata);
2243 m_connection->putEvent(e);
2244 }catch(ProcessedSilentlyException &e){
2245 }catch(ProcessedQueued &e){
2246 packet_queued = true;
2248 }catch(InvalidIncomingDataException &e){
2250 catch(ProcessedSilentlyException &e){
2255 bool ConnectionReceiveThread::getFromBuffers(u16 &peer_id, SharedBuffer<u8> &dst)
2257 std::list<u16> peerids = m_connection->getPeerIDs();
2259 for(std::list<u16>::iterator j = peerids.begin();
2260 j != peerids.end(); ++j)
2262 PeerHelper peer = m_connection->getPeerNoEx(*j);
2266 if(dynamic_cast<UDPPeer*>(&peer) == 0)
2269 for(u16 i=0; i<CHANNEL_COUNT; i++)
2271 Channel *channel = &(dynamic_cast<UDPPeer*>(&peer))->channels[i];
2273 SharedBuffer<u8> resultdata;
2274 bool got = checkIncomingBuffers(channel, peer_id, resultdata);
2284 bool ConnectionReceiveThread::checkIncomingBuffers(Channel *channel,
2285 u16 &peer_id, SharedBuffer<u8> &dst)
2287 u16 firstseqnum = 0;
2288 if (channel->incoming_reliables.getFirstSeqnum(firstseqnum))
2290 if(firstseqnum == channel->readNextIncomingSeqNum())
2292 BufferedPacket p = channel->incoming_reliables.popFirst();
2293 peer_id = readPeerId(*p.data);
2294 u8 channelnum = readChannel(*p.data);
2295 u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]);
2297 LOG(dout_con<<m_connection->getDesc()
2298 <<"UNBUFFERING TYPE_RELIABLE"
2299 <<" seqnum="<<seqnum
2300 <<" peer_id="<<peer_id
2301 <<" channel="<<((int)channelnum&0xff)
2304 channel->incNextIncomingSeqNum();
2306 u32 headers_size = BASE_HEADER_SIZE + RELIABLE_HEADER_SIZE;
2307 // Get out the inside packet and re-process it
2308 SharedBuffer<u8> payload(p.data.getSize() - headers_size);
2309 memcpy(*payload, &p.data[headers_size], payload.getSize());
2311 dst = processPacket(channel, payload, peer_id, channelnum, true);
2318 SharedBuffer<u8> ConnectionReceiveThread::processPacket(Channel *channel,
2319 SharedBuffer<u8> packetdata, u16 peer_id, u8 channelnum, bool reliable)
2321 PeerHelper peer = m_connection->getPeer(peer_id);
2323 if(packetdata.getSize() < 1)
2324 throw InvalidIncomingDataException("packetdata.getSize() < 1");
2326 u8 type = readU8(&(packetdata[0]));
2328 if(type == TYPE_CONTROL)
2330 if(packetdata.getSize() < 2)
2331 throw InvalidIncomingDataException("packetdata.getSize() < 2");
2333 u8 controltype = readU8(&(packetdata[1]));
2335 if( (controltype == CONTROLTYPE_ACK)
2336 && (peer_id <= MAX_UDP_PEERS))
2338 assert(channel != 0);
2339 if(packetdata.getSize() < 4)
2340 throw InvalidIncomingDataException
2341 ("packetdata.getSize() < 4 (ACK header size)");
2343 u16 seqnum = readU16(&packetdata[2]);
2344 LOG(dout_con<<m_connection->getDesc()
2345 <<" [ CONTROLTYPE_ACK: channelnum="
2346 <<((int)channelnum&0xff)<<", peer_id="<<peer_id
2347 <<", seqnum="<<seqnum<< " ]"<<std::endl);
2351 channel->outgoing_reliables_sent.popSeqnum(seqnum);
2352 // Get round trip time
2353 unsigned int current_time = porting::getTimeMs();
2355 if (current_time > p.absolute_send_time)
2357 float rtt = (current_time - p.absolute_send_time) / 1000.0;
2359 // Let peer calculate stuff according to it
2360 // (avg_rtt and resend_timeout)
2361 dynamic_cast<UDPPeer*>(&peer)->reportRTT(rtt);
2363 else if (p.totaltime > 0)
2365 float rtt = p.totaltime;
2367 // Let peer calculate stuff according to it
2368 // (avg_rtt and resend_timeout)
2369 dynamic_cast<UDPPeer*>(&peer)->reportRTT(rtt);
2371 //put bytes for max bandwidth calculation
2372 channel->UpdateBytesSent(p.data.getSize(),1);
2373 if (channel->outgoing_reliables_sent.size() == 0)
2375 m_connection->TriggerSend();
2378 catch(NotFoundException &e){
2379 LOG(derr_con<<m_connection->getDesc()
2380 <<"WARNING: ACKed packet not "
2383 channel->UpdatePacketTooLateCounter();
2385 throw ProcessedSilentlyException("Got an ACK");
2387 else if((controltype == CONTROLTYPE_SET_PEER_ID)
2388 && (peer_id <= MAX_UDP_PEERS))
2390 // Got a packet to set our peer id
2391 if(packetdata.getSize() < 4)
2392 throw InvalidIncomingDataException
2393 ("packetdata.getSize() < 4 (SET_PEER_ID header size)");
2394 u16 peer_id_new = readU16(&packetdata[2]);
2395 LOG(dout_con<<m_connection->getDesc()
2396 <<"Got new peer id: "<<peer_id_new<<"... "<<std::endl);
2398 if(m_connection->GetPeerID() != PEER_ID_INEXISTENT)
2400 LOG(derr_con<<m_connection->getDesc()
2401 <<"WARNING: Not changing"
2402 " existing peer id."<<std::endl);
2406 LOG(dout_con<<m_connection->getDesc()<<"changing own peer id"<<std::endl);
2407 m_connection->SetPeerID(peer_id_new);
2410 ConnectionCommand cmd;
2412 SharedBuffer<u8> reply(2);
2413 writeU8(&reply[0], TYPE_CONTROL);
2414 writeU8(&reply[1], CONTROLTYPE_ENABLE_BIG_SEND_WINDOW);
2415 cmd.disableLegacy(PEER_ID_SERVER,reply);
2416 m_connection->putCommand(cmd);
2418 throw ProcessedSilentlyException("Got a SET_PEER_ID");
2420 else if((controltype == CONTROLTYPE_PING)
2421 && (peer_id <= MAX_UDP_PEERS))
2423 // Just ignore it, the incoming data already reset
2424 // the timeout counter
2425 LOG(dout_con<<m_connection->getDesc()<<"PING"<<std::endl);
2426 throw ProcessedSilentlyException("Got a PING");
2428 else if(controltype == CONTROLTYPE_DISCO)
2430 // Just ignore it, the incoming data already reset
2431 // the timeout counter
2432 LOG(dout_con<<m_connection->getDesc()
2433 <<"DISCO: Removing peer "<<(peer_id)<<std::endl);
2435 if(m_connection->deletePeer(peer_id, false) == false)
2437 derr_con<<m_connection->getDesc()
2438 <<"DISCO: Peer not found"<<std::endl;
2441 throw ProcessedSilentlyException("Got a DISCO");
2443 else if((controltype == CONTROLTYPE_ENABLE_BIG_SEND_WINDOW)
2444 && (peer_id <= MAX_UDP_PEERS))
2446 dynamic_cast<UDPPeer*>(&peer)->setNonLegacyPeer();
2447 throw ProcessedSilentlyException("Got non legacy control");
2450 LOG(derr_con<<m_connection->getDesc()
2451 <<"INVALID TYPE_CONTROL: invalid controltype="
2452 <<((int)controltype&0xff)<<std::endl);
2453 throw InvalidIncomingDataException("Invalid control type");
2456 else if(type == TYPE_ORIGINAL)
2458 if(packetdata.getSize() <= ORIGINAL_HEADER_SIZE)
2459 throw InvalidIncomingDataException
2460 ("packetdata.getSize() <= ORIGINAL_HEADER_SIZE");
2461 LOG(dout_con<<m_connection->getDesc()
2462 <<"RETURNING TYPE_ORIGINAL to user"
2464 // Get the inside packet out and return it
2465 SharedBuffer<u8> payload(packetdata.getSize() - ORIGINAL_HEADER_SIZE);
2466 memcpy(*payload, &(packetdata[ORIGINAL_HEADER_SIZE]), payload.getSize());
2469 else if(type == TYPE_SPLIT)
2471 Address peer_address;
2473 if (peer->getAddress(MTP_UDP, peer_address)) {
2475 // We have to create a packet again for buffering
2476 // This isn't actually too bad an idea.
2477 BufferedPacket packet = makePacket(
2480 m_connection->GetProtocolID(),
2484 // Buffer the packet
2485 SharedBuffer<u8> data =
2486 peer->addSpiltPacket(channelnum,packet,reliable);
2488 if(data.getSize() != 0)
2490 LOG(dout_con<<m_connection->getDesc()
2491 <<"RETURNING TYPE_SPLIT: Constructed full data, "
2492 <<"size="<<data.getSize()<<std::endl);
2495 LOG(dout_con<<m_connection->getDesc()<<"BUFFERED TYPE_SPLIT"<<std::endl);
2496 throw ProcessedSilentlyException("Buffered a split packet chunk");
2499 //TODO throw some error
2502 else if((peer_id <= MAX_UDP_PEERS) && (type == TYPE_RELIABLE))
2504 assert(channel != 0);
2505 // Recursive reliable packets not allowed
2507 throw InvalidIncomingDataException("Found nested reliable packets");
2509 if(packetdata.getSize() < RELIABLE_HEADER_SIZE)
2510 throw InvalidIncomingDataException
2511 ("packetdata.getSize() < RELIABLE_HEADER_SIZE");
2513 u16 seqnum = readU16(&packetdata[1]);
2514 bool is_future_packet = false;
2515 bool is_old_packet = false;
2517 /* packet is within our receive window send ack */
2518 if (seqnum_in_window(seqnum, channel->readNextIncomingSeqNum(),MAX_RELIABLE_WINDOW_SIZE))
2520 m_connection->sendAck(peer_id,channelnum,seqnum);
2523 is_future_packet = seqnum_higher(seqnum, channel->readNextIncomingSeqNum());
2524 is_old_packet = seqnum_higher(channel->readNextIncomingSeqNum(), seqnum);
2527 /* packet is not within receive window, don't send ack. *
2528 * if this was a valid packet it's gonna be retransmitted */
2529 if (is_future_packet)
2531 throw ProcessedSilentlyException("Received packet newer then expected, not sending ack");
2534 /* seems like our ack was lost, send another one for a old packet */
2537 LOG(dout_con<<m_connection->getDesc()
2538 << "RE-SENDING ACK: peer_id: " << peer_id
2539 << ", channel: " << (channelnum&0xFF)
2540 << ", seqnum: " << seqnum << std::endl;)
2541 m_connection->sendAck(peer_id,channelnum,seqnum);
2543 // we already have this packet so this one was on wire at least
2544 // the current timeout
2545 dynamic_cast<UDPPeer*>(&peer)->reportRTT(dynamic_cast<UDPPeer*>(&peer)->getResendTimeout());
2547 throw ProcessedSilentlyException("Retransmitting ack for old packet");
2551 if (seqnum != channel->readNextIncomingSeqNum())
2553 Address peer_address;
2555 // this is a reliable packet so we have a udp address for sure
2556 peer->getAddress(MTP_MINETEST_RELIABLE_UDP, peer_address);
2557 // This one comes later, buffer it.
2558 // Actually we have to make a packet to buffer one.
2559 // Well, we have all the ingredients, so just do it.
2560 BufferedPacket packet = con::makePacket(
2563 m_connection->GetProtocolID(),
2567 channel->incoming_reliables.insert(packet,channel->readNextIncomingSeqNum());
2569 LOG(dout_con<<m_connection->getDesc()
2570 << "BUFFERING, TYPE_RELIABLE peer_id: " << peer_id
2571 << ", channel: " << (channelnum&0xFF)
2572 << ", seqnum: " << seqnum << std::endl;)
2574 throw ProcessedQueued("Buffered future reliable packet");
2576 catch(AlreadyExistsException &e)
2579 catch(IncomingDataCorruption &e)
2581 ConnectionCommand discon;
2582 discon.disconnect_peer(peer_id);
2583 m_connection->putCommand(discon);
2585 LOG(derr_con<<m_connection->getDesc()
2586 << "INVALID, TYPE_RELIABLE peer_id: " << peer_id
2587 << ", channel: " << (channelnum&0xFF)
2588 << ", seqnum: " << seqnum
2589 << "DROPPING CLIENT!" << std::endl;)
2593 /* we got a packet to process right now */
2594 LOG(dout_con<<m_connection->getDesc()
2595 << "RECURSIVE, TYPE_RELIABLE peer_id: " << peer_id
2596 << ", channel: " << (channelnum&0xFF)
2597 << ", seqnum: " << seqnum << std::endl;)
2600 /* check for resend case */
2601 u16 queued_seqnum = 0;
2602 if (channel->incoming_reliables.getFirstSeqnum(queued_seqnum))
2604 if (queued_seqnum == seqnum)
2606 BufferedPacket queued_packet = channel->incoming_reliables.popFirst();
2607 /** TODO find a way to verify the new against the old packet */
2611 channel->incNextIncomingSeqNum();
2613 // Get out the inside packet and re-process it
2614 SharedBuffer<u8> payload(packetdata.getSize() - RELIABLE_HEADER_SIZE);
2615 memcpy(*payload, &packetdata[RELIABLE_HEADER_SIZE], payload.getSize());
2617 return processPacket(channel, payload, peer_id, channelnum, true);
2621 derr_con<<m_connection->getDesc()
2622 <<"Got invalid type="<<((int)type&0xff)<<std::endl;
2623 throw InvalidIncomingDataException("Invalid packet type");
2626 // We should never get here.
2627 // If you get here, add an exception or a return to some of the
2628 // above conditionals.
2630 throw BaseException("Error in Channel::ProcessPacket()");
2637 Connection::Connection(u32 protocol_id, u32 max_packet_size, float timeout,
2643 m_protocol_id(protocol_id),
2644 m_sendThread(this, max_packet_size, timeout),
2645 m_receiveThread(this, max_packet_size),
2647 m_bc_peerhandler(0),
2648 m_bc_receive_timeout(0),
2649 m_shutting_down(false),
2650 m_next_remote_peer_id(2)
2652 m_udpSocket.setTimeoutMs(5);
2654 m_sendThread.Start();
2655 m_receiveThread.Start();
2658 Connection::Connection(u32 protocol_id, u32 max_packet_size, float timeout,
2659 bool ipv6, PeerHandler *peerhandler) :
2664 m_protocol_id(protocol_id),
2665 m_sendThread(this, max_packet_size, timeout),
2666 m_receiveThread(this, max_packet_size),
2668 m_bc_peerhandler(peerhandler),
2669 m_bc_receive_timeout(0),
2670 m_shutting_down(false),
2671 m_next_remote_peer_id(2)
2674 m_udpSocket.setTimeoutMs(5);
2676 m_sendThread.Start();
2677 m_receiveThread.Start();
2682 Connection::~Connection()
2684 m_shutting_down = true;
2685 // request threads to stop
2686 m_sendThread.Stop();
2687 m_receiveThread.Stop();
2689 //TODO for some unkonwn reason send/receive threads do not exit as they're
2690 // supposed to be but wait on peer timeout. To speed up shutdown we reduce
2691 // timeout to half a second.
2692 m_sendThread.setPeerTimeout(0.5);
2694 // wait for threads to finish
2695 m_sendThread.Wait();
2696 m_receiveThread.Wait();
2699 for(std::map<u16, Peer*>::iterator
2700 j = m_peers.begin();
2701 j != m_peers.end(); ++j)
2707 /* Internal stuff */
2708 void Connection::putEvent(ConnectionEvent &e)
2710 assert(e.type != CONNEVENT_NONE);
2711 m_event_queue.push_back(e);
2714 PeerHelper Connection::getPeer(u16 peer_id)
2716 JMutexAutoLock peerlock(m_peers_mutex);
2717 std::map<u16, Peer*>::iterator node = m_peers.find(peer_id);
2719 if(node == m_peers.end()){
2720 throw PeerNotFoundException("GetPeer: Peer not found (possible timeout)");
2724 assert(node->second->id == peer_id);
2726 return PeerHelper(node->second);
2729 PeerHelper Connection::getPeerNoEx(u16 peer_id)
2731 JMutexAutoLock peerlock(m_peers_mutex);
2732 std::map<u16, Peer*>::iterator node = m_peers.find(peer_id);
2734 if(node == m_peers.end()){
2735 return PeerHelper(NULL);
2739 assert(node->second->id == peer_id);
2741 return PeerHelper(node->second);
2744 /* find peer_id for address */
2745 u16 Connection::lookupPeer(Address& sender)
2747 JMutexAutoLock peerlock(m_peers_mutex);
2748 std::map<u16, Peer*>::iterator j;
2749 j = m_peers.begin();
2750 for(; j != m_peers.end(); ++j)
2752 Peer *peer = j->second;
2753 if(peer->isActive())
2758 if ((peer->getAddress(MTP_MINETEST_RELIABLE_UDP, tocheck)) && (tocheck == sender))
2761 if ((peer->getAddress(MTP_UDP, tocheck)) && (tocheck == sender))
2765 return PEER_ID_INEXISTENT;
2768 std::list<Peer*> Connection::getPeers()
2770 std::list<Peer*> list;
2771 for(std::map<u16, Peer*>::iterator j = m_peers.begin();
2772 j != m_peers.end(); ++j)
2774 Peer *peer = j->second;
2775 list.push_back(peer);
2780 bool Connection::deletePeer(u16 peer_id, bool timeout)
2784 /* lock list as short as possible */
2786 JMutexAutoLock peerlock(m_peers_mutex);
2787 if(m_peers.find(peer_id) == m_peers.end())
2789 peer = m_peers[peer_id];
2790 m_peers.erase(peer_id);
2793 Address peer_address;
2794 //any peer has a primary address this never fails!
2795 peer->getAddress(MTP_PRIMARY, peer_address);
2798 e.peerRemoved(peer_id, timeout, peer_address);
2808 ConnectionEvent Connection::getEvent()
2810 if(m_event_queue.empty()){
2812 e.type = CONNEVENT_NONE;
2815 return m_event_queue.pop_frontNoEx();
2818 ConnectionEvent Connection::waitEvent(u32 timeout_ms)
2821 return m_event_queue.pop_front(timeout_ms);
2822 } catch(ItemNotFoundException &ex){
2824 e.type = CONNEVENT_NONE;
2829 void Connection::putCommand(ConnectionCommand &c)
2831 if (!m_shutting_down)
2833 m_command_queue.push_back(c);
2834 m_sendThread.Trigger();
2838 void Connection::Serve(Address bind_addr)
2840 ConnectionCommand c;
2845 void Connection::Connect(Address address)
2847 ConnectionCommand c;
2852 bool Connection::Connected()
2854 JMutexAutoLock peerlock(m_peers_mutex);
2856 if(m_peers.size() != 1)
2859 std::map<u16, Peer*>::iterator node = m_peers.find(PEER_ID_SERVER);
2860 if(node == m_peers.end())
2863 if(m_peer_id == PEER_ID_INEXISTENT)
2869 void Connection::Disconnect()
2871 ConnectionCommand c;
2876 u32 Connection::Receive(u16 &peer_id, SharedBuffer<u8> &data)
2879 ConnectionEvent e = waitEvent(m_bc_receive_timeout);
2880 if(e.type != CONNEVENT_NONE)
2881 LOG(dout_con<<getDesc()<<": Receive: got event: "
2882 <<e.describe()<<std::endl);
2884 case CONNEVENT_NONE:
2885 throw NoIncomingDataException("No incoming data");
2886 case CONNEVENT_DATA_RECEIVED:
2887 peer_id = e.peer_id;
2888 data = SharedBuffer<u8>(e.data);
2889 return e.data.getSize();
2890 case CONNEVENT_PEER_ADDED: {
2891 UDPPeer tmp(e.peer_id, e.address, this);
2892 if(m_bc_peerhandler)
2893 m_bc_peerhandler->peerAdded(&tmp);
2895 case CONNEVENT_PEER_REMOVED: {
2896 UDPPeer tmp(e.peer_id, e.address, this);
2897 if(m_bc_peerhandler)
2898 m_bc_peerhandler->deletingPeer(&tmp, e.timeout);
2900 case CONNEVENT_BIND_FAILED:
2901 throw ConnectionBindFailed("Failed to bind socket "
2902 "(port already in use?)");
2905 throw NoIncomingDataException("No incoming data");
2908 void Connection::SendToAll(u8 channelnum, SharedBuffer<u8> data, bool reliable)
2910 assert(channelnum < CHANNEL_COUNT);
2912 ConnectionCommand c;
2913 c.sendToAll(channelnum, data, reliable);
2917 void Connection::Send(u16 peer_id, u8 channelnum,
2918 SharedBuffer<u8> data, bool reliable)
2920 assert(channelnum < CHANNEL_COUNT);
2922 ConnectionCommand c;
2923 c.send(peer_id, channelnum, data, reliable);
2927 Address Connection::GetPeerAddress(u16 peer_id)
2929 PeerHelper peer = getPeerNoEx(peer_id);
2932 throw PeerNotFoundException("No address for peer found!");
2933 Address peer_address;
2934 peer->getAddress(MTP_PRIMARY, peer_address);
2935 return peer_address;
2938 float Connection::getPeerStat(u16 peer_id, rtt_stat_type type)
2940 PeerHelper peer = getPeerNoEx(peer_id);
2941 if (!peer) return -1;
2942 return peer->getStat(type);
2945 float Connection::getLocalStat(rate_stat_type type)
2947 PeerHelper peer = getPeerNoEx(PEER_ID_SERVER);
2950 assert("Connection::getLocalStat we couldn't get our own peer? are you serious???" == 0);
2955 for (u16 j=0; j<CHANNEL_COUNT; j++) {
2958 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getCurrentDownloadRateKB();
2961 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getAvgDownloadRateKB();
2964 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getCurrentIncomingRateKB();
2967 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getAvgIncomingRateKB();
2970 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getAvgLossRateKB();
2973 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getCurrentLossRateKB();
2976 assert("Connection::getLocalStat Invalid stat type" == 0);
2982 u16 Connection::createPeer(Address& sender, MTProtocols protocol, int fd)
2984 // Somebody wants to make a new connection
2986 // Get a unique peer id (2 or higher)
2987 u16 peer_id_new = m_next_remote_peer_id;
2988 u16 overflow = MAX_UDP_PEERS;
2991 Find an unused peer id
2994 JMutexAutoLock lock(m_peers_mutex);
2995 bool out_of_ids = false;
2999 if(m_peers.find(peer_id_new) == m_peers.end())
3001 // Check for overflow
3002 if(peer_id_new == overflow){
3009 errorstream<<getDesc()<<" ran out of peer ids"<<std::endl;
3010 return PEER_ID_INEXISTENT;
3015 peer = new UDPPeer(peer_id_new, sender, this);
3017 m_peers[peer->id] = peer;
3020 m_next_remote_peer_id = (peer_id_new +1) % MAX_UDP_PEERS;
3022 LOG(dout_con<<getDesc()
3023 <<"createPeer(): giving peer_id="<<peer_id_new<<std::endl);
3025 ConnectionCommand cmd;
3026 SharedBuffer<u8> reply(4);
3027 writeU8(&reply[0], TYPE_CONTROL);
3028 writeU8(&reply[1], CONTROLTYPE_SET_PEER_ID);
3029 writeU16(&reply[2], peer_id_new);
3030 cmd.createPeer(peer_id_new,reply);
3031 this->putCommand(cmd);
3033 // Create peer addition event
3035 e.peerAdded(peer_id_new, sender);
3038 // We're now talking to a valid peer_id
3042 void Connection::PrintInfo(std::ostream &out)
3044 m_info_mutex.Lock();
3045 out<<getDesc()<<": ";
3046 m_info_mutex.Unlock();
3049 void Connection::PrintInfo()
3051 PrintInfo(dout_con);
3054 const std::string Connection::getDesc()
3056 return std::string("con(")+
3057 itos(m_udpSocket.GetHandle())+"/"+itos(m_peer_id)+")";
3060 void Connection::DisconnectPeer(u16 peer_id)
3062 ConnectionCommand discon;
3063 discon.disconnect_peer(peer_id);
3067 void Connection::sendAck(u16 peer_id, u8 channelnum, u16 seqnum)
3069 assert(channelnum < CHANNEL_COUNT);
3071 LOG(dout_con<<getDesc()
3072 <<" Queuing ACK command to peer_id: " << peer_id <<
3073 " channel: " << (channelnum & 0xFF) <<
3074 " seqnum: " << seqnum << std::endl);
3076 ConnectionCommand c;
3077 SharedBuffer<u8> ack(4);
3078 writeU8(&ack[0], TYPE_CONTROL);
3079 writeU8(&ack[1], CONTROLTYPE_ACK);
3080 writeU16(&ack[2], seqnum);
3082 c.ack(peer_id, channelnum, ack);
3084 m_sendThread.Trigger();
3087 UDPPeer* Connection::createServerPeer(Address& address)
3089 if (getPeerNoEx(PEER_ID_SERVER) != 0)
3091 throw ConnectionException("Already connected to a server");
3094 UDPPeer *peer = new UDPPeer(PEER_ID_SERVER, address, this);
3097 JMutexAutoLock lock(m_peers_mutex);
3098 m_peers[peer->id] = peer;
3104 std::list<u16> Connection::getPeerIDs()
3106 std::list<u16> retval;
3108 JMutexAutoLock lock(m_peers_mutex);
3109 for(std::map<u16, Peer*>::iterator j = m_peers.begin();
3110 j != m_peers.end(); ++j)
3112 retval.push_back(j->first);