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);
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,
193 /*dstream<<"BEGIN SharedBuffer<u8> makeReliablePacket()"<<std::endl;
194 dstream<<"data.getSize()="<<data.getSize()<<", data[0]="
195 <<((unsigned int)data[0]&0xff)<<std::endl;*/
197 u32 packet_size = data.getSize() + header_size;
198 SharedBuffer<u8> b(packet_size);
200 writeU8(&b[0], TYPE_RELIABLE);
201 writeU16(&b[1], seqnum);
203 memcpy(&b[header_size], *data, data.getSize());
205 /*dstream<<"data.getSize()="<<data.getSize()<<", data[0]="
206 <<((unsigned int)data[0]&0xff)<<std::endl;*/
207 //dstream<<"END SharedBuffer<u8> makeReliablePacket()"<<std::endl;
215 ReliablePacketBuffer::ReliablePacketBuffer(): m_list_size(0),writeptr(0) {}
217 void ReliablePacketBuffer::print()
219 JMutexAutoLock listlock(m_list_mutex);
220 LOG(dout_con<<"Dump of ReliablePacketBuffer:" << std::endl);
221 unsigned int index = 0;
222 for(std::list<BufferedPacket>::iterator i = m_list.begin();
226 u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
227 LOG(dout_con<<index<< ":" << s << std::endl);
231 bool ReliablePacketBuffer::empty()
233 JMutexAutoLock listlock(m_list_mutex);
234 return m_list.empty();
237 u32 ReliablePacketBuffer::size()
242 bool ReliablePacketBuffer::containsPacket(u16 seqnum)
244 return !(findPacket(seqnum) == m_list.end());
247 RPBSearchResult ReliablePacketBuffer::findPacket(u16 seqnum)
249 std::list<BufferedPacket>::iterator i = m_list.begin();
250 for(; i != m_list.end(); ++i)
252 u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
253 /*dout_con<<"findPacket(): finding seqnum="<<seqnum
254 <<", comparing to s="<<s<<std::endl;*/
260 RPBSearchResult ReliablePacketBuffer::notFound()
264 bool ReliablePacketBuffer::getFirstSeqnum(u16& result)
266 JMutexAutoLock listlock(m_list_mutex);
269 BufferedPacket p = *m_list.begin();
270 result = readU16(&p.data[BASE_HEADER_SIZE+1]);
274 BufferedPacket ReliablePacketBuffer::popFirst()
276 JMutexAutoLock listlock(m_list_mutex);
278 throw NotFoundException("Buffer is empty");
279 BufferedPacket p = *m_list.begin();
280 m_list.erase(m_list.begin());
283 if (m_list_size == 0)
284 { m_oldest_non_answered_ack = 0; }
286 { m_oldest_non_answered_ack = readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]); }
289 BufferedPacket ReliablePacketBuffer::popSeqnum(u16 seqnum)
291 JMutexAutoLock listlock(m_list_mutex);
292 RPBSearchResult r = findPacket(seqnum);
294 LOG(dout_con<<"Sequence number: " << seqnum << " not found in reliable buffer"<<std::endl);
295 throw NotFoundException("seqnum not found in buffer");
297 BufferedPacket p = *r;
300 RPBSearchResult next = r;
302 if (next != notFound()) {
303 u16 s = readU16(&(next->data[BASE_HEADER_SIZE+1]));
304 m_oldest_non_answered_ack = s;
310 if (m_list_size == 0)
311 { m_oldest_non_answered_ack = 0; }
313 { m_oldest_non_answered_ack = readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]); }
316 void ReliablePacketBuffer::insert(BufferedPacket &p,u16 next_expected)
318 JMutexAutoLock listlock(m_list_mutex);
319 assert(p.data.getSize() >= BASE_HEADER_SIZE+3);
320 u8 type = readU8(&p.data[BASE_HEADER_SIZE+0]);
321 assert(type == TYPE_RELIABLE);
322 u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]);
324 assert(seqnum_in_window(seqnum,next_expected,MAX_RELIABLE_WINDOW_SIZE));
325 assert(seqnum != next_expected);
328 assert(m_list_size <= SEQNUM_MAX+1);
330 // Find the right place for the packet and insert it there
331 // If list is empty, just add it
335 m_oldest_non_answered_ack = seqnum;
340 // Otherwise find the right place
341 std::list<BufferedPacket>::iterator i = m_list.begin();
342 // Find the first packet in the list which has a higher seqnum
343 u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
345 /* case seqnum is smaller then next_expected seqnum */
346 /* this is true e.g. on wrap around */
347 if (seqnum < next_expected) {
348 while(((s < seqnum) || (s >= next_expected)) && (i != m_list.end())) {
350 if (i != m_list.end())
351 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
354 /* non wrap around case (at least for incoming and next_expected */
357 while(((s < seqnum) && (s >= next_expected)) && (i != m_list.end())) {
359 if (i != m_list.end())
360 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
366 (readU16(&(i->data[BASE_HEADER_SIZE+1])) != seqnum) ||
367 (i->data.getSize() != p.data.getSize()) ||
368 (i->address != p.address)
371 /* if this happens your maximum transfer window may be to big */
372 fprintf(stderr, "Duplicated seqnum %d non matching packet detected:\n",seqnum);
373 fprintf(stderr, "Old: seqnum: %05d size: %04d, address: %s\n",
374 readU16(&(i->data[BASE_HEADER_SIZE+1])),i->data.getSize(), 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(), p.address.serializeString().c_str());
377 throw IncomingDataCorruption("duplicated packet isn't same as original one");
380 assert(readU16(&(i->data[BASE_HEADER_SIZE+1])) == seqnum);
381 assert(i->data.getSize() == p.data.getSize());
382 assert(i->address == p.address);
384 /* nothing to do this seems to be a resent packet */
385 /* for paranoia reason data should be compared */
388 /* insert or push back */
389 else if (i != m_list.end()) {
396 /* update last packet number */
397 m_oldest_non_answered_ack = readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]);
400 void ReliablePacketBuffer::incrementTimeouts(float dtime)
402 JMutexAutoLock listlock(m_list_mutex);
403 for(std::list<BufferedPacket>::iterator i = m_list.begin();
404 i != m_list.end(); ++i)
407 i->totaltime += dtime;
411 std::list<BufferedPacket> ReliablePacketBuffer::getTimedOuts(float timeout,
412 unsigned int max_packets)
414 JMutexAutoLock listlock(m_list_mutex);
415 std::list<BufferedPacket> timed_outs;
416 for(std::list<BufferedPacket>::iterator i = m_list.begin();
417 i != m_list.end(); ++i)
419 if(i->time >= timeout) {
420 timed_outs.push_back(*i);
422 //this packet will be sent right afterwards reset timeout here
424 if (timed_outs.size() >= max_packets)
435 IncomingSplitBuffer::~IncomingSplitBuffer()
437 JMutexAutoLock listlock(m_map_mutex);
438 for(std::map<u16, IncomingSplitPacket*>::iterator i = m_buf.begin();
439 i != m_buf.end(); ++i)
445 This will throw a GotSplitPacketException when a full
446 split packet is constructed.
448 SharedBuffer<u8> IncomingSplitBuffer::insert(BufferedPacket &p, bool reliable)
450 JMutexAutoLock listlock(m_map_mutex);
451 u32 headersize = BASE_HEADER_SIZE + 7;
452 assert(p.data.getSize() >= headersize);
453 u8 type = readU8(&p.data[BASE_HEADER_SIZE+0]);
454 assert(type == TYPE_SPLIT);
455 u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]);
456 u16 chunk_count = readU16(&p.data[BASE_HEADER_SIZE+3]);
457 u16 chunk_num = readU16(&p.data[BASE_HEADER_SIZE+5]);
459 // Add if doesn't exist
460 if(m_buf.find(seqnum) == m_buf.end())
462 IncomingSplitPacket *sp = new IncomingSplitPacket();
463 sp->chunk_count = chunk_count;
464 sp->reliable = reliable;
468 IncomingSplitPacket *sp = m_buf[seqnum];
470 // TODO: These errors should be thrown or something? Dunno.
471 if(chunk_count != sp->chunk_count)
472 LOG(derr_con<<"Connection: WARNING: chunk_count="<<chunk_count
473 <<" != sp->chunk_count="<<sp->chunk_count
475 if(reliable != sp->reliable)
476 LOG(derr_con<<"Connection: WARNING: reliable="<<reliable
477 <<" != sp->reliable="<<sp->reliable
480 // If chunk already exists, ignore it.
481 // Sometimes two identical packets may arrive when there is network
482 // lag and the server re-sends stuff.
483 if(sp->chunks.find(chunk_num) != sp->chunks.end())
484 return SharedBuffer<u8>();
486 // Cut chunk data out of packet
487 u32 chunkdatasize = p.data.getSize() - headersize;
488 SharedBuffer<u8> chunkdata(chunkdatasize);
489 memcpy(*chunkdata, &(p.data[headersize]), chunkdatasize);
491 // Set chunk data in buffer
492 sp->chunks[chunk_num] = chunkdata;
494 // If not all chunks are received, return empty buffer
495 if(sp->allReceived() == false)
496 return SharedBuffer<u8>();
498 // Calculate total size
500 for(std::map<u16, SharedBuffer<u8> >::iterator i = sp->chunks.begin();
501 i != sp->chunks.end(); ++i)
503 totalsize += i->second.getSize();
506 SharedBuffer<u8> fulldata(totalsize);
508 // Copy chunks to data buffer
510 for(u32 chunk_i=0; chunk_i<sp->chunk_count;
513 SharedBuffer<u8> buf = sp->chunks[chunk_i];
514 u16 chunkdatasize = buf.getSize();
515 memcpy(&fulldata[start], *buf, chunkdatasize);
516 start += chunkdatasize;;
519 // Remove sp from buffer
525 void IncomingSplitBuffer::removeUnreliableTimedOuts(float dtime, float timeout)
527 std::list<u16> remove_queue;
529 JMutexAutoLock listlock(m_map_mutex);
530 for(std::map<u16, IncomingSplitPacket*>::iterator i = m_buf.begin();
531 i != m_buf.end(); ++i)
533 IncomingSplitPacket *p = i->second;
534 // Reliable ones are not removed by timeout
535 if(p->reliable == true)
538 if(p->time >= timeout)
539 remove_queue.push_back(i->first);
542 for(std::list<u16>::iterator j = remove_queue.begin();
543 j != remove_queue.end(); ++j)
545 JMutexAutoLock listlock(m_map_mutex);
546 LOG(dout_con<<"NOTE: Removing timed out unreliable split packet"<<std::endl);
557 window_size(MIN_RELIABLE_WINDOW_SIZE),
558 next_incoming_seqnum(SEQNUM_INITIAL),
559 next_outgoing_seqnum(SEQNUM_INITIAL),
560 next_outgoing_split_seqnum(SEQNUM_INITIAL),
561 current_packet_loss(0),
562 current_packet_too_late(0),
563 packet_loss_counter(0),
564 current_bytes_transfered(0),
565 current_bytes_lost(0),
580 u16 Channel::readNextIncomingSeqNum()
582 JMutexAutoLock internal(m_internal_mutex);
583 return next_incoming_seqnum;
586 u16 Channel::incNextIncomingSeqNum()
588 JMutexAutoLock internal(m_internal_mutex);
589 u16 retval = next_incoming_seqnum;
590 next_incoming_seqnum++;
594 u16 Channel::readNextSplitSeqNum()
596 JMutexAutoLock internal(m_internal_mutex);
597 return next_outgoing_split_seqnum;
599 void Channel::setNextSplitSeqNum(u16 seqnum)
601 JMutexAutoLock internal(m_internal_mutex);
602 next_outgoing_split_seqnum = seqnum;
605 u16 Channel::getOutgoingSequenceNumber(bool& successfull)
607 JMutexAutoLock internal(m_internal_mutex);
608 u16 retval = next_outgoing_seqnum;
609 u16 lowest_unacked_seqnumber;
611 /* shortcut if there ain't any packet in outgoing list */
612 if (outgoing_reliables_sent.empty())
614 next_outgoing_seqnum++;
618 if (outgoing_reliables_sent.getFirstSeqnum(lowest_unacked_seqnumber))
620 if (lowest_unacked_seqnumber < next_outgoing_seqnum) {
621 // ugly cast but this one is required in order to tell compiler we
622 // know about difference of two unsigned may be negative in general
623 // but we already made sure it won't happen in this case
624 if (((u16)(next_outgoing_seqnum - lowest_unacked_seqnumber)) > window_size) {
630 // ugly cast but this one is required in order to tell compiler we
631 // know about difference of two unsigned may be negative in general
632 // but we already made sure it won't happen in this case
633 if ((next_outgoing_seqnum + (u16)(SEQNUM_MAX - lowest_unacked_seqnumber)) >
641 next_outgoing_seqnum++;
645 u16 Channel::readOutgoingSequenceNumber()
647 JMutexAutoLock internal(m_internal_mutex);
648 return next_outgoing_seqnum;
651 bool Channel::putBackSequenceNumber(u16 seqnum)
653 if (((seqnum + 1) % (SEQNUM_MAX+1)) == next_outgoing_seqnum) {
655 next_outgoing_seqnum = seqnum;
661 void Channel::UpdateBytesSent(unsigned int bytes, unsigned int packets)
663 JMutexAutoLock internal(m_internal_mutex);
664 current_bytes_transfered += bytes;
665 current_packet_successfull += packets;
668 void Channel::UpdateBytesLost(unsigned int bytes)
670 JMutexAutoLock internal(m_internal_mutex);
671 current_bytes_lost += bytes;
675 void Channel::UpdatePacketLossCounter(unsigned int count)
677 JMutexAutoLock internal(m_internal_mutex);
678 current_packet_loss += count;
681 void Channel::UpdatePacketTooLateCounter()
683 JMutexAutoLock internal(m_internal_mutex);
684 current_packet_too_late++;
687 void Channel::UpdateTimers(float dtime)
689 bpm_counter += dtime;
690 packet_loss_counter += dtime;
692 if (packet_loss_counter > 1.0)
694 packet_loss_counter -= 1.0;
696 unsigned int packet_loss = 11; /* use a neutral value for initialization */
697 unsigned int packets_successfull = 0;
698 unsigned int packet_too_late = 0;
700 bool reasonable_amount_of_data_transmitted = false;
703 JMutexAutoLock internal(m_internal_mutex);
704 packet_loss = current_packet_loss;
705 packet_too_late = current_packet_too_late;
706 packets_successfull = current_packet_successfull;
708 if (current_bytes_transfered > (window_size*512/2))
710 reasonable_amount_of_data_transmitted = true;
712 current_packet_loss = 0;
713 current_packet_too_late = 0;
714 current_packet_successfull = 0;
717 float successfull_to_lost_ratio = 0.0;
720 if (packets_successfull > 0) {
721 successfull_to_lost_ratio = packet_loss/packets_successfull;
723 else if (packet_loss > 0)
727 MIN_RELIABLE_WINDOW_SIZE);
733 if ((successfull_to_lost_ratio < 0.01) &&
734 (window_size < MAX_RELIABLE_WINDOW_SIZE))
736 /* don't even think about increasing if we didn't even
737 * use major parts of our window */
738 if (reasonable_amount_of_data_transmitted)
741 MAX_RELIABLE_WINDOW_SIZE);
743 else if ((successfull_to_lost_ratio < 0.05) &&
744 (window_size < MAX_RELIABLE_WINDOW_SIZE))
746 /* don't even think about increasing if we didn't even
747 * use major parts of our window */
748 if (reasonable_amount_of_data_transmitted)
751 MAX_RELIABLE_WINDOW_SIZE);
753 else if (successfull_to_lost_ratio > 0.15)
757 MIN_RELIABLE_WINDOW_SIZE);
759 else if (successfull_to_lost_ratio > 0.1)
763 MIN_RELIABLE_WINDOW_SIZE);
768 if (bpm_counter > 10.0)
771 JMutexAutoLock internal(m_internal_mutex);
772 cur_kbps = (current_bytes_transfered/bpm_counter)/1024;
773 current_bytes_transfered = 0;
774 cur_kbps_lost = (current_bytes_lost/bpm_counter)/1024;
775 current_bytes_lost = 0;
779 if (cur_kbps > max_kbps)
784 if (cur_kbps_lost > max_kbps_lost)
786 max_kbps_lost = cur_kbps_lost;
789 avg_kbps = avg_kbps * 0.9 + cur_kbps * 0.1;
790 avg_kbps_lost = avg_kbps_lost * 0.9 + cur_kbps_lost * 0.1;
799 PeerHelper::PeerHelper() :
804 PeerHelper::PeerHelper(Peer* peer) :
809 if (!peer->IncUseCount())
816 PeerHelper::~PeerHelper()
819 m_peer->DecUseCount();
824 PeerHelper& PeerHelper::operator=(Peer* peer)
829 if (!peer->IncUseCount())
837 Peer* PeerHelper::operator->() const
842 Peer* PeerHelper::operator&() const
847 bool PeerHelper::operator!() {
851 bool PeerHelper::operator!=(void* ptr)
853 return ((void*) m_peer != ptr);
856 bool Peer::IncUseCount()
858 JMutexAutoLock lock(m_exclusive_access_mutex);
860 if (!m_pending_deletion)
869 void Peer::DecUseCount()
872 JMutexAutoLock lock(m_exclusive_access_mutex);
876 if (!((m_pending_deletion) && (m_usage == 0)))
882 void Peer::RTTStatistics(float rtt,
883 std::string profiler_id,
884 unsigned int num_samples) {
886 if (m_last_rtt > 0) {
887 /* set min max values */
888 if (rtt < m_rtt.min_rtt)
890 if (rtt >= m_rtt.max_rtt)
893 /* do average calculation */
894 if(m_rtt.avg_rtt < 0.0)
897 m_rtt.avg_rtt = m_rtt.avg_rtt * (num_samples/(num_samples-1)) +
898 rtt * (1/num_samples);
900 /* do jitter calculation */
902 //just use some neutral value at beginning
903 float jitter = m_rtt.jitter_min;
905 if (rtt > m_last_rtt)
906 jitter = rtt-m_last_rtt;
908 if (rtt <= m_last_rtt)
909 jitter = m_last_rtt - rtt;
911 if (jitter < m_rtt.jitter_min)
912 m_rtt.jitter_min = jitter;
913 if (jitter >= m_rtt.jitter_max)
914 m_rtt.jitter_max = jitter;
916 if(m_rtt.jitter_avg < 0.0)
917 m_rtt.jitter_avg = jitter;
919 m_rtt.jitter_avg = m_rtt.jitter_avg * (num_samples/(num_samples-1)) +
920 jitter * (1/num_samples);
922 if (profiler_id != "")
924 g_profiler->graphAdd(profiler_id + "_rtt", rtt);
925 g_profiler->graphAdd(profiler_id + "_jitter", jitter);
928 /* save values required for next loop */
932 bool Peer::isTimedOut(float timeout)
934 JMutexAutoLock lock(m_exclusive_access_mutex);
935 u32 current_time = porting::getTimeMs();
937 float dtime = CALC_DTIME(m_last_timeout_check,current_time);
938 m_last_timeout_check = current_time;
940 m_timeout_counter += dtime;
942 return m_timeout_counter > timeout;
948 JMutexAutoLock usage_lock(m_exclusive_access_mutex);
949 m_pending_deletion = true;
954 PROFILE(std::stringstream peerIdentifier1);
955 PROFILE(peerIdentifier1 << "runTimeouts[" << m_connection->getDesc() << ";" << id << ";RELIABLE]");
956 PROFILE(g_profiler->remove(peerIdentifier1.str()));
957 PROFILE(std::stringstream peerIdentifier2);
958 PROFILE(peerIdentifier2 << "sendPackets[" << m_connection->getDesc() << ";" << id << ";RELIABLE]");
959 PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier2.str(), SPT_AVG));
964 UDPPeer::UDPPeer(u16 a_id, Address a_address, Connection* connection) :
965 Peer(a_address,a_id,connection),
966 m_pending_disconnect(false),
972 bool UDPPeer::getAddress(MTProtocols type,Address& toset)
974 if ((type == UDP) || (type == MINETEST_RELIABLE_UDP) || (type == PRIMARY))
983 void UDPPeer::setNonLegacyPeer()
985 m_legacy_peer = false;
986 for(unsigned int i=0; i< CHANNEL_COUNT; i++)
988 channels->setWindowSize(g_settings->getU16("max_packets_per_iteration"));
992 void UDPPeer::reportRTT(float rtt)
997 RTTStatistics(rtt,"rudp",MAX_RELIABLE_WINDOW_SIZE*10);
999 float timeout = getStat(AVG_RTT) * RESEND_TIMEOUT_FACTOR;
1000 if(timeout < RESEND_TIMEOUT_MIN)
1001 timeout = RESEND_TIMEOUT_MIN;
1002 if(timeout > RESEND_TIMEOUT_MAX)
1003 timeout = RESEND_TIMEOUT_MAX;
1005 JMutexAutoLock usage_lock(m_exclusive_access_mutex);
1006 resend_timeout = timeout;
1009 bool UDPPeer::Ping(float dtime,SharedBuffer<u8>& data)
1011 m_ping_timer += dtime;
1012 if(m_ping_timer >= PING_TIMEOUT)
1014 // Create and send PING packet
1015 writeU8(&data[0], TYPE_CONTROL);
1016 writeU8(&data[1], CONTROLTYPE_PING);
1023 void UDPPeer::PutReliableSendCommand(ConnectionCommand &c,
1024 unsigned int max_packet_size)
1026 if (m_pending_disconnect)
1029 if ( channels[c.channelnum].queued_commands.empty() &&
1030 /* don't queue more packets then window size */
1031 (channels[c.channelnum].queued_reliables.size()
1032 < (channels[c.channelnum].getWindowSize()/2)))
1034 LOG(dout_con<<m_connection->getDesc()
1035 <<" processing reliable command for peer id: " << c.peer_id
1036 <<" data size: " << c.data.getSize() << std::endl);
1037 if (!processReliableSendCommand(c,max_packet_size))
1039 channels[c.channelnum].queued_commands.push_back(c);
1044 LOG(dout_con<<m_connection->getDesc()
1045 <<" Queueing reliable command for peer id: " << c.peer_id
1046 <<" data size: " << c.data.getSize() <<std::endl);
1047 channels[c.channelnum].queued_commands.push_back(c);
1051 bool UDPPeer::processReliableSendCommand(
1052 ConnectionCommand &c,
1053 unsigned int max_packet_size)
1055 if (m_pending_disconnect)
1058 u32 chunksize_max = max_packet_size
1060 - RELIABLE_HEADER_SIZE;
1062 assert(c.data.getSize() < MAX_RELIABLE_WINDOW_SIZE*512);
1064 std::list<SharedBuffer<u8> > originals;
1065 u16 split_sequence_number = channels[c.channelnum].readNextSplitSeqNum();
1069 originals.push_back(c.data);
1072 originals = makeAutoSplitPacket(c.data, chunksize_max,split_sequence_number);
1073 channels[c.channelnum].setNextSplitSeqNum(split_sequence_number);
1076 bool have_sequence_number = true;
1077 bool have_initial_sequence_number = false;
1078 Queue<BufferedPacket> toadd;
1079 volatile u16 initial_sequence_number = 0;
1081 for(std::list<SharedBuffer<u8> >::iterator i = originals.begin();
1082 i != originals.end(); ++i)
1084 u16 seqnum = channels[c.channelnum].getOutgoingSequenceNumber(have_sequence_number);
1086 /* oops, we don't have enough sequence numbers to send this packet */
1087 if (!have_sequence_number)
1090 if (!have_initial_sequence_number)
1092 initial_sequence_number = seqnum;
1093 have_initial_sequence_number = true;
1096 SharedBuffer<u8> reliable = makeReliablePacket(*i, seqnum);
1098 // Add base headers and make a packet
1099 BufferedPacket p = con::makePacket(address, reliable,
1100 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1106 if (have_sequence_number) {
1107 volatile u16 pcount = 0;
1108 while(toadd.size() > 0) {
1109 BufferedPacket p = toadd.pop_front();
1110 // LOG(dout_con<<connection->getDesc()
1111 // << " queuing reliable packet for peer_id: " << c.peer_id
1112 // << " channel: " << (c.channelnum&0xFF)
1113 // << " seqnum: " << readU16(&p.data[BASE_HEADER_SIZE+1])
1115 channels[c.channelnum].queued_reliables.push_back(p);
1118 assert(channels[c.channelnum].queued_reliables.size() < 0xFFFF);
1122 volatile u16 packets_available = toadd.size();
1123 /* we didn't get a single sequence number no need to fill queue */
1124 if (!have_initial_sequence_number)
1128 while(toadd.size() > 0) {
1132 bool successfully_put_back_sequence_number
1133 = channels[c.channelnum].putBackSequenceNumber(
1134 (initial_sequence_number+toadd.size() % (SEQNUM_MAX+1)));
1136 assert(successfully_put_back_sequence_number);
1138 LOG(dout_con<<m_connection->getDesc()
1139 << " Windowsize exceeded on reliable sending " << c.data.getSize() << " bytes"
1140 << std::endl << "\t\tinitial_sequence_number: " << initial_sequence_number
1141 << std::endl << "\t\tgot at most : " << packets_available << " packets"
1142 << std::endl << "\t\tpackets queued : " << channels[c.channelnum].outgoing_reliables_sent.size()
1148 void UDPPeer::RunCommandQueues(
1149 unsigned int max_packet_size,
1150 unsigned int maxcommands,
1151 unsigned int maxtransfer)
1154 for (unsigned int i = 0; i < CHANNEL_COUNT; i++)
1156 unsigned int commands_processed = 0;
1158 if ((channels[i].queued_commands.size() > 0) &&
1159 (channels[i].queued_reliables.size() < maxtransfer) &&
1160 (commands_processed < maxcommands))
1163 ConnectionCommand c = channels[i].queued_commands.pop_front();
1164 LOG(dout_con<<m_connection->getDesc()
1165 <<" processing queued reliable command "<<std::endl);
1166 if (!processReliableSendCommand(c,max_packet_size)) {
1167 LOG(dout_con<<m_connection->getDesc()
1168 << " Failed to queue packets for peer_id: " << c.peer_id
1169 << ", delaying sending of " << c.data.getSize() << " bytes" << std::endl);
1170 channels[i].queued_commands.push_front(c);
1173 catch (ItemNotFoundException &e) {
1174 // intentionally empty
1180 u16 UDPPeer::getNextSplitSequenceNumber(u8 channel)
1182 assert(channel < CHANNEL_COUNT);
1183 return channels[channel].readNextIncomingSeqNum();
1186 void UDPPeer::setNextSplitSequenceNumber(u8 channel, u16 seqnum)
1188 assert(channel < CHANNEL_COUNT);
1189 channels[channel].setNextSplitSeqNum(seqnum);
1192 SharedBuffer<u8> UDPPeer::addSpiltPacket(u8 channel,
1193 BufferedPacket toadd,
1196 assert(channel < CHANNEL_COUNT);
1197 return channels[channel].incoming_splits.insert(toadd,reliable);
1200 /******************************************************************************/
1201 /* Connection Threads */
1202 /******************************************************************************/
1204 ConnectionSendThread::ConnectionSendThread(Connection* parent,
1205 unsigned int max_packet_size,
1207 m_connection(parent),
1208 m_max_packet_size(max_packet_size),
1210 m_max_commands_per_iteration(1),
1211 m_max_data_packets_per_iteration(g_settings->getU16("max_packets_per_iteration")),
1212 m_max_packets_requeued(256)
1216 void * ConnectionSendThread::Thread()
1219 log_register_thread("ConnectionSend");
1221 LOG(dout_con<<m_connection->getDesc()
1222 <<"ConnectionSend thread started"<<std::endl);
1224 u32 curtime = porting::getTimeMs();
1225 u32 lasttime = curtime;
1227 PROFILE(std::stringstream ThreadIdentifier);
1228 PROFILE(ThreadIdentifier << "ConnectionSend: [" << m_connection->getDesc() << "]");
1230 porting::setThreadName("ConnectionSend");
1232 /* if stop is requested don't stop immediately but try to send all */
1234 while(!StopRequested() || packetsQueued()) {
1235 BEGIN_DEBUG_EXCEPTION_HANDLER
1236 PROFILE(ScopeProfiler sp(g_profiler, ThreadIdentifier.str(), SPT_AVG));
1238 m_iteration_packets_avaialble = m_max_data_packets_per_iteration;
1240 /* wait for trigger or timeout */
1241 m_send_sleep_semaphore.Wait(50);
1243 /* remove all triggers */
1244 while(m_send_sleep_semaphore.Wait(0)) {}
1247 curtime = porting::getTimeMs();
1248 float dtime = CALC_DTIME(lasttime,curtime);
1250 /* first do all the reliable stuff */
1253 /* translate commands to packets */
1254 ConnectionCommand c = m_connection->m_command_queue.pop_frontNoEx(0);
1255 while(c.type != CONNCMD_NONE)
1258 processReliableCommand(c);
1260 processNonReliableCommand(c);
1262 c = m_connection->m_command_queue.pop_frontNoEx(0);
1265 /* send non reliable packets */
1268 END_DEBUG_EXCEPTION_HANDLER(derr_con);
1271 PROFILE(g_profiler->remove(ThreadIdentifier.str()));
1275 void ConnectionSendThread::Trigger()
1277 m_send_sleep_semaphore.Post();
1280 bool ConnectionSendThread::packetsQueued()
1282 std::list<u16> peerIds = m_connection->getPeerIDs();
1284 if ((this->m_outgoing_queue.size() > 0) && (peerIds.size() > 0))
1287 for(std::list<u16>::iterator j = peerIds.begin();
1288 j != peerIds.end(); ++j)
1290 PeerHelper peer = m_connection->getPeerNoEx(*j);
1295 if (dynamic_cast<UDPPeer*>(&peer) == 0)
1298 for(u16 i=0; i<CHANNEL_COUNT; i++)
1300 Channel *channel = &(dynamic_cast<UDPPeer*>(&peer))->channels[i];
1302 if (channel->queued_commands.size() > 0)
1313 void ConnectionSendThread::runTimeouts(float dtime)
1315 std::list<u16> timeouted_peers;
1316 std::list<u16> peerIds = m_connection->getPeerIDs();
1318 for(std::list<u16>::iterator j = peerIds.begin();
1319 j != peerIds.end(); ++j)
1321 PeerHelper peer = m_connection->getPeerNoEx(*j);
1326 if(dynamic_cast<UDPPeer*>(&peer) == 0)
1329 PROFILE(std::stringstream peerIdentifier);
1330 PROFILE(peerIdentifier << "runTimeouts[" << m_connection->getDesc() << ";" << *j << ";RELIABLE]");
1331 PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier.str(), SPT_AVG));
1333 SharedBuffer<u8> data(2); // data for sending ping, required here because of goto
1338 if(peer->isTimedOut(m_timeout))
1340 LOG(derr_con<<m_connection->getDesc()
1341 <<"RunTimeouts(): Peer "<<peer->id
1343 <<" (source=peer->timeout_counter)"
1345 // Add peer to the list
1346 timeouted_peers.push_back(peer->id);
1347 // Don't bother going through the buffers of this one
1351 float resend_timeout = dynamic_cast<UDPPeer*>(&peer)->getResendTimeout();
1352 for(u16 i=0; i<CHANNEL_COUNT; i++)
1354 std::list<BufferedPacket> timed_outs;
1355 Channel *channel = &(dynamic_cast<UDPPeer*>(&peer))->channels[i];
1357 if (dynamic_cast<UDPPeer*>(&peer)->getLegacyPeer())
1358 channel->setWindowSize(g_settings->getU16("workaround_window_size"));
1360 // Remove timed out incomplete unreliable split packets
1361 channel->incoming_splits.removeUnreliableTimedOuts(dtime, m_timeout);
1363 // Increment reliable packet times
1364 channel->outgoing_reliables_sent.incrementTimeouts(dtime);
1366 unsigned int numpeers = m_connection->m_peers.size();
1371 // Re-send timed out outgoing reliables
1372 timed_outs = channel->
1373 outgoing_reliables_sent.getTimedOuts(resend_timeout,
1374 (m_max_data_packets_per_iteration/numpeers));
1376 channel->UpdatePacketLossCounter(timed_outs.size());
1378 m_iteration_packets_avaialble -= timed_outs.size();
1380 for(std::list<BufferedPacket>::iterator j = timed_outs.begin();
1381 j != timed_outs.end(); ++j)
1383 u16 peer_id = readPeerId(*(j->data));
1384 u8 channelnum = readChannel(*(j->data));
1385 u16 seqnum = readU16(&(j->data[BASE_HEADER_SIZE+1]));
1387 channel->UpdateBytesLost(j->data.getSize());
1389 LOG(derr_con<<m_connection->getDesc()
1390 <<"RE-SENDING timed-out RELIABLE to "
1391 << j->address.serializeString()
1392 << "(t/o="<<resend_timeout<<"): "
1393 <<"from_peer_id="<<peer_id
1394 <<", channel="<<((int)channelnum&0xff)
1395 <<", seqnum="<<seqnum
1400 // do not handle rtt here as we can't decide if this packet was
1401 // lost or really takes more time to transmit
1404 if (!dynamic_cast<UDPPeer*>(&peer)->getLegacyPeer())
1405 channel->UpdateTimers(dtime);
1408 /* send ping if necessary */
1409 if (dynamic_cast<UDPPeer*>(&peer)->Ping(dtime,data)) {
1410 LOG(dout_con<<m_connection->getDesc()
1411 <<"Sending ping for peer_id: "
1412 << dynamic_cast<UDPPeer*>(&peer)->id <<std::endl);
1413 /* this may fail if there ain't a sequence number left */
1414 if (!rawSendAsPacket(dynamic_cast<UDPPeer*>(&peer)->id, 0, data, true))
1416 //retrigger with reduced ping interval
1417 dynamic_cast<UDPPeer*>(&peer)->Ping(4.0,data);
1421 dynamic_cast<UDPPeer*>(&peer)->RunCommandQueues(m_max_packet_size,
1422 m_max_commands_per_iteration,
1423 m_max_packets_requeued);
1426 // Remove timed out peers
1427 for(std::list<u16>::iterator i = timeouted_peers.begin();
1428 i != timeouted_peers.end(); ++i)
1430 LOG(derr_con<<m_connection->getDesc()
1431 <<"RunTimeouts(): Removing peer "<<(*i)<<std::endl);
1432 m_connection->deletePeer(*i, true);
1436 void ConnectionSendThread::rawSend(const BufferedPacket &packet)
1439 m_connection->m_udpSocket.Send(packet.address, *packet.data, packet.data.getSize());
1440 LOG(dout_con <<m_connection->getDesc()
1441 << " rawSend: " << packet.data.getSize() << " bytes sent" << std::endl);
1442 } catch(SendFailedException &e){
1443 LOG(derr_con<<m_connection->getDesc()
1444 <<"Connection::rawSend(): SendFailedException: "
1445 <<packet.address.serializeString()<<std::endl);
1449 void ConnectionSendThread::sendAsPacketReliable(BufferedPacket& p, Channel* channel)
1452 p.absolute_send_time = porting::getTimeMs();
1453 // Buffer the packet
1454 channel->outgoing_reliables_sent.insert(p,
1455 (channel->readOutgoingSequenceNumber() - MAX_RELIABLE_WINDOW_SIZE) % (MAX_RELIABLE_WINDOW_SIZE+1));
1457 catch(AlreadyExistsException &e)
1459 LOG(derr_con<<m_connection->getDesc()
1460 <<"WARNING: Going to send a reliable packet"
1461 <<" in outgoing buffer" <<std::endl);
1469 bool ConnectionSendThread::rawSendAsPacket(u16 peer_id, u8 channelnum,
1470 SharedBuffer<u8> data, bool reliable)
1472 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
1474 LOG(dout_con<<m_connection->getDesc()
1475 <<" INFO: dropped packet for non existent peer_id: " << peer_id << std::endl);
1476 assert(reliable && "trying to send raw packet reliable but no peer found!");
1479 Channel *channel = &(dynamic_cast<UDPPeer*>(&peer)->channels[channelnum]);
1483 bool have_sequence_number_for_raw_packet = true;
1484 u16 seqnum = channel->getOutgoingSequenceNumber(have_sequence_number_for_raw_packet);
1486 if (!have_sequence_number_for_raw_packet)
1489 SharedBuffer<u8> reliable = makeReliablePacket(data, seqnum);
1490 Address peer_address;
1491 peer->getAddress(MINETEST_RELIABLE_UDP,peer_address);
1493 // Add base headers and make a packet
1494 BufferedPacket p = con::makePacket(peer_address, reliable,
1495 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1498 // first check if our send window is already maxed out
1499 if (channel->outgoing_reliables_sent.size()
1500 < channel->getWindowSize()) {
1501 LOG(dout_con<<m_connection->getDesc()
1502 <<" INFO: sending a reliable packet to peer_id " << peer_id
1503 <<" channel: " << channelnum
1504 <<" seqnum: " << seqnum << std::endl);
1505 sendAsPacketReliable(p,channel);
1509 LOG(dout_con<<m_connection->getDesc()
1510 <<" INFO: queueing reliable packet for peer_id: " << peer_id
1511 <<" channel: " << channelnum
1512 <<" seqnum: " << seqnum << std::endl);
1513 channel->queued_reliables.push_back(p);
1519 Address peer_address;
1521 if (peer->getAddress(UDP,peer_address))
1523 // Add base headers and make a packet
1524 BufferedPacket p = con::makePacket(peer_address, data,
1525 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1533 LOG(dout_con<<m_connection->getDesc()
1534 <<" INFO: dropped unreliable packet for peer_id: " << peer_id
1535 <<" because of (yet) missing udp address" << std::endl);
1544 void ConnectionSendThread::processReliableCommand(ConnectionCommand &c)
1550 LOG(dout_con<<m_connection->getDesc()<<"UDP processing reliable CONNCMD_NONE"<<std::endl);
1554 LOG(dout_con<<m_connection->getDesc()<<"UDP processing reliable CONNCMD_SEND"<<std::endl);
1558 case CONNCMD_SEND_TO_ALL:
1559 LOG(dout_con<<m_connection->getDesc()<<"UDP processing CONNCMD_SEND_TO_ALL"<<std::endl);
1560 sendToAllReliable(c);
1563 case CONCMD_CREATE_PEER:
1564 LOG(dout_con<<m_connection->getDesc()<<"UDP processing reliable CONCMD_CREATE_PEER"<<std::endl);
1565 if (!rawSendAsPacket(c.peer_id,c.channelnum,c.data,c.reliable))
1567 /* put to queue if we couldn't send it immediately */
1572 case CONCMD_DISABLE_LEGACY:
1573 LOG(dout_con<<m_connection->getDesc()<<"UDP processing reliable CONCMD_DISABLE_LEGACY"<<std::endl);
1574 if (!rawSendAsPacket(c.peer_id,c.channelnum,c.data,c.reliable))
1576 /* put to queue if we couldn't send it immediately */
1582 case CONNCMD_CONNECT:
1583 case CONNCMD_DISCONNECT:
1585 assert("Got command that shouldn't be reliable as reliable command" == 0);
1587 LOG(dout_con<<m_connection->getDesc()<<" Invalid reliable command type: " << c.type <<std::endl);
1592 void ConnectionSendThread::processNonReliableCommand(ConnectionCommand &c)
1594 assert(!c.reliable);
1598 LOG(dout_con<<m_connection->getDesc()<<" UDP processing CONNCMD_NONE"<<std::endl);
1601 LOG(dout_con<<m_connection->getDesc()<<" UDP processing CONNCMD_SERVE port="
1602 <<c.address.serializeString()<<std::endl);
1605 case CONNCMD_CONNECT:
1606 LOG(dout_con<<m_connection->getDesc()<<" UDP processing CONNCMD_CONNECT"<<std::endl);
1609 case CONNCMD_DISCONNECT:
1610 LOG(dout_con<<m_connection->getDesc()<<" UDP processing CONNCMD_DISCONNECT"<<std::endl);
1613 case CONNCMD_DISCONNECT_PEER:
1614 LOG(dout_con<<m_connection->getDesc()<<" UDP processing CONNCMD_DISCONNECT_PEER"<<std::endl);
1615 disconnect_peer(c.peer_id);
1618 LOG(dout_con<<m_connection->getDesc()<<" UDP processing CONNCMD_SEND"<<std::endl);
1619 send(c.peer_id, c.channelnum, c.data);
1621 case CONNCMD_SEND_TO_ALL:
1622 LOG(dout_con<<m_connection->getDesc()<<" UDP processing CONNCMD_SEND_TO_ALL"<<std::endl);
1623 sendToAll(c.channelnum, c.data);
1626 LOG(dout_con<<m_connection->getDesc()<<" UDP processing CONCMD_ACK"<<std::endl);
1627 sendAsPacket(c.peer_id,c.channelnum,c.data,true);
1629 case CONCMD_CREATE_PEER:
1630 assert("Got command that should be reliable as unreliable command" == 0);
1632 LOG(dout_con<<m_connection->getDesc()<<" Invalid command type: " << c.type <<std::endl);
1636 void ConnectionSendThread::serve(Address bind_address)
1638 LOG(dout_con<<m_connection->getDesc()
1639 <<"UDP serving at port " << bind_address.serializeString() <<std::endl);
1641 m_connection->m_udpSocket.Bind(bind_address);
1642 m_connection->SetPeerID(PEER_ID_SERVER);
1644 catch(SocketException &e){
1648 m_connection->putEvent(ce);
1652 void ConnectionSendThread::connect(Address address)
1654 LOG(dout_con<<m_connection->getDesc()<<" connecting to "<<address.serializeString()
1655 <<":"<<address.getPort()<<std::endl);
1657 UDPPeer *peer = m_connection->createServerPeer(address);
1661 e.peerAdded(peer->id, peer->address);
1662 m_connection->putEvent(e);
1666 if (address.isIPv6())
1667 bind_addr.setAddress((IPv6AddressBytes*) NULL);
1669 bind_addr.setAddress(0,0,0,0);
1671 m_connection->m_udpSocket.Bind(bind_addr);
1673 // Send a dummy packet to server with peer_id = PEER_ID_INEXISTENT
1674 m_connection->SetPeerID(PEER_ID_INEXISTENT);
1675 SharedBuffer<u8> data(0);
1676 m_connection->Send(PEER_ID_SERVER, 0, data, true);
1679 void ConnectionSendThread::disconnect()
1681 LOG(dout_con<<m_connection->getDesc()<<" disconnecting"<<std::endl);
1683 // Create and send DISCO packet
1684 SharedBuffer<u8> data(2);
1685 writeU8(&data[0], TYPE_CONTROL);
1686 writeU8(&data[1], CONTROLTYPE_DISCO);
1690 std::list<u16> peerids = m_connection->getPeerIDs();
1692 for (std::list<u16>::iterator i = peerids.begin();
1696 sendAsPacket(*i, 0,data,false);
1700 void ConnectionSendThread::disconnect_peer(u16 peer_id)
1702 LOG(dout_con<<m_connection->getDesc()<<" disconnecting peer"<<std::endl);
1704 // Create and send DISCO packet
1705 SharedBuffer<u8> data(2);
1706 writeU8(&data[0], TYPE_CONTROL);
1707 writeU8(&data[1], CONTROLTYPE_DISCO);
1708 sendAsPacket(peer_id, 0,data,false);
1710 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
1715 if (dynamic_cast<UDPPeer*>(&peer) == 0)
1720 dynamic_cast<UDPPeer*>(&peer)->m_pending_disconnect = true;
1723 void ConnectionSendThread::send(u16 peer_id, u8 channelnum,
1724 SharedBuffer<u8> data)
1726 assert(channelnum < CHANNEL_COUNT);
1728 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
1731 LOG(dout_con<<m_connection->getDesc()<<" peer: peer_id="<<peer_id
1732 << ">>>NOT<<< found on sending packet"
1733 << ", channel " << (channelnum % 0xFF)
1734 << ", size: " << data.getSize() <<std::endl);
1738 LOG(dout_con<<m_connection->getDesc()<<" sending to peer_id="<<peer_id
1739 << ", channel " << (channelnum % 0xFF)
1740 << ", size: " << data.getSize() <<std::endl);
1742 u16 split_sequence_number = peer->getNextSplitSequenceNumber(channelnum);
1744 u32 chunksize_max = m_max_packet_size - BASE_HEADER_SIZE;
1745 std::list<SharedBuffer<u8> > originals;
1747 originals = makeAutoSplitPacket(data, chunksize_max,split_sequence_number);
1749 peer->setNextSplitSequenceNumber(channelnum,split_sequence_number);
1751 for(std::list<SharedBuffer<u8> >::iterator i = originals.begin();
1752 i != originals.end(); ++i)
1754 SharedBuffer<u8> original = *i;
1755 sendAsPacket(peer_id, channelnum, original);
1759 void ConnectionSendThread::sendReliable(ConnectionCommand &c)
1761 PeerHelper peer = m_connection->getPeerNoEx(c.peer_id);
1765 peer->PutReliableSendCommand(c,m_max_packet_size);
1768 void ConnectionSendThread::sendToAll(u8 channelnum, SharedBuffer<u8> data)
1770 std::list<u16> peerids = m_connection->getPeerIDs();
1772 for (std::list<u16>::iterator i = peerids.begin();
1776 send(*i, channelnum, data);
1780 void ConnectionSendThread::sendToAllReliable(ConnectionCommand &c)
1782 std::list<u16> peerids = m_connection->getPeerIDs();
1784 for (std::list<u16>::iterator i = peerids.begin();
1788 PeerHelper peer = m_connection->getPeerNoEx(*i);
1793 peer->PutReliableSendCommand(c,m_max_packet_size);
1797 void ConnectionSendThread::sendPackets(float dtime)
1799 std::list<u16> peerIds = m_connection->getPeerIDs();
1800 std::list<u16> pendingDisconnect;
1801 std::map<u16,bool> pending_unreliable;
1803 for(std::list<u16>::iterator
1804 j = peerIds.begin();
1805 j != peerIds.end(); ++j)
1807 PeerHelper peer = m_connection->getPeerNoEx(*j);
1808 //peer may have been removed
1810 LOG(dout_con<<m_connection->getDesc()<< " Peer not found: peer_id=" << *j << std::endl);
1813 peer->m_increment_packets_remaining = m_iteration_packets_avaialble/m_connection->m_peers.size();
1815 if (dynamic_cast<UDPPeer*>(&peer) == 0)
1820 if (dynamic_cast<UDPPeer*>(&peer)->m_pending_disconnect)
1822 pendingDisconnect.push_back(*j);
1825 PROFILE(std::stringstream peerIdentifier);
1826 PROFILE(peerIdentifier << "sendPackets[" << m_connection->getDesc() << ";" << *j << ";RELIABLE]");
1827 PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier.str(), SPT_AVG));
1829 LOG(dout_con<<m_connection->getDesc()
1830 << " Handle per peer queues: peer_id=" << *j
1831 << " packet quota: " << peer->m_increment_packets_remaining << std::endl);
1832 // first send queued reliable packets for all peers (if possible)
1833 for (unsigned int i=0; i < CHANNEL_COUNT; i++)
1835 u16 next_to_ack = 0;
1836 dynamic_cast<UDPPeer*>(&peer)->channels[i].outgoing_reliables_sent.getFirstSeqnum(next_to_ack);
1837 u16 next_to_receive = 0;
1838 dynamic_cast<UDPPeer*>(&peer)->channels[i].incoming_reliables.getFirstSeqnum(next_to_receive);
1840 LOG(dout_con<<m_connection->getDesc()<< "\t channel: "
1841 << i << ", peer quota:"
1842 << peer->m_increment_packets_remaining
1844 << "\t\t\treliables on wire: "
1845 << dynamic_cast<UDPPeer*>(&peer)->channels[i].outgoing_reliables_sent.size()
1846 << ", waiting for ack for " << next_to_ack
1848 << "\t\t\tincoming_reliables: "
1849 << dynamic_cast<UDPPeer*>(&peer)->channels[i].incoming_reliables.size()
1850 << ", next reliable packet: "
1851 << dynamic_cast<UDPPeer*>(&peer)->channels[i].readNextIncomingSeqNum()
1852 << ", next queued: " << next_to_receive
1854 << "\t\t\treliables queued : "
1855 << dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.size()
1857 << "\t\t\tqueued commands : "
1858 << dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_commands.size()
1861 while ((dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.size() > 0) &&
1862 (dynamic_cast<UDPPeer*>(&peer)->channels[i].outgoing_reliables_sent.size()
1863 < dynamic_cast<UDPPeer*>(&peer)->channels[i].getWindowSize())&&
1864 (peer->m_increment_packets_remaining > 0))
1866 BufferedPacket p = dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.pop_front();
1867 Channel* channel = &(dynamic_cast<UDPPeer*>(&peer)->channels[i]);
1868 LOG(dout_con<<m_connection->getDesc()
1869 <<" INFO: sending a queued reliable packet "
1871 <<", seqnum: " << readU16(&p.data[BASE_HEADER_SIZE+1])
1873 sendAsPacketReliable(p,channel);
1874 peer->m_increment_packets_remaining--;
1879 if (m_outgoing_queue.size())
1881 LOG(dout_con<<m_connection->getDesc()
1882 << " Handle non reliable queue ("
1883 << m_outgoing_queue.size() << " pkts)" << std::endl);
1886 unsigned int initial_queuesize = m_outgoing_queue.size();
1887 /* send non reliable packets*/
1888 for(unsigned int i=0;i < initial_queuesize;i++) {
1889 OutgoingPacket packet = m_outgoing_queue.pop_front();
1891 assert(!packet.reliable &&
1892 "reliable packets are not allowed in outgoing queue!");
1894 PeerHelper peer = m_connection->getPeerNoEx(packet.peer_id);
1896 LOG(dout_con<<m_connection->getDesc()
1897 <<" Outgoing queue: peer_id="<<packet.peer_id
1898 << ">>>NOT<<< found on sending packet"
1899 << ", channel " << (packet.channelnum % 0xFF)
1900 << ", size: " << packet.data.getSize() <<std::endl);
1903 /* send acks immediately */
1904 else if (packet.ack)
1906 rawSendAsPacket(packet.peer_id, packet.channelnum,
1907 packet.data, packet.reliable);
1908 peer->m_increment_packets_remaining =
1909 MYMIN(0,peer->m_increment_packets_remaining--);
1912 ( peer->m_increment_packets_remaining > 0) ||
1914 rawSendAsPacket(packet.peer_id, packet.channelnum,
1915 packet.data, packet.reliable);
1916 peer->m_increment_packets_remaining--;
1919 m_outgoing_queue.push_back(packet);
1920 pending_unreliable[packet.peer_id] = true;
1924 for(std::list<u16>::iterator
1925 k = pendingDisconnect.begin();
1926 k != pendingDisconnect.end(); ++k)
1928 if (!pending_unreliable[*k])
1930 m_connection->deletePeer(*k,false);
1935 void ConnectionSendThread::sendAsPacket(u16 peer_id, u8 channelnum,
1936 SharedBuffer<u8> data, bool ack)
1938 OutgoingPacket packet(peer_id, channelnum, data, false, ack);
1939 m_outgoing_queue.push_back(packet);
1942 ConnectionReceiveThread::ConnectionReceiveThread(Connection* parent,
1943 unsigned int max_packet_size) :
1944 m_connection(parent),
1945 m_max_packet_size(max_packet_size)
1949 void * ConnectionReceiveThread::Thread()
1952 log_register_thread("ConnectionReceive");
1954 LOG(dout_con<<m_connection->getDesc()
1955 <<"ConnectionReceive thread started"<<std::endl);
1957 PROFILE(std::stringstream ThreadIdentifier);
1958 PROFILE(ThreadIdentifier << "ConnectionReceive: [" << m_connection->getDesc() << "]");
1960 porting::setThreadName("ConnectionReceive");
1962 #ifdef DEBUG_CONNECTION_KBPS
1963 u32 curtime = porting::getTimeMs();
1964 u32 lasttime = curtime;
1965 float debug_print_timer = 0.0;
1968 while(!StopRequested()) {
1969 BEGIN_DEBUG_EXCEPTION_HANDLER
1970 PROFILE(ScopeProfiler sp(g_profiler, ThreadIdentifier.str(), SPT_AVG));
1972 #ifdef DEBUG_CONNECTION_KBPS
1974 curtime = porting::getTimeMs();
1975 float dtime = CALC_DTIME(lasttime,curtime);
1978 /* receive packets */
1981 #ifdef DEBUG_CONNECTION_KBPS
1982 debug_print_timer += dtime;
1983 if (debug_print_timer > 20.0) {
1984 debug_print_timer -= 20.0;
1986 std::list<u16> peerids = m_connection->getPeerIDs();
1988 for (std::list<u16>::iterator i = peerids.begin();
1992 PeerHelper peer = m_connection->getPeerNoEx(*i);
1996 float peer_current = 0.0;
1997 float peer_loss = 0.0;
1998 float avg_rate = 0.0;
1999 float avg_loss = 0.0;
2001 for(u16 j=0; j<CHANNEL_COUNT; j++)
2003 peer_current +=peer->channels[j].getCurrentDownloadRateKB();
2004 peer_loss += peer->channels[j].getCurrentLossRateKB();
2005 avg_rate += peer->channels[j].getAvgDownloadRateKB();
2006 avg_loss += peer->channels[j].getAvgLossRateKB();
2009 std::stringstream output;
2010 output << std::fixed << std::setprecision(1);
2011 output << "OUT to Peer " << *i << " RATES (good / loss) " << std::endl;
2012 output << "\tcurrent (sum): " << peer_current << "kb/s "<< peer_loss << "kb/s" << std::endl;
2013 output << "\taverage (sum): " << avg_rate << "kb/s "<< avg_loss << "kb/s" << std::endl;
2014 output << std::setfill(' ');
2015 for(u16 j=0; j<CHANNEL_COUNT; j++)
2017 output << "\tcha " << j << ":"
2018 << " CUR: " << std::setw(6) << peer->channels[j].getCurrentDownloadRateKB() <<"kb/s"
2019 << " AVG: " << std::setw(6) << peer->channels[j].getAvgDownloadRateKB() <<"kb/s"
2020 << " MAX: " << std::setw(6) << peer->channels[j].getMaxDownloadRateKB() <<"kb/s"
2022 << " CUR: " << std::setw(6) << peer->channels[j].getCurrentLossRateKB() <<"kb/s"
2023 << " AVG: " << std::setw(6) << peer->channels[j].getAvgLossRateKB() <<"kb/s"
2024 << " MAX: " << std::setw(6) << peer->channels[j].getMaxLossRateKB() <<"kb/s"
2025 << " / WS: " << peer->channels[j].getWindowSize()
2029 fprintf(stderr,"%s\n",output.str().c_str());
2033 END_DEBUG_EXCEPTION_HANDLER(derr_con);
2035 PROFILE(g_profiler->remove(ThreadIdentifier.str()));
2039 // Receive packets from the network and buffers and create ConnectionEvents
2040 void ConnectionReceiveThread::receive()
2042 // use IPv6 minimum allowed MTU as receive buffer size as this is
2043 // theoretical reliable upper boundary of a udp packet for all IPv6 enabled
2045 unsigned int packet_maxsize = 1500;
2046 SharedBuffer<u8> packetdata(packet_maxsize);
2048 bool packet_queued = true;
2050 unsigned int loop_count = 0;
2052 /* first of all read packets from socket */
2053 /* check for incoming data available */
2054 while( (loop_count < 10) &&
2055 (m_connection->m_udpSocket.WaitData(50)))
2061 bool no_data_left = false;
2063 SharedBuffer<u8> resultdata;
2064 while(!no_data_left)
2067 no_data_left = !getFromBuffers(peer_id, resultdata);
2068 if (!no_data_left) {
2070 e.dataReceived(peer_id, resultdata);
2071 m_connection->putEvent(e);
2074 catch(ProcessedSilentlyException &e) {
2075 /* try reading again */
2078 packet_queued = false;
2082 s32 received_size = m_connection->m_udpSocket.Receive(sender, *packetdata, packet_maxsize);
2084 if ((received_size < 0) ||
2085 (received_size < BASE_HEADER_SIZE) ||
2086 (readU32(&packetdata[0]) != m_connection->GetProtocolID()))
2088 LOG(derr_con<<m_connection->getDesc()
2089 <<"Receive(): Invalid incoming packet, "
2090 <<"size: " << received_size
2091 <<", protocol: " << readU32(&packetdata[0]) <<std::endl);
2095 u16 peer_id = readPeerId(*packetdata);
2096 u8 channelnum = readChannel(*packetdata);
2098 if(channelnum > CHANNEL_COUNT-1){
2099 LOG(derr_con<<m_connection->getDesc()
2100 <<"Receive(): Invalid channel "<<channelnum<<std::endl);
2101 throw InvalidIncomingDataException("Channel doesn't exist");
2104 /* preserve original peer_id for later usage */
2105 u16 packet_peer_id = peer_id;
2107 /* Try to identify peer by sender address (may happen on join) */
2108 if(peer_id == PEER_ID_INEXISTENT)
2110 peer_id = m_connection->lookupPeer(sender);
2113 /* The peer was not found in our lists. Add it. */
2114 if(peer_id == PEER_ID_INEXISTENT)
2116 peer_id = m_connection->createPeer(sender,MINETEST_RELIABLE_UDP,0);
2119 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
2122 LOG(dout_con<<m_connection->getDesc()
2123 <<" got packet from unknown peer_id: "
2124 <<peer_id<<" Ignoring."<<std::endl);
2128 // Validate peer address
2130 Address peer_address;
2132 if (peer->getAddress(UDP,peer_address)) {
2133 if (peer_address != sender) {
2134 LOG(derr_con<<m_connection->getDesc()
2135 <<m_connection->getDesc()
2136 <<" Peer "<<peer_id<<" sending from different address."
2137 " Ignoring."<<std::endl);
2143 bool invalid_address = true;
2144 if (invalid_address) {
2145 LOG(derr_con<<m_connection->getDesc()
2146 <<m_connection->getDesc()
2147 <<" Peer "<<peer_id<<" unknown."
2148 " Ignoring."<<std::endl);
2154 /* mark peer as seen with id */
2155 if (!(packet_peer_id == PEER_ID_INEXISTENT))
2156 peer->setSentWithID();
2158 peer->ResetTimeout();
2160 Channel *channel = 0;
2162 if (dynamic_cast<UDPPeer*>(&peer) != 0)
2164 channel = &(dynamic_cast<UDPPeer*>(&peer)->channels[channelnum]);
2167 // Throw the received packet to channel->processPacket()
2169 // Make a new SharedBuffer from the data without the base headers
2170 SharedBuffer<u8> strippeddata(received_size - BASE_HEADER_SIZE);
2171 memcpy(*strippeddata, &packetdata[BASE_HEADER_SIZE],
2172 strippeddata.getSize());
2175 // Process it (the result is some data with no headers made by us)
2176 SharedBuffer<u8> resultdata = processPacket
2177 (channel, strippeddata, peer_id, channelnum, false);
2179 LOG(dout_con<<m_connection->getDesc()
2180 <<" ProcessPacket from peer_id: " << peer_id
2181 << ",channel: " << (channelnum & 0xFF) << ", returned "
2182 << resultdata.getSize() << " bytes" <<std::endl);
2185 e.dataReceived(peer_id, resultdata);
2186 m_connection->putEvent(e);
2187 }catch(ProcessedSilentlyException &e){
2188 }catch(ProcessedQueued &e){
2189 packet_queued = true;
2191 }catch(InvalidIncomingDataException &e){
2193 catch(ProcessedSilentlyException &e){
2198 bool ConnectionReceiveThread::getFromBuffers(u16 &peer_id, SharedBuffer<u8> &dst)
2200 std::list<u16> peerids = m_connection->getPeerIDs();
2202 for(std::list<u16>::iterator j = peerids.begin();
2203 j != peerids.end(); ++j)
2205 PeerHelper peer = m_connection->getPeerNoEx(*j);
2209 if(dynamic_cast<UDPPeer*>(&peer) == 0)
2212 for(u16 i=0; i<CHANNEL_COUNT; i++)
2214 Channel *channel = &(dynamic_cast<UDPPeer*>(&peer))->channels[i];
2216 SharedBuffer<u8> resultdata;
2217 bool got = checkIncomingBuffers(channel, peer_id, resultdata);
2227 bool ConnectionReceiveThread::checkIncomingBuffers(Channel *channel, u16 &peer_id,
2228 SharedBuffer<u8> &dst)
2230 u16 firstseqnum = 0;
2231 if (channel->incoming_reliables.getFirstSeqnum(firstseqnum))
2233 if(firstseqnum == channel->readNextIncomingSeqNum())
2235 BufferedPacket p = channel->incoming_reliables.popFirst();
2236 peer_id = readPeerId(*p.data);
2237 u8 channelnum = readChannel(*p.data);
2238 u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]);
2240 LOG(dout_con<<m_connection->getDesc()
2241 <<"UNBUFFERING TYPE_RELIABLE"
2242 <<" seqnum="<<seqnum
2243 <<" peer_id="<<peer_id
2244 <<" channel="<<((int)channelnum&0xff)
2247 channel->incNextIncomingSeqNum();
2249 u32 headers_size = BASE_HEADER_SIZE + RELIABLE_HEADER_SIZE;
2250 // Get out the inside packet and re-process it
2251 SharedBuffer<u8> payload(p.data.getSize() - headers_size);
2252 memcpy(*payload, &p.data[headers_size], payload.getSize());
2254 dst = processPacket(channel, payload, peer_id, channelnum, true);
2261 SharedBuffer<u8> ConnectionReceiveThread::processPacket(Channel *channel,
2262 SharedBuffer<u8> packetdata, u16 peer_id,
2263 u8 channelnum, bool reliable)
2265 PeerHelper peer = m_connection->getPeer(peer_id);
2267 if(packetdata.getSize() < 1)
2268 throw InvalidIncomingDataException("packetdata.getSize() < 1");
2270 u8 type = readU8(&packetdata[0]);
2272 if(type == TYPE_CONTROL)
2274 if(packetdata.getSize() < 2)
2275 throw InvalidIncomingDataException("packetdata.getSize() < 2");
2277 u8 controltype = readU8(&packetdata[1]);
2279 if( (controltype == CONTROLTYPE_ACK)
2280 && (peer_id <= MAX_UDP_PEERS))
2282 assert(channel != 0);
2283 if(packetdata.getSize() < 4)
2284 throw InvalidIncomingDataException
2285 ("packetdata.getSize() < 4 (ACK header size)");
2287 u16 seqnum = readU16(&packetdata[2]);
2288 LOG(dout_con<<m_connection->getDesc()
2289 <<" [ CONTROLTYPE_ACK: channelnum="
2290 <<((int)channelnum&0xff)<<", peer_id="<<peer_id
2291 <<", seqnum="<<seqnum<< " ]"<<std::endl);
2295 channel->outgoing_reliables_sent.popSeqnum(seqnum);
2296 // Get round trip time
2297 unsigned int current_time = porting::getTimeMs();
2299 if (current_time > p.absolute_send_time)
2301 float rtt = (current_time - p.absolute_send_time) / 1000.0;
2303 // Let peer calculate stuff according to it
2304 // (avg_rtt and resend_timeout)
2305 dynamic_cast<UDPPeer*>(&peer)->reportRTT(rtt);
2307 else if (p.totaltime > 0)
2309 float rtt = p.totaltime;
2311 // Let peer calculate stuff according to it
2312 // (avg_rtt and resend_timeout)
2313 dynamic_cast<UDPPeer*>(&peer)->reportRTT(rtt);
2315 //put bytes for max bandwidth calculation
2316 channel->UpdateBytesSent(p.data.getSize(),1);
2317 if (channel->outgoing_reliables_sent.size() == 0)
2319 m_connection->TriggerSend();
2322 catch(NotFoundException &e){
2323 LOG(derr_con<<m_connection->getDesc()
2324 <<"WARNING: ACKed packet not "
2327 channel->UpdatePacketTooLateCounter();
2329 throw ProcessedSilentlyException("Got an ACK");
2331 else if((controltype == CONTROLTYPE_SET_PEER_ID)
2332 && (peer_id <= MAX_UDP_PEERS))
2334 // Got a packet to set our peer id
2335 if(packetdata.getSize() < 4)
2336 throw InvalidIncomingDataException
2337 ("packetdata.getSize() < 4 (SET_PEER_ID header size)");
2338 u16 peer_id_new = readU16(&packetdata[2]);
2339 LOG(dout_con<<m_connection->getDesc()
2340 <<"Got new peer id: "<<peer_id_new<<"... "<<std::endl);
2342 if(m_connection->GetPeerID() != PEER_ID_INEXISTENT)
2344 LOG(derr_con<<m_connection->getDesc()
2345 <<"WARNING: Not changing"
2346 " existing peer id."<<std::endl);
2350 LOG(dout_con<<m_connection->getDesc()<<"changing own peer id"<<std::endl);
2351 m_connection->SetPeerID(peer_id_new);
2354 ConnectionCommand cmd;
2356 SharedBuffer<u8> reply(2);
2357 writeU8(&reply[0], TYPE_CONTROL);
2358 writeU8(&reply[1], CONTROLTYPE_ENABLE_BIG_SEND_WINDOW);
2359 cmd.disableLegacy(PEER_ID_SERVER,reply);
2360 m_connection->putCommand(cmd);
2362 throw ProcessedSilentlyException("Got a SET_PEER_ID");
2364 else if((controltype == CONTROLTYPE_PING)
2365 && (peer_id <= MAX_UDP_PEERS))
2367 // Just ignore it, the incoming data already reset
2368 // the timeout counter
2369 LOG(dout_con<<m_connection->getDesc()<<"PING"<<std::endl);
2370 throw ProcessedSilentlyException("Got a PING");
2372 else if(controltype == CONTROLTYPE_DISCO)
2374 // Just ignore it, the incoming data already reset
2375 // the timeout counter
2376 LOG(dout_con<<m_connection->getDesc()
2377 <<"DISCO: Removing peer "<<(peer_id)<<std::endl);
2379 if(m_connection->deletePeer(peer_id, false) == false)
2381 derr_con<<m_connection->getDesc()
2382 <<"DISCO: Peer not found"<<std::endl;
2385 throw ProcessedSilentlyException("Got a DISCO");
2387 else if((controltype == CONTROLTYPE_ENABLE_BIG_SEND_WINDOW)
2388 && (peer_id <= MAX_UDP_PEERS))
2390 dynamic_cast<UDPPeer*>(&peer)->setNonLegacyPeer();
2391 throw ProcessedSilentlyException("Got non legacy control");
2394 LOG(derr_con<<m_connection->getDesc()
2395 <<"INVALID TYPE_CONTROL: invalid controltype="
2396 <<((int)controltype&0xff)<<std::endl);
2397 throw InvalidIncomingDataException("Invalid control type");
2400 else if(type == TYPE_ORIGINAL)
2402 if(packetdata.getSize() < ORIGINAL_HEADER_SIZE)
2403 throw InvalidIncomingDataException
2404 ("packetdata.getSize() < ORIGINAL_HEADER_SIZE");
2405 LOG(dout_con<<m_connection->getDesc()
2406 <<"RETURNING TYPE_ORIGINAL to user"
2408 // Get the inside packet out and return it
2409 SharedBuffer<u8> payload(packetdata.getSize() - ORIGINAL_HEADER_SIZE);
2410 memcpy(*payload, &packetdata[ORIGINAL_HEADER_SIZE], payload.getSize());
2413 else if(type == TYPE_SPLIT)
2415 Address peer_address;
2417 if (peer->getAddress(UDP,peer_address)) {
2419 // We have to create a packet again for buffering
2420 // This isn't actually too bad an idea.
2421 BufferedPacket packet = makePacket(
2424 m_connection->GetProtocolID(),
2428 // Buffer the packet
2429 SharedBuffer<u8> data =
2430 peer->addSpiltPacket(channelnum,packet,reliable);
2432 if(data.getSize() != 0)
2434 LOG(dout_con<<m_connection->getDesc()
2435 <<"RETURNING TYPE_SPLIT: Constructed full data, "
2436 <<"size="<<data.getSize()<<std::endl);
2439 LOG(dout_con<<m_connection->getDesc()<<"BUFFERED TYPE_SPLIT"<<std::endl);
2440 throw ProcessedSilentlyException("Buffered a split packet chunk");
2443 //TODO throw some error
2446 else if((peer_id <= MAX_UDP_PEERS) && (type == TYPE_RELIABLE))
2448 assert(channel != 0);
2449 // Recursive reliable packets not allowed
2451 throw InvalidIncomingDataException("Found nested reliable packets");
2453 if(packetdata.getSize() < RELIABLE_HEADER_SIZE)
2454 throw InvalidIncomingDataException
2455 ("packetdata.getSize() < RELIABLE_HEADER_SIZE");
2457 u16 seqnum = readU16(&packetdata[1]);
2458 bool is_future_packet = false;
2459 bool is_old_packet = false;
2461 /* packet is within our receive window send ack */
2462 if (seqnum_in_window(seqnum, channel->readNextIncomingSeqNum(),MAX_RELIABLE_WINDOW_SIZE))
2464 m_connection->sendAck(peer_id,channelnum,seqnum);
2467 is_future_packet = seqnum_higher(seqnum, channel->readNextIncomingSeqNum());
2468 is_old_packet = seqnum_higher(channel->readNextIncomingSeqNum(), seqnum);
2471 /* packet is not within receive window, don't send ack. *
2472 * if this was a valid packet it's gonna be retransmitted */
2473 if (is_future_packet)
2475 throw ProcessedSilentlyException("Received packet newer then expected, not sending ack");
2478 /* seems like our ack was lost, send another one for a old packet */
2481 LOG(dout_con<<m_connection->getDesc()
2482 << "RE-SENDING ACK: peer_id: " << peer_id
2483 << ", channel: " << (channelnum&0xFF)
2484 << ", seqnum: " << seqnum << std::endl;)
2485 m_connection->sendAck(peer_id,channelnum,seqnum);
2487 // we already have this packet so this one was on wire at least
2488 // the current timeout
2489 dynamic_cast<UDPPeer*>(&peer)->reportRTT(dynamic_cast<UDPPeer*>(&peer)->getResendTimeout());
2491 throw ProcessedSilentlyException("Retransmitting ack for old packet");
2495 if (seqnum != channel->readNextIncomingSeqNum())
2497 Address peer_address;
2499 // this is a reliable packet so we have a udp address for sure
2500 peer->getAddress(MINETEST_RELIABLE_UDP,peer_address);
2501 // This one comes later, buffer it.
2502 // Actually we have to make a packet to buffer one.
2503 // Well, we have all the ingredients, so just do it.
2504 BufferedPacket packet = con::makePacket(
2507 m_connection->GetProtocolID(),
2511 channel->incoming_reliables.insert(packet,channel->readNextIncomingSeqNum());
2513 LOG(dout_con<<m_connection->getDesc()
2514 << "BUFFERING, TYPE_RELIABLE peer_id: " << peer_id
2515 << ", channel: " << (channelnum&0xFF)
2516 << ", seqnum: " << seqnum << std::endl;)
2518 throw ProcessedQueued("Buffered future reliable packet");
2520 catch(AlreadyExistsException &e)
2523 catch(IncomingDataCorruption &e)
2525 ConnectionCommand discon;
2526 discon.disconnect_peer(peer_id);
2527 m_connection->putCommand(discon);
2529 LOG(derr_con<<m_connection->getDesc()
2530 << "INVALID, TYPE_RELIABLE peer_id: " << peer_id
2531 << ", channel: " << (channelnum&0xFF)
2532 << ", seqnum: " << seqnum
2533 << "DROPPING CLIENT!" << std::endl;)
2537 /* we got a packet to process right now */
2538 LOG(dout_con<<m_connection->getDesc()
2539 << "RECURSIVE, TYPE_RELIABLE peer_id: " << peer_id
2540 << ", channel: " << (channelnum&0xFF)
2541 << ", seqnum: " << seqnum << std::endl;)
2544 /* check for resend case */
2545 u16 queued_seqnum = 0;
2546 if (channel->incoming_reliables.getFirstSeqnum(queued_seqnum))
2548 if (queued_seqnum == seqnum)
2550 BufferedPacket queued_packet = channel->incoming_reliables.popFirst();
2551 /** TODO find a way to verify the new against the old packet */
2555 channel->incNextIncomingSeqNum();
2557 // Get out the inside packet and re-process it
2558 SharedBuffer<u8> payload(packetdata.getSize() - RELIABLE_HEADER_SIZE);
2559 memcpy(*payload, &packetdata[RELIABLE_HEADER_SIZE], payload.getSize());
2561 return processPacket(channel, payload, peer_id, channelnum, true);
2565 derr_con<<m_connection->getDesc()
2566 <<"Got invalid type="<<((int)type&0xff)<<std::endl;
2567 throw InvalidIncomingDataException("Invalid packet type");
2570 // We should never get here.
2571 // If you get here, add an exception or a return to some of the
2572 // above conditionals.
2574 throw BaseException("Error in Channel::ProcessPacket()");
2581 Connection::Connection(u32 protocol_id, u32 max_packet_size, float timeout,
2587 m_protocol_id(protocol_id),
2588 m_sendThread(this, max_packet_size, timeout),
2589 m_receiveThread(this, max_packet_size),
2591 m_bc_peerhandler(0),
2592 m_bc_receive_timeout(0),
2593 m_shutting_down(false),
2594 m_next_remote_peer_id(2)
2596 m_udpSocket.setTimeoutMs(5);
2598 m_sendThread.Start();
2599 m_receiveThread.Start();
2602 Connection::Connection(u32 protocol_id, u32 max_packet_size, float timeout,
2603 bool ipv6, PeerHandler *peerhandler):
2608 m_protocol_id(protocol_id),
2609 m_sendThread(this, max_packet_size, timeout),
2610 m_receiveThread(this, max_packet_size),
2612 m_bc_peerhandler(peerhandler),
2613 m_bc_receive_timeout(0),
2614 m_shutting_down(false),
2615 m_next_remote_peer_id(2)
2618 m_udpSocket.setTimeoutMs(5);
2620 m_sendThread.Start();
2621 m_receiveThread.Start();
2626 Connection::~Connection()
2628 m_shutting_down = true;
2629 // request threads to stop
2630 m_sendThread.Stop();
2631 m_receiveThread.Stop();
2633 //TODO for some unkonwn reason send/receive threads do not exit as they're
2634 // supposed to be but wait on peer timeout. To speed up shutdown we reduce
2635 // timeout to half a second.
2636 m_sendThread.setPeerTimeout(0.5);
2638 // wait for threads to finish
2639 m_sendThread.Wait();
2640 m_receiveThread.Wait();
2643 for(std::map<u16, Peer*>::iterator
2644 j = m_peers.begin();
2645 j != m_peers.end(); ++j)
2651 /* Internal stuff */
2652 void Connection::putEvent(ConnectionEvent &e)
2654 assert(e.type != CONNEVENT_NONE);
2655 m_event_queue.push_back(e);
2658 PeerHelper Connection::getPeer(u16 peer_id)
2660 JMutexAutoLock peerlock(m_peers_mutex);
2661 std::map<u16, Peer*>::iterator node = m_peers.find(peer_id);
2663 if(node == m_peers.end()){
2664 throw PeerNotFoundException("GetPeer: Peer not found (possible timeout)");
2668 assert(node->second->id == peer_id);
2670 return PeerHelper(node->second);
2673 PeerHelper Connection::getPeerNoEx(u16 peer_id)
2675 JMutexAutoLock peerlock(m_peers_mutex);
2676 std::map<u16, Peer*>::iterator node = m_peers.find(peer_id);
2678 if(node == m_peers.end()){
2679 return PeerHelper(NULL);
2683 assert(node->second->id == peer_id);
2685 return PeerHelper(node->second);
2688 /* find peer_id for address */
2689 u16 Connection::lookupPeer(Address& sender)
2691 JMutexAutoLock peerlock(m_peers_mutex);
2692 std::map<u16, Peer*>::iterator j;
2693 j = m_peers.begin();
2694 for(; j != m_peers.end(); ++j)
2696 Peer *peer = j->second;
2697 if(peer->isActive())
2702 if ((peer->getAddress(MINETEST_RELIABLE_UDP,tocheck)) && (tocheck == sender))
2705 if ((peer->getAddress(UDP,tocheck)) && (tocheck == sender))
2709 return PEER_ID_INEXISTENT;
2712 std::list<Peer*> Connection::getPeers()
2714 std::list<Peer*> list;
2715 for(std::map<u16, Peer*>::iterator j = m_peers.begin();
2716 j != m_peers.end(); ++j)
2718 Peer *peer = j->second;
2719 list.push_back(peer);
2724 bool Connection::deletePeer(u16 peer_id, bool timeout)
2728 /* lock list as short as possible */
2730 JMutexAutoLock peerlock(m_peers_mutex);
2731 if(m_peers.find(peer_id) == m_peers.end())
2733 peer = m_peers[peer_id];
2734 m_peers.erase(peer_id);
2737 Address peer_address;
2738 //any peer has a primary address this never fails!
2739 peer->getAddress(PRIMARY,peer_address);
2742 e.peerRemoved(peer_id, timeout, peer_address);
2752 ConnectionEvent Connection::getEvent()
2754 if(m_event_queue.empty()){
2756 e.type = CONNEVENT_NONE;
2759 return m_event_queue.pop_frontNoEx();
2762 ConnectionEvent Connection::waitEvent(u32 timeout_ms)
2765 return m_event_queue.pop_front(timeout_ms);
2766 } catch(ItemNotFoundException &ex){
2768 e.type = CONNEVENT_NONE;
2773 void Connection::putCommand(ConnectionCommand &c)
2775 if (!m_shutting_down)
2777 m_command_queue.push_back(c);
2778 m_sendThread.Trigger();
2782 void Connection::Serve(Address bind_addr)
2784 ConnectionCommand c;
2789 void Connection::Connect(Address address)
2791 ConnectionCommand c;
2796 bool Connection::Connected()
2798 JMutexAutoLock peerlock(m_peers_mutex);
2800 if(m_peers.size() != 1)
2803 std::map<u16, Peer*>::iterator node = m_peers.find(PEER_ID_SERVER);
2804 if(node == m_peers.end())
2807 if(m_peer_id == PEER_ID_INEXISTENT)
2813 void Connection::Disconnect()
2815 ConnectionCommand c;
2820 u32 Connection::Receive(u16 &peer_id, SharedBuffer<u8> &data)
2823 ConnectionEvent e = waitEvent(m_bc_receive_timeout);
2824 if(e.type != CONNEVENT_NONE)
2825 LOG(dout_con<<getDesc()<<": Receive: got event: "
2826 <<e.describe()<<std::endl);
2828 case CONNEVENT_NONE:
2829 throw NoIncomingDataException("No incoming data");
2830 case CONNEVENT_DATA_RECEIVED:
2831 peer_id = e.peer_id;
2832 data = SharedBuffer<u8>(e.data);
2833 return e.data.getSize();
2834 case CONNEVENT_PEER_ADDED: {
2835 UDPPeer tmp(e.peer_id, e.address, this);
2836 if(m_bc_peerhandler)
2837 m_bc_peerhandler->peerAdded(&tmp);
2839 case CONNEVENT_PEER_REMOVED: {
2840 UDPPeer tmp(e.peer_id, e.address, this);
2841 if(m_bc_peerhandler)
2842 m_bc_peerhandler->deletingPeer(&tmp, e.timeout);
2844 case CONNEVENT_BIND_FAILED:
2845 throw ConnectionBindFailed("Failed to bind socket "
2846 "(port already in use?)");
2849 throw NoIncomingDataException("No incoming data");
2852 void Connection::SendToAll(u8 channelnum, SharedBuffer<u8> data, bool reliable)
2854 assert(channelnum < CHANNEL_COUNT);
2856 ConnectionCommand c;
2857 c.sendToAll(channelnum, data, reliable);
2861 void Connection::Send(u16 peer_id, u8 channelnum,
2862 SharedBuffer<u8> data, bool reliable)
2864 assert(channelnum < CHANNEL_COUNT);
2866 ConnectionCommand c;
2867 c.send(peer_id, channelnum, data, reliable);
2871 Address Connection::GetPeerAddress(u16 peer_id)
2873 PeerHelper peer = getPeerNoEx(peer_id);
2876 throw PeerNotFoundException("No address for peer found!");
2877 Address peer_address;
2878 peer->getAddress(PRIMARY,peer_address);
2879 return peer_address;
2882 float Connection::getPeerStat(u16 peer_id, rtt_stat_type type)
2884 PeerHelper peer = getPeerNoEx(peer_id);
2885 if (!peer) return -1;
2886 return peer->getStat(type);
2889 u16 Connection::createPeer(Address& sender, MTProtocols protocol, int fd)
2891 // Somebody wants to make a new connection
2893 // Get a unique peer id (2 or higher)
2894 u16 peer_id_new = m_next_remote_peer_id;
2895 u16 overflow = MAX_UDP_PEERS;
2898 Find an unused peer id
2901 JMutexAutoLock lock(m_peers_mutex);
2902 bool out_of_ids = false;
2906 if(m_peers.find(peer_id_new) == m_peers.end())
2908 // Check for overflow
2909 if(peer_id_new == overflow){
2916 errorstream<<getDesc()<<" ran out of peer ids"<<std::endl;
2917 return PEER_ID_INEXISTENT;
2922 peer = new UDPPeer(peer_id_new, sender, this);
2924 m_peers[peer->id] = peer;
2927 m_next_remote_peer_id = (peer_id_new +1) % MAX_UDP_PEERS;
2929 LOG(dout_con<<getDesc()
2930 <<"createPeer(): giving peer_id="<<peer_id_new<<std::endl);
2932 ConnectionCommand cmd;
2933 SharedBuffer<u8> reply(4);
2934 writeU8(&reply[0], TYPE_CONTROL);
2935 writeU8(&reply[1], CONTROLTYPE_SET_PEER_ID);
2936 writeU16(&reply[2], peer_id_new);
2937 cmd.createPeer(peer_id_new,reply);
2938 this->putCommand(cmd);
2940 // Create peer addition event
2942 e.peerAdded(peer_id_new, sender);
2945 // We're now talking to a valid peer_id
2949 void Connection::PrintInfo(std::ostream &out)
2951 m_info_mutex.Lock();
2952 out<<getDesc()<<": ";
2953 m_info_mutex.Unlock();
2956 void Connection::PrintInfo()
2958 PrintInfo(dout_con);
2961 const std::string Connection::getDesc()
2963 return std::string("con(")+itos(m_udpSocket.GetHandle())+"/"+itos(m_peer_id)+")";
2966 void Connection::DisconnectPeer(u16 peer_id)
2968 ConnectionCommand discon;
2969 discon.disconnect_peer(peer_id);
2973 void Connection::sendAck(u16 peer_id, u8 channelnum, u16 seqnum) {
2975 assert(channelnum < CHANNEL_COUNT);
2977 LOG(dout_con<<getDesc()
2978 <<" Queuing ACK command to peer_id: " << peer_id <<
2979 " channel: " << (channelnum & 0xFF) <<
2980 " seqnum: " << seqnum << std::endl);
2982 ConnectionCommand c;
2983 SharedBuffer<u8> ack(4);
2984 writeU8(&ack[0], TYPE_CONTROL);
2985 writeU8(&ack[1], CONTROLTYPE_ACK);
2986 writeU16(&ack[2], seqnum);
2988 c.ack(peer_id, channelnum, ack);
2990 m_sendThread.Trigger();
2993 UDPPeer* Connection::createServerPeer(Address& address)
2995 if (getPeerNoEx(PEER_ID_SERVER) != 0)
2997 throw ConnectionException("Already connected to a server");
3000 UDPPeer *peer = new UDPPeer(PEER_ID_SERVER, address, this);
3003 JMutexAutoLock lock(m_peers_mutex);
3004 m_peers[peer->id] = peer;
3010 std::list<u16> Connection::getPeerIDs()
3012 std::list<u16> retval;
3014 JMutexAutoLock lock(m_peers_mutex);
3015 for(std::map<u16, Peer*>::iterator j = m_peers.begin();
3016 j != m_peers.end(); ++j)
3018 retval.push_back(j->first);