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 /* this mutex is used to achieve log message consistency */
38 JMutex log_message_mutex;
41 JMutexAutoLock loglock(log_message_mutex); \
45 /******************************************************************************/
46 /* defines used for debugging and profiling */
47 /******************************************************************************/
51 //#define DEBUG_CONNECTION_KBPS
52 #undef DEBUG_CONNECTION_KBPS
55 static inline float CALC_DTIME(unsigned int lasttime, unsigned int curtime) {
56 float value = ( curtime - lasttime) / 1000.0;
57 return MYMAX(MYMIN(value,0.1),0.0);
60 /* maximum window size to use, 0xFFFF is theoretical maximum don't think about
61 * touching it, the less you're away from it the more likely data corruption
64 #define MAX_RELIABLE_WINDOW_SIZE 0x8000
65 /* starting value for window size */
66 #define MIN_RELIABLE_WINDOW_SIZE 0x40
68 #define MAX_UDP_PEERS 65535
70 #define PING_TIMEOUT 5.0
72 static u16 readPeerId(u8 *packetdata)
74 return readU16(&packetdata[4]);
76 static u8 readChannel(u8 *packetdata)
78 return readU8(&packetdata[6]);
81 BufferedPacket makePacket(Address &address, u8 *data, u32 datasize,
82 u32 protocol_id, u16 sender_peer_id, u8 channel)
84 u32 packet_size = datasize + BASE_HEADER_SIZE;
85 BufferedPacket p(packet_size);
88 writeU32(&p.data[0], protocol_id);
89 writeU16(&p.data[4], sender_peer_id);
90 writeU8(&p.data[6], channel);
92 memcpy(&p.data[BASE_HEADER_SIZE], data, datasize);
97 BufferedPacket makePacket(Address &address, SharedBuffer<u8> &data,
98 u32 protocol_id, u16 sender_peer_id, u8 channel)
100 return makePacket(address, *data, data.getSize(),
101 protocol_id, sender_peer_id, channel);
104 SharedBuffer<u8> makeOriginalPacket(
105 SharedBuffer<u8> data)
108 u32 packet_size = data.getSize() + header_size;
109 SharedBuffer<u8> b(packet_size);
111 writeU8(&b[0], TYPE_ORIGINAL);
113 memcpy(&b[header_size], *data, data.getSize());
118 std::list<SharedBuffer<u8> > makeSplitPacket(
119 SharedBuffer<u8> data,
123 // Chunk packets, containing the TYPE_SPLIT header
124 std::list<SharedBuffer<u8> > chunks;
126 u32 chunk_header_size = 7;
127 u32 maximum_data_size = chunksize_max - chunk_header_size;
133 end = start + maximum_data_size - 1;
134 if(end > data.getSize() - 1)
135 end = data.getSize() - 1;
137 u32 payload_size = end - start + 1;
138 u32 packet_size = chunk_header_size + payload_size;
140 SharedBuffer<u8> chunk(packet_size);
142 writeU8(&chunk[0], TYPE_SPLIT);
143 writeU16(&chunk[1], seqnum);
144 // [3] u16 chunk_count is written at next stage
145 writeU16(&chunk[5], chunk_num);
146 memcpy(&chunk[chunk_header_size], &data[start], payload_size);
148 chunks.push_back(chunk);
154 while(end != data.getSize() - 1);
156 for(std::list<SharedBuffer<u8> >::iterator i = chunks.begin();
157 i != chunks.end(); ++i)
160 writeU16(&((*i)[3]), chunk_count);
166 std::list<SharedBuffer<u8> > makeAutoSplitPacket(
167 SharedBuffer<u8> data,
171 u32 original_header_size = 1;
172 std::list<SharedBuffer<u8> > list;
173 if(data.getSize() + original_header_size > chunksize_max)
175 list = makeSplitPacket(data, chunksize_max, split_seqnum);
181 list.push_back(makeOriginalPacket(data));
186 SharedBuffer<u8> makeReliablePacket(
187 SharedBuffer<u8> data,
190 /*dstream<<"BEGIN SharedBuffer<u8> makeReliablePacket()"<<std::endl;
191 dstream<<"data.getSize()="<<data.getSize()<<", data[0]="
192 <<((unsigned int)data[0]&0xff)<<std::endl;*/
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());
202 /*dstream<<"data.getSize()="<<data.getSize()<<", data[0]="
203 <<((unsigned int)data[0]&0xff)<<std::endl;*/
204 //dstream<<"END SharedBuffer<u8> makeReliablePacket()"<<std::endl;
212 ReliablePacketBuffer::ReliablePacketBuffer(): m_list_size(0),writeptr(0) {}
214 void ReliablePacketBuffer::print()
216 JMutexAutoLock listlock(m_list_mutex);
217 LOG(dout_con<<"Dump of ReliablePacketBuffer:" << std::endl);
218 unsigned int index = 0;
219 for(std::list<BufferedPacket>::iterator i = m_list.begin();
223 u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
224 LOG(dout_con<<index<< ":" << s << std::endl);
228 bool ReliablePacketBuffer::empty()
230 JMutexAutoLock listlock(m_list_mutex);
231 return m_list.empty();
234 u32 ReliablePacketBuffer::size()
239 bool ReliablePacketBuffer::containsPacket(u16 seqnum)
241 return !(findPacket(seqnum) == m_list.end());
244 RPBSearchResult ReliablePacketBuffer::findPacket(u16 seqnum)
246 std::list<BufferedPacket>::iterator i = m_list.begin();
247 for(; i != m_list.end(); ++i)
249 u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
250 /*dout_con<<"findPacket(): finding seqnum="<<seqnum
251 <<", comparing to s="<<s<<std::endl;*/
257 RPBSearchResult ReliablePacketBuffer::notFound()
261 bool ReliablePacketBuffer::getFirstSeqnum(u16& result)
263 JMutexAutoLock listlock(m_list_mutex);
266 BufferedPacket p = *m_list.begin();
267 result = readU16(&p.data[BASE_HEADER_SIZE+1]);
271 BufferedPacket ReliablePacketBuffer::popFirst()
273 JMutexAutoLock listlock(m_list_mutex);
275 throw NotFoundException("Buffer is empty");
276 BufferedPacket p = *m_list.begin();
277 m_list.erase(m_list.begin());
280 if (m_list_size == 0)
281 { m_oldest_non_answered_ack = 0; }
283 { m_oldest_non_answered_ack = readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]); }
286 BufferedPacket ReliablePacketBuffer::popSeqnum(u16 seqnum)
288 JMutexAutoLock listlock(m_list_mutex);
289 RPBSearchResult r = findPacket(seqnum);
291 LOG(dout_con<<"Sequence number: " << seqnum << " 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 */
369 fprintf(stderr, "Duplicated seqnum %d non matching packet detected:\n",seqnum);
370 fprintf(stderr, "Old: seqnum: %05d size: %04d, address: %s\n",
371 readU16(&(i->data[BASE_HEADER_SIZE+1])),i->data.getSize(), i->address.serializeString().c_str());
372 fprintf(stderr, "New: seqnum: %05d size: %04d, address: %s\n",
373 readU16(&(p.data[BASE_HEADER_SIZE+1])),p.data.getSize(), p.address.serializeString().c_str());
374 throw IncomingDataCorruption("duplicated packet isn't same as original one");
377 assert(readU16(&(i->data[BASE_HEADER_SIZE+1])) == seqnum);
378 assert(i->data.getSize() == p.data.getSize());
379 assert(i->address == p.address);
381 /* nothing to do this seems to be a resent packet */
382 /* for paranoia reason data should be compared */
385 /* insert or push back */
386 else if (i != m_list.end()) {
393 /* update last packet number */
394 m_oldest_non_answered_ack = readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]);
397 void ReliablePacketBuffer::incrementTimeouts(float dtime)
399 JMutexAutoLock listlock(m_list_mutex);
400 for(std::list<BufferedPacket>::iterator i = m_list.begin();
401 i != m_list.end(); ++i)
404 i->totaltime += dtime;
408 std::list<BufferedPacket> ReliablePacketBuffer::getTimedOuts(float timeout,
409 unsigned int max_packets)
411 JMutexAutoLock listlock(m_list_mutex);
412 std::list<BufferedPacket> timed_outs;
413 for(std::list<BufferedPacket>::iterator i = m_list.begin();
414 i != m_list.end(); ++i)
416 if(i->time >= timeout) {
417 timed_outs.push_back(*i);
419 //this packet will be sent right afterwards reset timeout here
421 if (timed_outs.size() >= max_packets)
432 IncomingSplitBuffer::~IncomingSplitBuffer()
434 JMutexAutoLock listlock(m_map_mutex);
435 for(std::map<u16, IncomingSplitPacket*>::iterator i = m_buf.begin();
436 i != m_buf.end(); ++i)
442 This will throw a GotSplitPacketException when a full
443 split packet is constructed.
445 SharedBuffer<u8> IncomingSplitBuffer::insert(BufferedPacket &p, bool reliable)
447 JMutexAutoLock listlock(m_map_mutex);
448 u32 headersize = BASE_HEADER_SIZE + 7;
449 assert(p.data.getSize() >= headersize);
450 u8 type = readU8(&p.data[BASE_HEADER_SIZE+0]);
451 assert(type == TYPE_SPLIT);
452 u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]);
453 u16 chunk_count = readU16(&p.data[BASE_HEADER_SIZE+3]);
454 u16 chunk_num = readU16(&p.data[BASE_HEADER_SIZE+5]);
456 // Add if doesn't exist
457 if(m_buf.find(seqnum) == m_buf.end())
459 IncomingSplitPacket *sp = new IncomingSplitPacket();
460 sp->chunk_count = chunk_count;
461 sp->reliable = reliable;
465 IncomingSplitPacket *sp = m_buf[seqnum];
467 // TODO: These errors should be thrown or something? Dunno.
468 if(chunk_count != sp->chunk_count)
469 LOG(derr_con<<"Connection: WARNING: chunk_count="<<chunk_count
470 <<" != sp->chunk_count="<<sp->chunk_count
472 if(reliable != sp->reliable)
473 LOG(derr_con<<"Connection: WARNING: reliable="<<reliable
474 <<" != sp->reliable="<<sp->reliable
477 // If chunk already exists, ignore it.
478 // Sometimes two identical packets may arrive when there is network
479 // lag and the server re-sends stuff.
480 if(sp->chunks.find(chunk_num) != sp->chunks.end())
481 return SharedBuffer<u8>();
483 // Cut chunk data out of packet
484 u32 chunkdatasize = p.data.getSize() - headersize;
485 SharedBuffer<u8> chunkdata(chunkdatasize);
486 memcpy(*chunkdata, &(p.data[headersize]), chunkdatasize);
488 // Set chunk data in buffer
489 sp->chunks[chunk_num] = chunkdata;
491 // If not all chunks are received, return empty buffer
492 if(sp->allReceived() == false)
493 return SharedBuffer<u8>();
495 // Calculate total size
497 for(std::map<u16, SharedBuffer<u8> >::iterator i = sp->chunks.begin();
498 i != sp->chunks.end(); ++i)
500 totalsize += i->second.getSize();
503 SharedBuffer<u8> fulldata(totalsize);
505 // Copy chunks to data buffer
507 for(u32 chunk_i=0; chunk_i<sp->chunk_count;
510 SharedBuffer<u8> buf = sp->chunks[chunk_i];
511 u16 chunkdatasize = buf.getSize();
512 memcpy(&fulldata[start], *buf, chunkdatasize);
513 start += chunkdatasize;;
516 // Remove sp from buffer
522 void IncomingSplitBuffer::removeUnreliableTimedOuts(float dtime, float timeout)
524 std::list<u16> remove_queue;
526 JMutexAutoLock listlock(m_map_mutex);
527 for(std::map<u16, IncomingSplitPacket*>::iterator i = m_buf.begin();
528 i != m_buf.end(); ++i)
530 IncomingSplitPacket *p = i->second;
531 // Reliable ones are not removed by timeout
532 if(p->reliable == true)
535 if(p->time >= timeout)
536 remove_queue.push_back(i->first);
539 for(std::list<u16>::iterator j = remove_queue.begin();
540 j != remove_queue.end(); ++j)
542 JMutexAutoLock listlock(m_map_mutex);
543 LOG(dout_con<<"NOTE: Removing timed out unreliable split packet"<<std::endl);
554 window_size(MIN_RELIABLE_WINDOW_SIZE),
555 next_incoming_seqnum(SEQNUM_INITIAL),
556 next_outgoing_seqnum(SEQNUM_INITIAL),
557 next_outgoing_split_seqnum(SEQNUM_INITIAL),
558 current_packet_loss(0),
559 current_packet_too_late(0),
560 packet_loss_counter(0),
561 current_bytes_transfered(0),
562 current_bytes_lost(0),
577 u16 Channel::readNextIncomingSeqNum()
579 JMutexAutoLock internal(m_internal_mutex);
580 return next_incoming_seqnum;
583 u16 Channel::incNextIncomingSeqNum()
585 JMutexAutoLock internal(m_internal_mutex);
586 u16 retval = next_incoming_seqnum;
587 next_incoming_seqnum++;
591 u16 Channel::readNextSplitSeqNum()
593 JMutexAutoLock internal(m_internal_mutex);
594 return next_outgoing_split_seqnum;
596 void Channel::setNextSplitSeqNum(u16 seqnum)
598 JMutexAutoLock internal(m_internal_mutex);
599 next_outgoing_split_seqnum = seqnum;
602 u16 Channel::getOutgoingSequenceNumber(bool& successfull)
604 JMutexAutoLock internal(m_internal_mutex);
605 u16 retval = next_outgoing_seqnum;
606 u16 lowest_unacked_seqnumber;
608 /* shortcut if there ain't any packet in outgoing list */
609 if (outgoing_reliables_sent.empty())
611 next_outgoing_seqnum++;
615 if (outgoing_reliables_sent.getFirstSeqnum(lowest_unacked_seqnumber))
617 if (lowest_unacked_seqnumber < next_outgoing_seqnum) {
618 // ugly cast but this one is required in order to tell compiler we
619 // know about difference of two unsigned may be negative in general
620 // but we already made sure it won't happen in this case
621 if (((u16)(next_outgoing_seqnum - lowest_unacked_seqnumber)) > window_size) {
627 // ugly cast but this one is required in order to tell compiler we
628 // know about difference of two unsigned may be negative in general
629 // but we already made sure it won't happen in this case
630 if ((next_outgoing_seqnum + (u16)(SEQNUM_MAX - lowest_unacked_seqnumber)) >
638 next_outgoing_seqnum++;
642 u16 Channel::readOutgoingSequenceNumber()
644 JMutexAutoLock internal(m_internal_mutex);
645 return next_outgoing_seqnum;
648 bool Channel::putBackSequenceNumber(u16 seqnum)
650 if (((seqnum + 1) % (SEQNUM_MAX+1)) == next_outgoing_seqnum) {
652 next_outgoing_seqnum = seqnum;
658 void Channel::UpdateBytesSent(unsigned int bytes, unsigned int packets)
660 JMutexAutoLock internal(m_internal_mutex);
661 current_bytes_transfered += bytes;
662 current_packet_successfull += packets;
665 void Channel::UpdateBytesLost(unsigned int bytes)
667 JMutexAutoLock internal(m_internal_mutex);
668 current_bytes_lost += bytes;
672 void Channel::UpdatePacketLossCounter(unsigned int count)
674 JMutexAutoLock internal(m_internal_mutex);
675 current_packet_loss += count;
678 void Channel::UpdatePacketTooLateCounter()
680 JMutexAutoLock internal(m_internal_mutex);
681 current_packet_too_late++;
684 void Channel::UpdateTimers(float dtime)
686 bpm_counter += dtime;
687 packet_loss_counter += dtime;
689 if (packet_loss_counter > 1.0)
691 packet_loss_counter -= 1.0;
693 unsigned int packet_loss = 11; /* use a neutral value for initialization */
694 unsigned int packets_successfull = 0;
695 unsigned int packet_too_late = 0;
697 bool reasonable_amount_of_data_transmitted = false;
700 JMutexAutoLock internal(m_internal_mutex);
701 packet_loss = current_packet_loss;
702 packet_too_late = current_packet_too_late;
703 packets_successfull = current_packet_successfull;
705 if (current_bytes_transfered > (window_size*512/2))
707 reasonable_amount_of_data_transmitted = true;
709 current_packet_loss = 0;
710 current_packet_too_late = 0;
711 current_packet_successfull = 0;
714 float successfull_to_lost_ratio = 0.0;
717 if (packets_successfull > 0) {
718 successfull_to_lost_ratio = packet_loss/packets_successfull;
720 else if (packet_loss > 0)
724 MIN_RELIABLE_WINDOW_SIZE);
730 if ((successfull_to_lost_ratio < 0.01) &&
731 (window_size < MAX_RELIABLE_WINDOW_SIZE))
733 /* don't even think about increasing if we didn't even
734 * use major parts of our window */
735 if (reasonable_amount_of_data_transmitted)
738 MAX_RELIABLE_WINDOW_SIZE);
740 else if ((successfull_to_lost_ratio < 0.05) &&
741 (window_size < MAX_RELIABLE_WINDOW_SIZE))
743 /* don't even think about increasing if we didn't even
744 * use major parts of our window */
745 if (reasonable_amount_of_data_transmitted)
748 MAX_RELIABLE_WINDOW_SIZE);
750 else if (successfull_to_lost_ratio > 0.15)
754 MIN_RELIABLE_WINDOW_SIZE);
756 else if (successfull_to_lost_ratio > 0.1)
760 MIN_RELIABLE_WINDOW_SIZE);
765 if (bpm_counter > 10.0)
768 JMutexAutoLock internal(m_internal_mutex);
769 cur_kbps = (current_bytes_transfered/bpm_counter)/1024;
770 current_bytes_transfered = 0;
771 cur_kbps_lost = (current_bytes_lost/bpm_counter)/1024;
772 current_bytes_lost = 0;
776 if (cur_kbps > max_kbps)
781 if (cur_kbps_lost > max_kbps_lost)
783 max_kbps_lost = cur_kbps_lost;
786 avg_kbps = avg_kbps * 0.9 + cur_kbps * 0.1;
787 avg_kbps_lost = avg_kbps_lost * 0.9 + cur_kbps_lost * 0.1;
796 PeerHelper::PeerHelper() :
801 PeerHelper::PeerHelper(Peer* peer) :
806 if (!peer->IncUseCount())
813 PeerHelper::~PeerHelper()
816 m_peer->DecUseCount();
821 PeerHelper& PeerHelper::operator=(Peer* peer)
826 if (!peer->IncUseCount())
834 Peer* PeerHelper::operator->() const
839 Peer* PeerHelper::operator&() const
844 bool PeerHelper::operator!() {
848 bool PeerHelper::operator!=(void* ptr)
850 return ((void*) m_peer != ptr);
853 bool Peer::IncUseCount()
855 JMutexAutoLock lock(m_exclusive_access_mutex);
857 if (!m_pending_deletion)
866 void Peer::DecUseCount()
869 JMutexAutoLock lock(m_exclusive_access_mutex);
873 if (!((m_pending_deletion) && (m_usage == 0)))
879 void Peer::RTTStatistics(float rtt,
880 std::string profiler_id,
881 unsigned int num_samples) {
883 if (m_last_rtt > 0) {
884 /* set min max values */
885 if (rtt < m_rtt.min_rtt)
887 if (rtt >= m_rtt.max_rtt)
890 /* do average calculation */
891 if(m_rtt.avg_rtt < 0.0)
894 m_rtt.avg_rtt = m_rtt.avg_rtt * (num_samples/(num_samples-1)) +
895 rtt * (1/num_samples);
897 /* do jitter calculation */
899 //just use some neutral value at beginning
900 float jitter = m_rtt.jitter_min;
902 if (rtt > m_last_rtt)
903 jitter = rtt-m_last_rtt;
905 if (rtt <= m_last_rtt)
906 jitter = m_last_rtt - rtt;
908 if (jitter < m_rtt.jitter_min)
909 m_rtt.jitter_min = jitter;
910 if (jitter >= m_rtt.jitter_max)
911 m_rtt.jitter_max = jitter;
913 if(m_rtt.jitter_avg < 0.0)
914 m_rtt.jitter_avg = jitter;
916 m_rtt.jitter_avg = m_rtt.jitter_avg * (num_samples/(num_samples-1)) +
917 jitter * (1/num_samples);
919 if (profiler_id != "")
921 g_profiler->graphAdd(profiler_id + "_rtt", rtt);
922 g_profiler->graphAdd(profiler_id + "_jitter", jitter);
925 /* save values required for next loop */
929 bool Peer::isTimedOut(float timeout)
931 JMutexAutoLock lock(m_exclusive_access_mutex);
932 u32 current_time = porting::getTimeMs();
934 float dtime = CALC_DTIME(m_last_timeout_check,current_time);
935 m_last_timeout_check = current_time;
937 m_timeout_counter += dtime;
939 return m_timeout_counter > timeout;
945 JMutexAutoLock usage_lock(m_exclusive_access_mutex);
946 m_pending_deletion = true;
951 PROFILE(std::stringstream peerIdentifier1);
952 PROFILE(peerIdentifier1 << "runTimeouts[" << m_connection->getDesc() << ";" << id << ";RELIABLE]");
953 PROFILE(g_profiler->remove(peerIdentifier1.str()));
954 PROFILE(std::stringstream peerIdentifier2);
955 PROFILE(peerIdentifier2 << "sendPackets[" << m_connection->getDesc() << ";" << id << ";RELIABLE]");
956 PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier2.str(), SPT_AVG));
961 UDPPeer::UDPPeer(u16 a_id, Address a_address, Connection* connection) :
962 Peer(a_address,a_id,connection),
972 bool UDPPeer::getAddress(MTProtocols type,Address& toset)
974 if ((type == UDP) || (type == MINETEST_RELIABLE_UDP) || (type == PRIMARY))
983 void UDPPeer::reportRTT(float rtt)
988 RTTStatistics(rtt,"rudp",MAX_RELIABLE_WINDOW_SIZE*10);
990 float timeout = getStat(AVG_RTT) * RESEND_TIMEOUT_FACTOR;
991 if(timeout < RESEND_TIMEOUT_MIN)
992 timeout = RESEND_TIMEOUT_MIN;
993 if(timeout > RESEND_TIMEOUT_MAX)
994 timeout = RESEND_TIMEOUT_MAX;
996 JMutexAutoLock usage_lock(m_exclusive_access_mutex);
997 resend_timeout = timeout;
1000 bool UDPPeer::Ping(float dtime,SharedBuffer<u8>& data)
1002 m_ping_timer += dtime;
1003 if(m_ping_timer >= PING_TIMEOUT)
1005 // Create and send PING packet
1006 writeU8(&data[0], TYPE_CONTROL);
1007 writeU8(&data[1], CONTROLTYPE_PING);
1014 void UDPPeer::PutReliableSendCommand(ConnectionCommand &c,
1015 unsigned int max_packet_size)
1017 if ( channels[c.channelnum].queued_commands.empty() &&
1018 /* don't queue more packets then window size */
1019 (channels[c.channelnum].queued_reliables.size()
1020 < (channels[c.channelnum].getWindowSize()/2)))
1022 LOG(dout_con<<m_connection->getDesc()
1023 <<" processing reliable command for peer id: " << c.peer_id
1024 <<" data size: " << c.data.getSize() << std::endl);
1025 if (!processReliableSendCommand(c,max_packet_size))
1027 channels[c.channelnum].queued_commands.push_back(c);
1032 LOG(dout_con<<m_connection->getDesc()
1033 <<" Queueing reliable command for peer id: " << c.peer_id
1034 <<" data size: " << c.data.getSize() <<std::endl);
1035 channels[c.channelnum].queued_commands.push_back(c);
1039 bool UDPPeer::processReliableSendCommand(
1040 ConnectionCommand &c,
1041 unsigned int max_packet_size)
1043 u32 chunksize_max = max_packet_size
1045 - RELIABLE_HEADER_SIZE;
1047 assert(c.data.getSize() < MAX_RELIABLE_WINDOW_SIZE*512);
1049 std::list<SharedBuffer<u8> > originals;
1050 u16 split_sequence_number = channels[c.channelnum].readNextSplitSeqNum();
1054 originals.push_back(c.data);
1057 originals = makeAutoSplitPacket(c.data, chunksize_max,split_sequence_number);
1058 channels[c.channelnum].setNextSplitSeqNum(split_sequence_number);
1061 bool have_sequence_number = true;
1062 bool have_initial_sequence_number = false;
1063 Queue<BufferedPacket> toadd;
1064 volatile u16 initial_sequence_number = 0;
1066 for(std::list<SharedBuffer<u8> >::iterator i = originals.begin();
1067 i != originals.end(); ++i)
1069 u16 seqnum = channels[c.channelnum].getOutgoingSequenceNumber(have_sequence_number);
1071 /* oops, we don't have enough sequence numbers to send this packet */
1072 if (!have_sequence_number)
1075 if (!have_initial_sequence_number)
1077 initial_sequence_number = seqnum;
1078 have_initial_sequence_number = true;
1081 SharedBuffer<u8> reliable = makeReliablePacket(*i, seqnum);
1083 // Add base headers and make a packet
1084 BufferedPacket p = con::makePacket(address, reliable,
1085 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1091 if (have_sequence_number) {
1092 volatile u16 pcount = 0;
1093 while(toadd.size() > 0) {
1094 BufferedPacket p = toadd.pop_front();
1095 // LOG(dout_con<<connection->getDesc()
1096 // << " queuing reliable packet for peer_id: " << c.peer_id
1097 // << " channel: " << (c.channelnum&0xFF)
1098 // << " seqnum: " << readU16(&p.data[BASE_HEADER_SIZE+1])
1100 channels[c.channelnum].queued_reliables.push_back(p);
1103 assert(channels[c.channelnum].queued_reliables.size() < 0xFFFF);
1107 volatile u16 packets_available = toadd.size();
1108 /* we didn't get a single sequence number no need to fill queue */
1109 if (!have_initial_sequence_number)
1113 while(toadd.size() > 0) {
1117 bool successfully_put_back_sequence_number
1118 = channels[c.channelnum].putBackSequenceNumber(
1119 (initial_sequence_number+toadd.size() % (SEQNUM_MAX+1)));
1121 assert(successfully_put_back_sequence_number);
1123 LOG(dout_con<<m_connection->getDesc()
1124 << " Windowsize exceeded on reliable sending " << c.data.getSize() << " bytes"
1125 << std::endl << "\t\tinitial_sequence_number: " << initial_sequence_number
1126 << std::endl << "\t\tgot at most : " << packets_available << " packets"
1127 << std::endl << "\t\tpackets queued : " << channels[c.channelnum].outgoing_reliables_sent.size()
1133 void UDPPeer::RunCommandQueues(
1134 unsigned int max_packet_size,
1135 unsigned int maxcommands,
1136 unsigned int maxtransfer)
1139 for (unsigned int i = 0; i < CHANNEL_COUNT; i++)
1141 unsigned int commands_processed = 0;
1143 if ((channels[i].queued_commands.size() > 0) &&
1144 (channels[i].queued_reliables.size() < maxtransfer) &&
1145 (commands_processed < maxcommands))
1148 ConnectionCommand c = channels[i].queued_commands.pop_front();
1149 LOG(dout_con<<m_connection->getDesc()
1150 <<" processing queued reliable command "<<std::endl);
1151 if (!processReliableSendCommand(c,max_packet_size)) {
1152 LOG(dout_con<<m_connection->getDesc()
1153 << " Failed to queue packets for peer_id: " << c.peer_id
1154 << ", delaying sending of " << c.data.getSize() << " bytes" << std::endl);
1155 channels[i].queued_commands.push_front(c);
1158 catch (ItemNotFoundException e) {
1159 // intentionally empty
1165 u16 UDPPeer::getNextSplitSequenceNumber(u8 channel)
1167 assert(channel < CHANNEL_COUNT);
1168 return channels[channel].readNextIncomingSeqNum();
1171 void UDPPeer::setNextSplitSequenceNumber(u8 channel, u16 seqnum)
1173 assert(channel < CHANNEL_COUNT);
1174 channels[channel].setNextSplitSeqNum(seqnum);
1177 SharedBuffer<u8> UDPPeer::addSpiltPacket(u8 channel,
1178 BufferedPacket toadd,
1181 assert(channel < CHANNEL_COUNT);
1182 return channels[channel].incoming_splits.insert(toadd,reliable);
1185 /******************************************************************************/
1186 /* Connection Threads */
1187 /******************************************************************************/
1189 ConnectionSendThread::ConnectionSendThread(Connection* parent,
1190 unsigned int max_packet_size,
1192 m_connection(parent),
1193 m_max_packet_size(max_packet_size),
1195 m_max_commands_per_iteration(1),
1196 m_max_data_packets_per_iteration(g_settings->getU16("max_packets_per_iteration")),
1197 m_max_packets_requeued(256)
1201 void * ConnectionSendThread::Thread()
1204 log_register_thread("ConnectionSend");
1206 LOG(dout_con<<m_connection->getDesc()
1207 <<"ConnectionSend thread started"<<std::endl);
1209 u32 curtime = porting::getTimeMs();
1210 u32 lasttime = curtime;
1212 PROFILE(std::stringstream ThreadIdentifier);
1213 PROFILE(ThreadIdentifier << "ConnectionSend: [" << m_connection->getDesc() << "]");
1215 /* if stop is requested don't stop immediately but try to send all */
1217 while(!StopRequested() || packetsQueued()) {
1218 BEGIN_DEBUG_EXCEPTION_HANDLER
1219 PROFILE(ScopeProfiler sp(g_profiler, ThreadIdentifier.str(), SPT_AVG));
1221 m_iteration_packets_avaialble = m_max_data_packets_per_iteration;
1223 /* wait for trigger or timeout */
1224 m_send_sleep_semaphore.Wait(50);
1226 /* remove all triggers */
1227 while(m_send_sleep_semaphore.Wait(0)) {}
1230 curtime = porting::getTimeMs();
1231 float dtime = CALC_DTIME(lasttime,curtime);
1233 /* first do all the reliable stuff */
1236 /* translate commands to packets */
1237 ConnectionCommand c = m_connection->m_command_queue.pop_frontNoEx(0);
1238 while(c.type != CONNCMD_NONE)
1241 processReliableCommand(c);
1243 processNonReliableCommand(c);
1245 c = m_connection->m_command_queue.pop_frontNoEx(0);
1248 /* send non reliable packets */
1251 END_DEBUG_EXCEPTION_HANDLER(derr_con);
1254 PROFILE(g_profiler->remove(ThreadIdentifier.str()));
1258 void ConnectionSendThread::Trigger()
1260 m_send_sleep_semaphore.Post();
1263 bool ConnectionSendThread::packetsQueued()
1265 std::list<u16> peerIds = m_connection->getPeerIDs();
1267 if ((this->m_outgoing_queue.size() > 0) && (peerIds.size() > 0))
1270 for(std::list<u16>::iterator j = peerIds.begin();
1271 j != peerIds.end(); ++j)
1273 PeerHelper peer = m_connection->getPeerNoEx(*j);
1278 if (dynamic_cast<UDPPeer*>(&peer) == 0)
1281 for(u16 i=0; i<CHANNEL_COUNT; i++)
1283 Channel *channel = &(dynamic_cast<UDPPeer*>(&peer))->channels[i];
1285 if (channel->queued_commands.size() > 0)
1296 void ConnectionSendThread::runTimeouts(float dtime)
1298 std::list<u16> timeouted_peers;
1299 std::list<u16> peerIds = m_connection->getPeerIDs();
1301 for(std::list<u16>::iterator j = peerIds.begin();
1302 j != peerIds.end(); ++j)
1304 PeerHelper peer = m_connection->getPeerNoEx(*j);
1309 if(dynamic_cast<UDPPeer*>(&peer) == 0)
1312 PROFILE(std::stringstream peerIdentifier);
1313 PROFILE(peerIdentifier << "runTimeouts[" << m_connection->getDesc() << ";" << *j << ";RELIABLE]");
1314 PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier.str(), SPT_AVG));
1316 SharedBuffer<u8> data(2); // data for sending ping, required here because of goto
1321 if(peer->isTimedOut(m_timeout))
1323 LOG(derr_con<<m_connection->getDesc()
1324 <<"RunTimeouts(): Peer "<<peer->id
1326 <<" (source=peer->timeout_counter)"
1328 // Add peer to the list
1329 timeouted_peers.push_back(peer->id);
1330 // Don't bother going through the buffers of this one
1334 float resend_timeout = dynamic_cast<UDPPeer*>(&peer)->getResendTimeout();
1335 for(u16 i=0; i<CHANNEL_COUNT; i++)
1337 std::list<BufferedPacket> timed_outs;
1338 Channel *channel = &(dynamic_cast<UDPPeer*>(&peer))->channels[i];
1340 if (dynamic_cast<UDPPeer*>(&peer)->getLegacyPeer())
1341 channel->setWindowSize(g_settings->getU16("workaround_window_size"));
1343 // Remove timed out incomplete unreliable split packets
1344 channel->incoming_splits.removeUnreliableTimedOuts(dtime, m_timeout);
1346 // Increment reliable packet times
1347 channel->outgoing_reliables_sent.incrementTimeouts(dtime);
1349 unsigned int numpeers = m_connection->m_peers.size();
1354 // Re-send timed out outgoing reliables
1355 timed_outs = channel->
1356 outgoing_reliables_sent.getTimedOuts(resend_timeout,
1357 (m_max_data_packets_per_iteration/numpeers));
1359 channel->UpdatePacketLossCounter(timed_outs.size());
1361 m_iteration_packets_avaialble -= timed_outs.size();
1363 for(std::list<BufferedPacket>::iterator j = timed_outs.begin();
1364 j != timed_outs.end(); ++j)
1366 u16 peer_id = readPeerId(*(j->data));
1367 u8 channelnum = readChannel(*(j->data));
1368 u16 seqnum = readU16(&(j->data[BASE_HEADER_SIZE+1]));
1370 channel->UpdateBytesLost(j->data.getSize());
1372 LOG(derr_con<<m_connection->getDesc()
1373 <<"RE-SENDING timed-out RELIABLE to "
1374 << j->address.serializeString()
1375 << "(t/o="<<resend_timeout<<"): "
1376 <<"from_peer_id="<<peer_id
1377 <<", channel="<<((int)channelnum&0xff)
1378 <<", seqnum="<<seqnum
1383 // do not handle rtt here as we can't decide if this packet was
1384 // lost or really takes more time to transmit
1387 if (!dynamic_cast<UDPPeer*>(&peer)->getLegacyPeer())
1388 channel->UpdateTimers(dtime);
1391 /* send ping if necessary */
1392 if (dynamic_cast<UDPPeer*>(&peer)->Ping(dtime,data)) {
1393 LOG(dout_con<<m_connection->getDesc()
1394 <<"Sending ping for peer_id: "
1395 << dynamic_cast<UDPPeer*>(&peer)->id <<std::endl);
1396 /* this may fail if there ain't a sequence number left */
1397 if (!rawSendAsPacket(dynamic_cast<UDPPeer*>(&peer)->id, 0, data, true))
1399 //retrigger with reduced ping interval
1400 dynamic_cast<UDPPeer*>(&peer)->Ping(4.0,data);
1404 dynamic_cast<UDPPeer*>(&peer)->RunCommandQueues(m_max_packet_size,
1405 m_max_commands_per_iteration,
1406 m_max_packets_requeued);
1409 // Remove timed out peers
1410 for(std::list<u16>::iterator i = timeouted_peers.begin();
1411 i != timeouted_peers.end(); ++i)
1413 LOG(derr_con<<m_connection->getDesc()
1414 <<"RunTimeouts(): Removing peer "<<(*i)<<std::endl);
1415 m_connection->deletePeer(*i, true);
1419 void ConnectionSendThread::rawSend(const BufferedPacket &packet)
1422 m_connection->m_udpSocket.Send(packet.address, *packet.data, packet.data.getSize());
1423 LOG(dout_con <<m_connection->getDesc()
1424 << " rawSend: " << packet.data.getSize() << " bytes sent" << std::endl);
1425 } catch(SendFailedException &e){
1426 LOG(derr_con<<m_connection->getDesc()
1427 <<"Connection::rawSend(): SendFailedException: "
1428 <<packet.address.serializeString()<<std::endl);
1432 void ConnectionSendThread::sendAsPacketReliable(BufferedPacket& p, Channel* channel)
1435 p.absolute_send_time = porting::getTimeMs();
1436 // Buffer the packet
1437 channel->outgoing_reliables_sent.insert(p,
1438 (channel->readOutgoingSequenceNumber() - MAX_RELIABLE_WINDOW_SIZE) % (MAX_RELIABLE_WINDOW_SIZE+1));
1440 catch(AlreadyExistsException &e)
1442 LOG(derr_con<<m_connection->getDesc()
1443 <<"WARNING: Going to send a reliable packet"
1444 <<" in outgoing buffer" <<std::endl);
1452 bool ConnectionSendThread::rawSendAsPacket(u16 peer_id, u8 channelnum,
1453 SharedBuffer<u8> data, bool reliable)
1455 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
1457 LOG(dout_con<<m_connection->getDesc()
1458 <<" INFO: dropped packet for non existent peer_id: " << peer_id << std::endl);
1459 assert(reliable && "trying to send raw packet reliable but no peer found!");
1462 Channel *channel = &(dynamic_cast<UDPPeer*>(&peer)->channels[channelnum]);
1466 bool have_sequence_number_for_raw_packet = true;
1467 u16 seqnum = channel->getOutgoingSequenceNumber(have_sequence_number_for_raw_packet);
1469 if (!have_sequence_number_for_raw_packet)
1472 SharedBuffer<u8> reliable = makeReliablePacket(data, seqnum);
1473 Address peer_address;
1474 peer->getAddress(MINETEST_RELIABLE_UDP,peer_address);
1476 // Add base headers and make a packet
1477 BufferedPacket p = con::makePacket(peer_address, reliable,
1478 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1481 // first check if our send window is already maxed out
1482 if (channel->outgoing_reliables_sent.size()
1483 < channel->getWindowSize()) {
1484 LOG(dout_con<<m_connection->getDesc()
1485 <<" INFO: sending a reliable packet to peer_id " << peer_id
1486 <<" channel: " << channelnum
1487 <<" seqnum: " << seqnum << std::endl);
1488 sendAsPacketReliable(p,channel);
1492 LOG(dout_con<<m_connection->getDesc()
1493 <<" INFO: queueing reliable packet for peer_id: " << peer_id
1494 <<" channel: " << channelnum
1495 <<" seqnum: " << seqnum << std::endl);
1496 channel->queued_reliables.push_back(p);
1502 Address peer_address;
1504 if (peer->getAddress(UDP,peer_address))
1506 // Add base headers and make a packet
1507 BufferedPacket p = con::makePacket(peer_address, data,
1508 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1516 LOG(dout_con<<m_connection->getDesc()
1517 <<" INFO: dropped unreliable packet for peer_id: " << peer_id
1518 <<" because of (yet) missing udp address" << std::endl);
1527 void ConnectionSendThread::processReliableCommand(ConnectionCommand &c)
1533 LOG(dout_con<<m_connection->getDesc()<<"UDP processing reliable CONNCMD_NONE"<<std::endl);
1537 LOG(dout_con<<m_connection->getDesc()<<"UDP processing reliable CONNCMD_SEND"<<std::endl);
1541 case CONNCMD_SEND_TO_ALL:
1542 LOG(dout_con<<m_connection->getDesc()<<"UDP processing CONNCMD_SEND_TO_ALL"<<std::endl);
1543 sendToAllReliable(c);
1546 case CONCMD_CREATE_PEER:
1547 LOG(dout_con<<m_connection->getDesc()<<"UDP processing reliable CONCMD_CREATE_PEER"<<std::endl);
1548 if (!rawSendAsPacket(c.peer_id,c.channelnum,c.data,c.reliable))
1550 /* put to queue if we couldn't send it immediately */
1555 case CONCMD_DISABLE_LEGACY:
1556 LOG(dout_con<<m_connection->getDesc()<<"UDP processing reliable CONCMD_DISABLE_LEGACY"<<std::endl);
1557 if (!rawSendAsPacket(c.peer_id,c.channelnum,c.data,c.reliable))
1559 /* put to queue if we couldn't send it immediately */
1565 case CONNCMD_CONNECT:
1566 case CONNCMD_DISCONNECT:
1567 case CONNCMD_DELETE_PEER:
1569 assert("Got command that shouldn't be reliable as reliable command" == 0);
1571 LOG(dout_con<<m_connection->getDesc()<<" Invalid reliable command type: " << c.type <<std::endl);
1576 void ConnectionSendThread::processNonReliableCommand(ConnectionCommand &c)
1578 assert(!c.reliable);
1582 LOG(dout_con<<m_connection->getDesc()<<" UDP processing CONNCMD_NONE"<<std::endl);
1585 LOG(dout_con<<m_connection->getDesc()<<" UDP processing CONNCMD_SERVE port="
1586 <<c.port<<std::endl);
1589 case CONNCMD_CONNECT:
1590 LOG(dout_con<<m_connection->getDesc()<<" UDP processing CONNCMD_CONNECT"<<std::endl);
1593 case CONNCMD_DISCONNECT:
1594 LOG(dout_con<<m_connection->getDesc()<<" UDP processing CONNCMD_DISCONNECT"<<std::endl);
1597 case CONNCMD_DISCONNECT_PEER:
1598 LOG(dout_con<<m_connection->getDesc()<<" UDP processing CONNCMD_DISCONNECT_PEER"<<std::endl);
1599 disconnect_peer(c.peer_id);
1602 LOG(dout_con<<m_connection->getDesc()<<" UDP processing CONNCMD_SEND"<<std::endl);
1603 send(c.peer_id, c.channelnum, c.data);
1605 case CONNCMD_SEND_TO_ALL:
1606 LOG(dout_con<<m_connection->getDesc()<<" UDP processing CONNCMD_SEND_TO_ALL"<<std::endl);
1607 sendToAll(c.channelnum, c.data);
1609 case CONNCMD_DELETE_PEER:
1610 LOG(dout_con<<m_connection->getDesc()<<" UDP processing CONNCMD_DELETE_PEER"<<std::endl);
1611 m_connection->deletePeer(c.peer_id, false);
1614 LOG(dout_con<<m_connection->getDesc()<<" UDP processing CONCMD_ACK"<<std::endl);
1615 sendAsPacket(c.peer_id,c.channelnum,c.data,true);
1617 case CONCMD_CREATE_PEER:
1618 assert("Got command that should be reliable as unreliable command" == 0);
1620 LOG(dout_con<<m_connection->getDesc()<<" Invalid command type: " << c.type <<std::endl);
1624 void ConnectionSendThread::serve(u16 port)
1626 LOG(dout_con<<m_connection->getDesc()<<"UDP serving at port "<<port<<std::endl);
1628 m_connection->m_udpSocket.Bind(port);
1629 m_connection->SetPeerID(PEER_ID_SERVER);
1631 catch(SocketException &e){
1635 m_connection->putEvent(ce);
1639 void ConnectionSendThread::connect(Address address)
1641 LOG(dout_con<<m_connection->getDesc()<<" connecting to "<<address.serializeString()
1642 <<":"<<address.getPort()<<std::endl);
1644 UDPPeer *peer = m_connection->createServerPeer(address);
1648 e.peerAdded(peer->id, peer->address);
1649 m_connection->putEvent(e);
1651 m_connection->m_udpSocket.Bind(0);
1653 // Send a dummy packet to server with peer_id = PEER_ID_INEXISTENT
1654 m_connection->SetPeerID(PEER_ID_INEXISTENT);
1655 SharedBuffer<u8> data(0);
1656 m_connection->Send(PEER_ID_SERVER, 0, data, true);
1659 void ConnectionSendThread::disconnect()
1661 LOG(dout_con<<m_connection->getDesc()<<" disconnecting"<<std::endl);
1663 // Create and send DISCO packet
1664 SharedBuffer<u8> data(2);
1665 writeU8(&data[0], TYPE_CONTROL);
1666 writeU8(&data[1], CONTROLTYPE_DISCO);
1670 std::list<u16> peerids = m_connection->getPeerIDs();
1672 for (std::list<u16>::iterator i = peerids.begin();
1676 sendAsPacket(*i, 0,data,false);
1680 void ConnectionSendThread::disconnect_peer(u16 peer_id)
1682 LOG(dout_con<<m_connection->getDesc()<<" disconnecting peer"<<std::endl);
1684 // Create and send DISCO packet
1685 SharedBuffer<u8> data(2);
1686 writeU8(&data[0], TYPE_CONTROL);
1687 writeU8(&data[1], CONTROLTYPE_DISCO);
1688 sendAsPacket(peer_id, 0,data,false);
1691 void ConnectionSendThread::send(u16 peer_id, u8 channelnum,
1692 SharedBuffer<u8> data)
1694 assert(channelnum < CHANNEL_COUNT);
1696 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
1698 LOG(dout_con<<m_connection->getDesc()<<" peer: peer_id="<<peer_id
1699 << ">>>NOT<<< found on sending packet"
1700 << ", channel " << (channelnum % 0xFF)
1701 << ", size: " << data.getSize() <<std::endl);
1705 LOG(dout_con<<m_connection->getDesc()<<" sending to peer_id="<<peer_id
1706 << ", channel " << (channelnum % 0xFF)
1707 << ", size: " << data.getSize() <<std::endl);
1709 u16 split_sequence_number = peer->getNextSplitSequenceNumber(channelnum);
1711 u32 chunksize_max = m_max_packet_size - BASE_HEADER_SIZE;
1712 std::list<SharedBuffer<u8> > originals;
1714 originals = makeAutoSplitPacket(data, chunksize_max,split_sequence_number);
1716 peer->setNextSplitSequenceNumber(channelnum,split_sequence_number);
1718 for(std::list<SharedBuffer<u8> >::iterator i = originals.begin();
1719 i != originals.end(); ++i)
1721 SharedBuffer<u8> original = *i;
1722 sendAsPacket(peer_id, channelnum, original);
1726 void ConnectionSendThread::sendReliable(ConnectionCommand &c)
1728 PeerHelper peer = m_connection->getPeerNoEx(c.peer_id);
1732 peer->PutReliableSendCommand(c,m_max_packet_size);
1735 void ConnectionSendThread::sendToAll(u8 channelnum, SharedBuffer<u8> data)
1737 std::list<u16> peerids = m_connection->getPeerIDs();
1739 for (std::list<u16>::iterator i = peerids.begin();
1743 send(*i, channelnum, data);
1747 void ConnectionSendThread::sendToAllReliable(ConnectionCommand &c)
1749 std::list<u16> peerids = m_connection->getPeerIDs();
1751 for (std::list<u16>::iterator i = peerids.begin();
1755 PeerHelper peer = m_connection->getPeerNoEx(*i);
1760 peer->PutReliableSendCommand(c,m_max_packet_size);
1764 void ConnectionSendThread::sendPackets(float dtime)
1766 std::list<u16> peerIds = m_connection->getPeerIDs();
1768 for(std::list<u16>::iterator
1769 j = peerIds.begin();
1770 j != peerIds.end(); ++j)
1772 PeerHelper peer = m_connection->getPeerNoEx(*j);
1773 //peer may have been removed
1775 LOG(dout_con<<m_connection->getDesc()<< " Peer not found: peer_id=" << *j << std::endl);
1778 peer->m_increment_packets_remaining = m_iteration_packets_avaialble/m_connection->m_peers.size();
1780 if (dynamic_cast<UDPPeer*>(&peer) == 0)
1785 PROFILE(std::stringstream peerIdentifier);
1786 PROFILE(peerIdentifier << "sendPackets[" << m_connection->getDesc() << ";" << *j << ";RELIABLE]");
1787 PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier.str(), SPT_AVG));
1789 LOG(dout_con<<m_connection->getDesc()
1790 << " Handle per peer queues: peer_id=" << *j
1791 << " packet quota: " << peer->m_increment_packets_remaining << std::endl);
1792 // first send queued reliable packets for all peers (if possible)
1793 for (unsigned int i=0; i < CHANNEL_COUNT; i++)
1795 u16 next_to_ack = 0;
1796 dynamic_cast<UDPPeer*>(&peer)->channels[i].outgoing_reliables_sent.getFirstSeqnum(next_to_ack);
1797 u16 next_to_receive = 0;
1798 dynamic_cast<UDPPeer*>(&peer)->channels[i].incoming_reliables.getFirstSeqnum(next_to_receive);
1800 LOG(dout_con<<m_connection->getDesc()<< "\t channel: "
1801 << i << ", peer quota:"
1802 << peer->m_increment_packets_remaining
1804 << "\t\t\treliables on wire: "
1805 << dynamic_cast<UDPPeer*>(&peer)->channels[i].outgoing_reliables_sent.size()
1806 << ", waiting for ack for " << next_to_ack
1808 << "\t\t\tincoming_reliables: "
1809 << dynamic_cast<UDPPeer*>(&peer)->channels[i].incoming_reliables.size()
1810 << ", next reliable packet: "
1811 << dynamic_cast<UDPPeer*>(&peer)->channels[i].readNextIncomingSeqNum()
1812 << ", next queued: " << next_to_receive
1814 << "\t\t\treliables queued : "
1815 << dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.size()
1817 << "\t\t\tqueued commands : "
1818 << dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_commands.size()
1821 while ((dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.size() > 0) &&
1822 (dynamic_cast<UDPPeer*>(&peer)->channels[i].outgoing_reliables_sent.size()
1823 < dynamic_cast<UDPPeer*>(&peer)->channels[i].getWindowSize())&&
1824 (peer->m_increment_packets_remaining > 0))
1826 BufferedPacket p = dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.pop_front();
1827 Channel* channel = &(dynamic_cast<UDPPeer*>(&peer)->channels[i]);
1828 LOG(dout_con<<m_connection->getDesc()
1829 <<" INFO: sending a queued reliable packet "
1831 <<", seqnum: " << readU16(&p.data[BASE_HEADER_SIZE+1])
1833 sendAsPacketReliable(p,channel);
1834 peer->m_increment_packets_remaining--;
1839 if (m_outgoing_queue.size())
1841 LOG(dout_con<<m_connection->getDesc()
1842 << " Handle non reliable queue ("
1843 << m_outgoing_queue.size() << " pkts)" << std::endl);
1846 unsigned int initial_queuesize = m_outgoing_queue.size();
1847 /* send non reliable packets*/
1848 for(unsigned int i=0;i < initial_queuesize;i++) {
1849 OutgoingPacket packet = m_outgoing_queue.pop_front();
1851 assert(!packet.reliable &&
1852 "reliable packets are not allowed in outgoing queue!");
1854 PeerHelper peer = m_connection->getPeerNoEx(packet.peer_id);
1856 LOG(dout_con<<m_connection->getDesc()
1857 <<" Outgoing queue: peer_id="<<packet.peer_id
1858 << ">>>NOT<<< found on sending packet"
1859 << ", channel " << (packet.channelnum % 0xFF)
1860 << ", size: " << packet.data.getSize() <<std::endl);
1863 /* send acks immediately */
1864 else if (packet.ack)
1866 rawSendAsPacket(packet.peer_id, packet.channelnum,
1867 packet.data, packet.reliable);
1868 peer->m_increment_packets_remaining =
1869 MYMIN(0,peer->m_increment_packets_remaining--);
1872 ( peer->m_increment_packets_remaining > 0) ||
1874 rawSendAsPacket(packet.peer_id, packet.channelnum,
1875 packet.data, packet.reliable);
1876 peer->m_increment_packets_remaining--;
1879 m_outgoing_queue.push_back(packet);
1884 void ConnectionSendThread::sendAsPacket(u16 peer_id, u8 channelnum,
1885 SharedBuffer<u8> data, bool ack)
1887 OutgoingPacket packet(peer_id, channelnum, data, false, ack);
1888 m_outgoing_queue.push_back(packet);
1891 ConnectionReceiveThread::ConnectionReceiveThread(Connection* parent,
1892 unsigned int max_packet_size) :
1893 m_connection(parent),
1894 m_max_packet_size(max_packet_size)
1898 void * ConnectionReceiveThread::Thread()
1901 log_register_thread("ConnectionReceive");
1903 LOG(dout_con<<m_connection->getDesc()
1904 <<"ConnectionReceive thread started"<<std::endl);
1906 PROFILE(std::stringstream ThreadIdentifier);
1907 PROFILE(ThreadIdentifier << "ConnectionReceive: [" << m_connection->getDesc() << "]");
1909 #ifdef DEBUG_CONNECTION_KBPS
1910 u32 curtime = porting::getTimeMs();
1911 u32 lasttime = curtime;
1912 float debug_print_timer = 0.0;
1915 while(!StopRequested()) {
1916 BEGIN_DEBUG_EXCEPTION_HANDLER
1917 PROFILE(ScopeProfiler sp(g_profiler, ThreadIdentifier.str(), SPT_AVG));
1919 #ifdef DEBUG_CONNECTION_KBPS
1921 curtime = porting::getTimeMs();
1922 float dtime = CALC_DTIME(lasttime,curtime);
1925 /* receive packets */
1928 #ifdef DEBUG_CONNECTION_KBPS
1929 debug_print_timer += dtime;
1930 if (debug_print_timer > 20.0) {
1931 debug_print_timer -= 20.0;
1933 std::list<u16> peerids = m_connection->getPeerIDs();
1935 for (std::list<u16>::iterator i = peerids.begin();
1939 PeerHelper peer = m_connection->getPeerNoEx(*i);
1943 float peer_current = 0.0;
1944 float peer_loss = 0.0;
1945 float avg_rate = 0.0;
1946 float avg_loss = 0.0;
1948 for(u16 j=0; j<CHANNEL_COUNT; j++)
1950 peer_current +=peer->channels[j].getCurrentDownloadRateKB();
1951 peer_loss += peer->channels[j].getCurrentLossRateKB();
1952 avg_rate += peer->channels[j].getAvgDownloadRateKB();
1953 avg_loss += peer->channels[j].getAvgLossRateKB();
1956 std::stringstream output;
1957 output << std::fixed << std::setprecision(1);
1958 output << "OUT to Peer " << *i << " RATES (good / loss) " << std::endl;
1959 output << "\tcurrent (sum): " << peer_current << "kb/s "<< peer_loss << "kb/s" << std::endl;
1960 output << "\taverage (sum): " << avg_rate << "kb/s "<< avg_loss << "kb/s" << std::endl;
1961 output << std::setfill(' ');
1962 for(u16 j=0; j<CHANNEL_COUNT; j++)
1964 output << "\tcha " << j << ":"
1965 << " CUR: " << std::setw(6) << peer->channels[j].getCurrentDownloadRateKB() <<"kb/s"
1966 << " AVG: " << std::setw(6) << peer->channels[j].getAvgDownloadRateKB() <<"kb/s"
1967 << " MAX: " << std::setw(6) << peer->channels[j].getMaxDownloadRateKB() <<"kb/s"
1969 << " CUR: " << std::setw(6) << peer->channels[j].getCurrentLossRateKB() <<"kb/s"
1970 << " AVG: " << std::setw(6) << peer->channels[j].getAvgLossRateKB() <<"kb/s"
1971 << " MAX: " << std::setw(6) << peer->channels[j].getMaxLossRateKB() <<"kb/s"
1972 << " / WS: " << peer->channels[j].getWindowSize()
1976 fprintf(stderr,"%s\n",output.str().c_str());
1980 END_DEBUG_EXCEPTION_HANDLER(derr_con);
1982 PROFILE(g_profiler->remove(ThreadIdentifier.str()));
1986 // Receive packets from the network and buffers and create ConnectionEvents
1987 void ConnectionReceiveThread::receive()
1989 /* now reorder reliables */
1990 u32 datasize = m_max_packet_size * 2; // Double it just to be safe
1991 // TODO: We can not know how many layers of header there are.
1992 // For now, just assume there are no other than the base headers.
1993 u32 packet_maxsize = datasize + BASE_HEADER_SIZE;
1994 SharedBuffer<u8> packetdata(packet_maxsize);
1996 bool packet_queued = true;
1998 unsigned int loop_count = 0;
2000 /* first of all read packets from socket */
2001 /* check for incoming data available */
2002 while( (loop_count < 10) &&
2003 (m_connection->m_udpSocket.WaitData(50)))
2009 bool no_data_left = false;
2011 SharedBuffer<u8> resultdata;
2012 while(!no_data_left)
2015 no_data_left = !getFromBuffers(peer_id, resultdata);
2016 if (!no_data_left) {
2018 e.dataReceived(peer_id, resultdata);
2019 m_connection->putEvent(e);
2022 catch(ProcessedSilentlyException e) {
2023 /* try reading again */
2026 packet_queued = false;
2030 s32 received_size = m_connection->m_udpSocket.Receive(sender, *packetdata, packet_maxsize);
2032 if ((received_size < 0) ||
2033 (received_size < BASE_HEADER_SIZE) ||
2034 (readU32(&packetdata[0]) != m_connection->GetProtocolID()))
2036 LOG(derr_con<<m_connection->getDesc()
2037 <<"Receive(): Invalid incoming packet, "
2038 <<"size: " << received_size
2039 <<", protocol: " << readU32(&packetdata[0]) <<std::endl);
2043 u16 peer_id = readPeerId(*packetdata);
2044 u8 channelnum = readChannel(*packetdata);
2046 if(channelnum > CHANNEL_COUNT-1){
2047 LOG(derr_con<<m_connection->getDesc()
2048 <<"Receive(): Invalid channel "<<channelnum<<std::endl);
2049 throw InvalidIncomingDataException("Channel doesn't exist");
2052 /* preserve original peer_id for later usage */
2053 u16 packet_peer_id = peer_id;
2055 /* Try to identify peer by sender address (may happen on join) */
2056 if(peer_id == PEER_ID_INEXISTENT)
2058 peer_id = m_connection->lookupPeer(sender);
2061 /* The peer was not found in our lists. Add it. */
2062 if(peer_id == PEER_ID_INEXISTENT)
2064 peer_id = m_connection->createPeer(sender,MINETEST_RELIABLE_UDP,0);
2067 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
2070 LOG(dout_con<<m_connection->getDesc()
2071 <<" got packet from unknown peer_id: "
2072 <<peer_id<<" Ignoring."<<std::endl);
2076 // Validate peer address
2078 Address peer_address;
2080 if (peer->getAddress(UDP,peer_address)) {
2081 if (peer_address != sender) {
2082 LOG(derr_con<<m_connection->getDesc()
2083 <<m_connection->getDesc()
2084 <<" Peer "<<peer_id<<" sending from different address."
2085 " Ignoring."<<std::endl);
2091 bool invalid_address = true;
2092 if (invalid_address) {
2093 LOG(derr_con<<m_connection->getDesc()
2094 <<m_connection->getDesc()
2095 <<" Peer "<<peer_id<<" unknown."
2096 " Ignoring."<<std::endl);
2102 /* mark peer as seen with id */
2103 if (!(packet_peer_id == PEER_ID_INEXISTENT))
2104 peer->setSentWithID();
2106 peer->ResetTimeout();
2108 Channel *channel = 0;
2110 if (dynamic_cast<UDPPeer*>(&peer) != 0)
2112 channel = &(dynamic_cast<UDPPeer*>(&peer)->channels[channelnum]);
2115 // Throw the received packet to channel->processPacket()
2117 // Make a new SharedBuffer from the data without the base headers
2118 SharedBuffer<u8> strippeddata(received_size - BASE_HEADER_SIZE);
2119 memcpy(*strippeddata, &packetdata[BASE_HEADER_SIZE],
2120 strippeddata.getSize());
2123 // Process it (the result is some data with no headers made by us)
2124 SharedBuffer<u8> resultdata = processPacket
2125 (channel, strippeddata, peer_id, channelnum, false);
2127 LOG(dout_con<<m_connection->getDesc()
2128 <<" ProcessPacket from peer_id: " << peer_id
2129 << ",channel: " << channelnum << ", returned "
2130 << resultdata.getSize() << " bytes" <<std::endl);
2133 e.dataReceived(peer_id, resultdata);
2134 m_connection->putEvent(e);
2135 }catch(ProcessedSilentlyException &e){
2136 }catch(ProcessedQueued &e){
2137 packet_queued = true;
2139 }catch(InvalidIncomingDataException &e){
2141 catch(ProcessedSilentlyException &e){
2146 bool ConnectionReceiveThread::getFromBuffers(u16 &peer_id, SharedBuffer<u8> &dst)
2148 std::list<u16> peerids = m_connection->getPeerIDs();
2150 for(std::list<u16>::iterator j = peerids.begin();
2151 j != peerids.end(); ++j)
2153 PeerHelper peer = m_connection->getPeerNoEx(*j);
2157 if(dynamic_cast<UDPPeer*>(&peer) == 0)
2160 for(u16 i=0; i<CHANNEL_COUNT; i++)
2162 Channel *channel = &(dynamic_cast<UDPPeer*>(&peer))->channels[i];
2164 SharedBuffer<u8> resultdata;
2165 bool got = checkIncomingBuffers(channel, peer_id, resultdata);
2175 bool ConnectionReceiveThread::checkIncomingBuffers(Channel *channel, u16 &peer_id,
2176 SharedBuffer<u8> &dst)
2178 u16 firstseqnum = 0;
2179 if (channel->incoming_reliables.getFirstSeqnum(firstseqnum))
2181 if(firstseqnum == channel->readNextIncomingSeqNum())
2183 BufferedPacket p = channel->incoming_reliables.popFirst();
2184 peer_id = readPeerId(*p.data);
2185 u8 channelnum = readChannel(*p.data);
2186 u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]);
2188 LOG(dout_con<<m_connection->getDesc()
2189 <<"UNBUFFERING TYPE_RELIABLE"
2190 <<" seqnum="<<seqnum
2191 <<" peer_id="<<peer_id
2192 <<" channel="<<((int)channelnum&0xff)
2195 channel->incNextIncomingSeqNum();
2197 u32 headers_size = BASE_HEADER_SIZE + RELIABLE_HEADER_SIZE;
2198 // Get out the inside packet and re-process it
2199 SharedBuffer<u8> payload(p.data.getSize() - headers_size);
2200 memcpy(*payload, &p.data[headers_size], payload.getSize());
2202 dst = processPacket(channel, payload, peer_id, channelnum, true);
2209 SharedBuffer<u8> ConnectionReceiveThread::processPacket(Channel *channel,
2210 SharedBuffer<u8> packetdata, u16 peer_id,
2211 u8 channelnum, bool reliable)
2213 PeerHelper peer = m_connection->getPeer(peer_id);
2215 if(packetdata.getSize() < 1)
2216 throw InvalidIncomingDataException("packetdata.getSize() < 1");
2218 u8 type = readU8(&packetdata[0]);
2220 if(type == TYPE_CONTROL)
2222 if(packetdata.getSize() < 2)
2223 throw InvalidIncomingDataException("packetdata.getSize() < 2");
2225 u8 controltype = readU8(&packetdata[1]);
2227 if( (controltype == CONTROLTYPE_ACK)
2228 && (peer_id <= MAX_UDP_PEERS))
2230 assert(channel != 0);
2231 if(packetdata.getSize() < 4)
2232 throw InvalidIncomingDataException
2233 ("packetdata.getSize() < 4 (ACK header size)");
2235 u16 seqnum = readU16(&packetdata[2]);
2236 LOG(dout_con<<m_connection->getDesc()
2237 <<" [ CONTROLTYPE_ACK: channelnum="
2238 <<((int)channelnum&0xff)<<", peer_id="<<peer_id
2239 <<", seqnum="<<seqnum<< " ]"<<std::endl);
2243 channel->outgoing_reliables_sent.popSeqnum(seqnum);
2244 // Get round trip time
2245 unsigned int current_time = porting::getTimeMs();
2247 if (current_time > p.absolute_send_time)
2249 float rtt = (current_time - p.absolute_send_time) / 1000.0;
2251 // Let peer calculate stuff according to it
2252 // (avg_rtt and resend_timeout)
2253 dynamic_cast<UDPPeer*>(&peer)->reportRTT(rtt);
2255 else if (p.totaltime > 0)
2257 float rtt = p.totaltime;
2259 // Let peer calculate stuff according to it
2260 // (avg_rtt and resend_timeout)
2261 dynamic_cast<UDPPeer*>(&peer)->reportRTT(rtt);
2263 //put bytes for max bandwidth calculation
2264 channel->UpdateBytesSent(p.data.getSize(),1);
2266 catch(NotFoundException &e){
2267 LOG(derr_con<<m_connection->getDesc()
2268 <<"WARNING: ACKed packet not "
2271 channel->UpdatePacketTooLateCounter();
2273 throw ProcessedSilentlyException("Got an ACK");
2275 else if((controltype == CONTROLTYPE_SET_PEER_ID)
2276 && (peer_id <= MAX_UDP_PEERS))
2278 // Got a packet to set our peer id
2279 if(packetdata.getSize() < 4)
2280 throw InvalidIncomingDataException
2281 ("packetdata.getSize() < 4 (SET_PEER_ID header size)");
2282 u16 peer_id_new = readU16(&packetdata[2]);
2283 LOG(dout_con<<m_connection->getDesc()
2284 <<"Got new peer id: "<<peer_id_new<<"... "<<std::endl);
2286 if(m_connection->GetPeerID() != PEER_ID_INEXISTENT)
2288 LOG(derr_con<<m_connection->getDesc()
2289 <<"WARNING: Not changing"
2290 " existing peer id."<<std::endl);
2294 LOG(dout_con<<m_connection->getDesc()<<"changing own peer id"<<std::endl);
2295 m_connection->SetPeerID(peer_id_new);
2298 ConnectionCommand cmd;
2300 SharedBuffer<u8> reply(2);
2301 writeU8(&reply[0], TYPE_CONTROL);
2302 writeU8(&reply[1], CONTROLTYPE_ENABLE_BIG_SEND_WINDOW);
2303 cmd.disableLegacy(PEER_ID_SERVER,reply);
2304 m_connection->putCommand(cmd);
2306 throw ProcessedSilentlyException("Got a SET_PEER_ID");
2308 else if((controltype == CONTROLTYPE_PING)
2309 && (peer_id <= MAX_UDP_PEERS))
2311 // Just ignore it, the incoming data already reset
2312 // the timeout counter
2313 LOG(dout_con<<m_connection->getDesc()<<"PING"<<std::endl);
2314 throw ProcessedSilentlyException("Got a PING");
2316 else if(controltype == CONTROLTYPE_DISCO)
2318 // Just ignore it, the incoming data already reset
2319 // the timeout counter
2320 LOG(dout_con<<m_connection->getDesc()
2321 <<"DISCO: Removing peer "<<(peer_id)<<std::endl);
2323 if(m_connection->deletePeer(peer_id, false) == false)
2325 derr_con<<m_connection->getDesc()
2326 <<"DISCO: Peer not found"<<std::endl;
2329 throw ProcessedSilentlyException("Got a DISCO");
2331 else if((controltype == CONTROLTYPE_ENABLE_BIG_SEND_WINDOW)
2332 && (peer_id <= MAX_UDP_PEERS))
2334 dynamic_cast<UDPPeer*>(&peer)->setNonLegacyPeer();
2335 throw ProcessedSilentlyException("Got non legacy control");
2338 LOG(derr_con<<m_connection->getDesc()
2339 <<"INVALID TYPE_CONTROL: invalid controltype="
2340 <<((int)controltype&0xff)<<std::endl);
2341 throw InvalidIncomingDataException("Invalid control type");
2344 else if(type == TYPE_ORIGINAL)
2346 if(packetdata.getSize() < ORIGINAL_HEADER_SIZE)
2347 throw InvalidIncomingDataException
2348 ("packetdata.getSize() < ORIGINAL_HEADER_SIZE");
2349 LOG(dout_con<<m_connection->getDesc()
2350 <<"RETURNING TYPE_ORIGINAL to user"
2352 // Get the inside packet out and return it
2353 SharedBuffer<u8> payload(packetdata.getSize() - ORIGINAL_HEADER_SIZE);
2354 memcpy(*payload, &packetdata[ORIGINAL_HEADER_SIZE], payload.getSize());
2357 else if(type == TYPE_SPLIT)
2359 Address peer_address;
2361 if (peer->getAddress(UDP,peer_address)) {
2363 // We have to create a packet again for buffering
2364 // This isn't actually too bad an idea.
2365 BufferedPacket packet = makePacket(
2368 m_connection->GetProtocolID(),
2372 // Buffer the packet
2373 SharedBuffer<u8> data =
2374 peer->addSpiltPacket(channelnum,packet,reliable);
2376 if(data.getSize() != 0)
2378 LOG(dout_con<<m_connection->getDesc()
2379 <<"RETURNING TYPE_SPLIT: Constructed full data, "
2380 <<"size="<<data.getSize()<<std::endl);
2383 LOG(dout_con<<m_connection->getDesc()<<"BUFFERED TYPE_SPLIT"<<std::endl);
2384 throw ProcessedSilentlyException("Buffered a split packet chunk");
2387 //TODO throw some error
2390 else if((peer_id <= MAX_UDP_PEERS) && (type == TYPE_RELIABLE))
2392 assert(channel != 0);
2393 // Recursive reliable packets not allowed
2395 throw InvalidIncomingDataException("Found nested reliable packets");
2397 if(packetdata.getSize() < RELIABLE_HEADER_SIZE)
2398 throw InvalidIncomingDataException
2399 ("packetdata.getSize() < RELIABLE_HEADER_SIZE");
2401 u16 seqnum = readU16(&packetdata[1]);
2402 bool is_future_packet = false;
2403 bool is_old_packet = false;
2405 /* packet is within our receive window send ack */
2406 if (seqnum_in_window(seqnum, channel->readNextIncomingSeqNum(),MAX_RELIABLE_WINDOW_SIZE))
2408 m_connection->sendAck(peer_id,channelnum,seqnum);
2411 is_future_packet = seqnum_higher(seqnum, channel->readNextIncomingSeqNum());
2412 is_old_packet = seqnum_higher(channel->readNextIncomingSeqNum(), seqnum);
2415 /* packet is not within receive window, don't send ack. *
2416 * if this was a valid packet it's gonna be retransmitted */
2417 if (is_future_packet)
2419 throw ProcessedSilentlyException("Received packet newer then expected, not sending ack");
2422 /* seems like our ack was lost, send another one for a old packet */
2425 LOG(dout_con<<m_connection->getDesc()
2426 << "RE-SENDING ACK: peer_id: " << peer_id
2427 << ", channel: " << (channelnum&0xFF)
2428 << ", seqnum: " << seqnum << std::endl;)
2429 m_connection->sendAck(peer_id,channelnum,seqnum);
2431 // we already have this packet so this one was on wire at least
2432 // the current timeout
2433 dynamic_cast<UDPPeer*>(&peer)->reportRTT(dynamic_cast<UDPPeer*>(&peer)->getResendTimeout());
2435 throw ProcessedSilentlyException("Retransmitting ack for old packet");
2439 if (seqnum != channel->readNextIncomingSeqNum())
2441 Address peer_address;
2443 // this is a reliable packet so we have a udp address for sure
2444 peer->getAddress(MINETEST_RELIABLE_UDP,peer_address);
2445 // This one comes later, buffer it.
2446 // Actually we have to make a packet to buffer one.
2447 // Well, we have all the ingredients, so just do it.
2448 BufferedPacket packet = con::makePacket(
2451 m_connection->GetProtocolID(),
2455 channel->incoming_reliables.insert(packet,channel->readNextIncomingSeqNum());
2457 LOG(dout_con<<m_connection->getDesc()
2458 << "BUFFERING, TYPE_RELIABLE peer_id: " << peer_id
2459 << ", channel: " << (channelnum&0xFF)
2460 << ", seqnum: " << seqnum << std::endl;)
2462 throw ProcessedQueued("Buffered future reliable packet");
2464 catch(AlreadyExistsException &e)
2467 catch(IncomingDataCorruption &e)
2469 ConnectionCommand discon;
2470 discon.disconnect_peer(peer_id);
2471 m_connection->putCommand(discon);
2473 LOG(derr_con<<m_connection->getDesc()
2474 << "INVALID, TYPE_RELIABLE peer_id: " << peer_id
2475 << ", channel: " << (channelnum&0xFF)
2476 << ", seqnum: " << seqnum
2477 << "DROPPING CLIENT!" << std::endl;)
2481 /* we got a packet to process right now */
2482 LOG(dout_con<<m_connection->getDesc()
2483 << "RECURSIVE, TYPE_RELIABLE peer_id: " << peer_id
2484 << ", channel: " << (channelnum&0xFF)
2485 << ", seqnum: " << seqnum << std::endl;)
2488 /* check for resend case */
2489 u16 queued_seqnum = 0;
2490 if (channel->incoming_reliables.getFirstSeqnum(queued_seqnum))
2492 if (queued_seqnum == seqnum)
2494 BufferedPacket queued_packet = channel->incoming_reliables.popFirst();
2495 /** TODO find a way to verify the new against the old packet */
2499 channel->incNextIncomingSeqNum();
2501 // Get out the inside packet and re-process it
2502 SharedBuffer<u8> payload(packetdata.getSize() - RELIABLE_HEADER_SIZE);
2503 memcpy(*payload, &packetdata[RELIABLE_HEADER_SIZE], payload.getSize());
2505 return processPacket(channel, payload, peer_id, channelnum, true);
2509 derr_con<<m_connection->getDesc()
2510 <<"Got invalid type="<<((int)type&0xff)<<std::endl;
2511 throw InvalidIncomingDataException("Invalid packet type");
2514 // We should never get here.
2515 // If you get here, add an exception or a return to some of the
2516 // above conditionals.
2518 throw BaseException("Error in Channel::ProcessPacket()");
2525 Connection::Connection(u32 protocol_id, u32 max_packet_size, float timeout,
2531 m_protocol_id(protocol_id),
2532 m_sendThread(this, max_packet_size, timeout),
2533 m_receiveThread(this, max_packet_size),
2535 m_bc_peerhandler(0),
2536 m_bc_receive_timeout(0),
2537 m_shutting_down(false)
2539 m_udpSocket.setTimeoutMs(5);
2541 m_sendThread.Start();
2542 m_receiveThread.Start();
2545 Connection::Connection(u32 protocol_id, u32 max_packet_size, float timeout,
2546 bool ipv6, PeerHandler *peerhandler):
2551 m_protocol_id(protocol_id),
2552 m_sendThread(this, max_packet_size, timeout),
2553 m_receiveThread(this, max_packet_size),
2555 m_bc_peerhandler(peerhandler),
2556 m_bc_receive_timeout(0),
2557 m_shutting_down(false)
2560 m_udpSocket.setTimeoutMs(5);
2562 m_sendThread.Start();
2563 m_receiveThread.Start();
2568 Connection::~Connection()
2570 m_shutting_down = true;
2571 // request threads to stop
2572 m_sendThread.Stop();
2573 m_receiveThread.Stop();
2575 //TODO for some unkonwn reason send/receive threads do not exit as they're
2576 // supposed to be but wait on peer timeout. To speed up shutdown we reduce
2577 // timeout to half a second.
2578 m_sendThread.setPeerTimeout(0.5);
2580 // wait for threads to finish
2581 m_sendThread.Wait();
2582 m_receiveThread.Wait();
2585 for(std::map<u16, Peer*>::iterator
2586 j = m_peers.begin();
2587 j != m_peers.end(); ++j)
2593 /* Internal stuff */
2594 void Connection::putEvent(ConnectionEvent &e)
2596 assert(e.type != CONNEVENT_NONE);
2597 m_event_queue.push_back(e);
2600 PeerHelper Connection::getPeer(u16 peer_id)
2602 JMutexAutoLock peerlock(m_peers_mutex);
2603 std::map<u16, Peer*>::iterator node = m_peers.find(peer_id);
2605 if(node == m_peers.end()){
2606 throw PeerNotFoundException("GetPeer: Peer not found (possible timeout)");
2610 assert(node->second->id == peer_id);
2612 return PeerHelper(node->second);
2615 PeerHelper Connection::getPeerNoEx(u16 peer_id)
2617 JMutexAutoLock peerlock(m_peers_mutex);
2618 std::map<u16, Peer*>::iterator node = m_peers.find(peer_id);
2620 if(node == m_peers.end()){
2621 return PeerHelper(NULL);
2625 assert(node->second->id == peer_id);
2627 return PeerHelper(node->second);
2630 /* find peer_id for address */
2631 u16 Connection::lookupPeer(Address& sender)
2633 JMutexAutoLock peerlock(m_peers_mutex);
2634 std::map<u16, Peer*>::iterator j;
2635 j = m_peers.begin();
2636 for(; j != m_peers.end(); ++j)
2638 Peer *peer = j->second;
2639 if(peer->isActive())
2644 if ((peer->getAddress(MINETEST_RELIABLE_UDP,tocheck)) && (tocheck == sender))
2647 if ((peer->getAddress(UDP,tocheck)) && (tocheck == sender))
2651 return PEER_ID_INEXISTENT;
2654 std::list<Peer*> Connection::getPeers()
2656 std::list<Peer*> list;
2657 for(std::map<u16, Peer*>::iterator j = m_peers.begin();
2658 j != m_peers.end(); ++j)
2660 Peer *peer = j->second;
2661 list.push_back(peer);
2666 bool Connection::deletePeer(u16 peer_id, bool timeout)
2670 /* lock list as short as possible */
2672 JMutexAutoLock peerlock(m_peers_mutex);
2673 if(m_peers.find(peer_id) == m_peers.end())
2675 peer = m_peers[peer_id];
2676 m_peers.erase(peer_id);
2679 Address peer_address;
2680 //any peer has a primary address this never fails!
2681 peer->getAddress(PRIMARY,peer_address);
2684 e.peerRemoved(peer_id, timeout, peer_address);
2694 ConnectionEvent Connection::getEvent()
2696 if(m_event_queue.empty()){
2698 e.type = CONNEVENT_NONE;
2701 return m_event_queue.pop_frontNoEx();
2704 ConnectionEvent Connection::waitEvent(u32 timeout_ms)
2707 return m_event_queue.pop_front(timeout_ms);
2708 } catch(ItemNotFoundException &ex){
2710 e.type = CONNEVENT_NONE;
2715 void Connection::putCommand(ConnectionCommand &c)
2717 if (!m_shutting_down)
2719 m_command_queue.push_back(c);
2720 m_sendThread.Trigger();
2724 void Connection::Serve(unsigned short port)
2726 ConnectionCommand c;
2731 void Connection::Connect(Address address)
2733 ConnectionCommand c;
2738 bool Connection::Connected()
2740 JMutexAutoLock peerlock(m_peers_mutex);
2742 if(m_peers.size() != 1)
2745 std::map<u16, Peer*>::iterator node = m_peers.find(PEER_ID_SERVER);
2746 if(node == m_peers.end())
2749 if(m_peer_id == PEER_ID_INEXISTENT)
2755 void Connection::Disconnect()
2757 ConnectionCommand c;
2762 u32 Connection::Receive(u16 &peer_id, SharedBuffer<u8> &data)
2765 ConnectionEvent e = waitEvent(m_bc_receive_timeout);
2766 if(e.type != CONNEVENT_NONE)
2767 LOG(dout_con<<getDesc()<<": Receive: got event: "
2768 <<e.describe()<<std::endl);
2770 case CONNEVENT_NONE:
2771 throw NoIncomingDataException("No incoming data");
2772 case CONNEVENT_DATA_RECEIVED:
2773 peer_id = e.peer_id;
2774 data = SharedBuffer<u8>(e.data);
2775 return e.data.getSize();
2776 case CONNEVENT_PEER_ADDED: {
2777 UDPPeer tmp(e.peer_id, e.address, this);
2778 if(m_bc_peerhandler)
2779 m_bc_peerhandler->peerAdded(&tmp);
2781 case CONNEVENT_PEER_REMOVED: {
2782 UDPPeer tmp(e.peer_id, e.address, this);
2783 if(m_bc_peerhandler)
2784 m_bc_peerhandler->deletingPeer(&tmp, e.timeout);
2786 case CONNEVENT_BIND_FAILED:
2787 throw ConnectionBindFailed("Failed to bind socket "
2788 "(port already in use?)");
2791 throw NoIncomingDataException("No incoming data");
2794 void Connection::SendToAll(u8 channelnum, SharedBuffer<u8> data, bool reliable)
2796 assert(channelnum < CHANNEL_COUNT);
2798 ConnectionCommand c;
2799 c.sendToAll(channelnum, data, reliable);
2803 void Connection::Send(u16 peer_id, u8 channelnum,
2804 SharedBuffer<u8> data, bool reliable)
2806 assert(channelnum < CHANNEL_COUNT);
2808 ConnectionCommand c;
2809 c.send(peer_id, channelnum, data, reliable);
2813 void Connection::RunTimeouts(float dtime)
2818 Address Connection::GetPeerAddress(u16 peer_id)
2820 PeerHelper peer = getPeerNoEx(peer_id);
2823 throw PeerNotFoundException("No address for peer found!");
2824 Address peer_address;
2825 peer->getAddress(PRIMARY,peer_address);
2826 return peer_address;
2829 float Connection::GetPeerAvgRTT(u16 peer_id)
2831 PeerHelper peer = getPeerNoEx(peer_id);
2832 if (!peer) return -1;
2833 return peer->getStat(AVG_RTT);
2836 u16 Connection::createPeer(Address& sender, MTProtocols protocol, int fd)
2838 // Somebody wants to make a new connection
2840 // Get a unique peer id (2 or higher)
2841 u16 peer_id_new = 2;
2842 u16 overflow = MAX_UDP_PEERS;
2845 Find an unused peer id
2847 bool out_of_ids = false;
2851 if(m_peers.find(peer_id_new) == m_peers.end())
2853 // Check for overflow
2854 if(peer_id_new == overflow){
2861 errorstream<<getDesc()<<" ran out of peer ids"<<std::endl;
2862 return PEER_ID_INEXISTENT;
2865 LOG(dout_con<<getDesc()
2866 <<"createPeer(): giving peer_id="<<peer_id_new<<std::endl);
2871 peer = new UDPPeer(peer_id_new, sender, this);
2873 m_peers_mutex.Lock();
2874 m_peers[peer->id] = peer;
2875 m_peers_mutex.Unlock();
2877 // Create peer addition event
2879 e.peerAdded(peer_id_new, sender);
2882 ConnectionCommand cmd;
2883 SharedBuffer<u8> reply(4);
2884 writeU8(&reply[0], TYPE_CONTROL);
2885 writeU8(&reply[1], CONTROLTYPE_SET_PEER_ID);
2886 writeU16(&reply[2], peer_id_new);
2887 cmd.createPeer(peer_id_new,reply);
2888 this->putCommand(cmd);
2890 // We're now talking to a valid peer_id
2894 void Connection::DeletePeer(u16 peer_id)
2896 ConnectionCommand c;
2897 c.deletePeer(peer_id);
2901 void Connection::PrintInfo(std::ostream &out)
2903 m_info_mutex.Lock();
2904 out<<getDesc()<<": ";
2905 m_info_mutex.Unlock();
2908 void Connection::PrintInfo()
2910 PrintInfo(dout_con);
2913 const std::string Connection::getDesc()
2915 return std::string("con(")+itos(m_udpSocket.GetHandle())+"/"+itos(m_peer_id)+")";
2918 void Connection::sendAck(u16 peer_id, u8 channelnum, u16 seqnum) {
2920 assert(channelnum < CHANNEL_COUNT);
2922 LOG(dout_con<<getDesc()
2923 <<" Queuing ACK command to peer_id: " << peer_id <<
2924 " channel: " << (channelnum & 0xFF) <<
2925 " seqnum: " << seqnum << std::endl);
2927 ConnectionCommand c;
2928 SharedBuffer<u8> ack(4);
2929 writeU8(&ack[0], TYPE_CONTROL);
2930 writeU8(&ack[1], CONTROLTYPE_ACK);
2931 writeU16(&ack[2], seqnum);
2933 c.ack(peer_id, channelnum, ack);
2935 m_sendThread.Trigger();
2938 UDPPeer* Connection::createServerPeer(Address& address)
2940 if (getPeerNoEx(PEER_ID_SERVER) != 0)
2942 throw ConnectionException("Already connected to a server");
2945 UDPPeer *peer = new UDPPeer(PEER_ID_SERVER, address, this);
2948 JMutexAutoLock lock(m_peers_mutex);
2949 m_peers[peer->id] = peer;
2955 std::list<u16> Connection::getPeerIDs()
2957 std::list<u16> retval;
2959 JMutexAutoLock lock(m_peers_mutex);
2960 for(std::map<u16, Peer*>::iterator j = m_peers.begin();
2961 j != m_peers.end(); ++j)
2963 retval.push_back(j->first);