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 /* send non reliable packets*/
1847 for(unsigned int i=0;i < m_outgoing_queue.size();i++) {
1848 OutgoingPacket packet = m_outgoing_queue.pop_front();
1850 assert(!packet.reliable &&
1851 "reliable packets are not allowed in outgoing queue!");
1853 PeerHelper peer = m_connection->getPeerNoEx(packet.peer_id);
1855 LOG(dout_con<<m_connection->getDesc()
1856 <<" Outgoing queue: peer_id="<<packet.peer_id
1857 << ">>>NOT<<< found on sending packet"
1858 << ", channel " << (packet.channelnum % 0xFF)
1859 << ", size: " << packet.data.getSize() <<std::endl);
1862 /* send acks immediately */
1863 else if (packet.ack)
1865 rawSendAsPacket(packet.peer_id, packet.channelnum,
1866 packet.data, packet.reliable);
1867 peer->m_increment_packets_remaining =
1868 MYMIN(0,peer->m_increment_packets_remaining--);
1871 ( peer->m_increment_packets_remaining > 0) ||
1873 rawSendAsPacket(packet.peer_id, packet.channelnum,
1874 packet.data, packet.reliable);
1875 peer->m_increment_packets_remaining--;
1878 m_outgoing_queue.push_back(packet);
1883 void ConnectionSendThread::sendAsPacket(u16 peer_id, u8 channelnum,
1884 SharedBuffer<u8> data, bool ack)
1886 OutgoingPacket packet(peer_id, channelnum, data, false, ack);
1887 m_outgoing_queue.push_back(packet);
1890 ConnectionReceiveThread::ConnectionReceiveThread(Connection* parent,
1891 unsigned int max_packet_size) :
1892 m_connection(parent),
1893 m_max_packet_size(max_packet_size)
1897 void * ConnectionReceiveThread::Thread()
1900 log_register_thread("ConnectionReceive");
1902 LOG(dout_con<<m_connection->getDesc()
1903 <<"ConnectionReceive thread started"<<std::endl);
1905 PROFILE(std::stringstream ThreadIdentifier);
1906 PROFILE(ThreadIdentifier << "ConnectionReceive: [" << m_connection->getDesc() << "]");
1908 #ifdef DEBUG_CONNECTION_KBPS
1909 u32 curtime = porting::getTimeMs();
1910 u32 lasttime = curtime;
1911 float debug_print_timer = 0.0;
1914 while(!StopRequested()) {
1915 BEGIN_DEBUG_EXCEPTION_HANDLER
1916 PROFILE(ScopeProfiler sp(g_profiler, ThreadIdentifier.str(), SPT_AVG));
1918 #ifdef DEBUG_CONNECTION_KBPS
1920 curtime = porting::getTimeMs();
1921 float dtime = CALC_DTIME(lasttime,curtime);
1924 /* receive packets */
1927 #ifdef DEBUG_CONNECTION_KBPS
1928 debug_print_timer += dtime;
1929 if (debug_print_timer > 20.0) {
1930 debug_print_timer -= 20.0;
1932 std::list<u16> peerids = m_connection->getPeerIDs();
1934 for (std::list<u16>::iterator i = peerids.begin();
1938 PeerHelper peer = m_connection->getPeerNoEx(*i);
1942 float peer_current = 0.0;
1943 float peer_loss = 0.0;
1944 float avg_rate = 0.0;
1945 float avg_loss = 0.0;
1947 for(u16 j=0; j<CHANNEL_COUNT; j++)
1949 peer_current +=peer->channels[j].getCurrentDownloadRateKB();
1950 peer_loss += peer->channels[j].getCurrentLossRateKB();
1951 avg_rate += peer->channels[j].getAvgDownloadRateKB();
1952 avg_loss += peer->channels[j].getAvgLossRateKB();
1955 std::stringstream output;
1956 output << std::fixed << std::setprecision(1);
1957 output << "OUT to Peer " << *i << " RATES (good / loss) " << std::endl;
1958 output << "\tcurrent (sum): " << peer_current << "kb/s "<< peer_loss << "kb/s" << std::endl;
1959 output << "\taverage (sum): " << avg_rate << "kb/s "<< avg_loss << "kb/s" << std::endl;
1960 output << std::setfill(' ');
1961 for(u16 j=0; j<CHANNEL_COUNT; j++)
1963 output << "\tcha " << j << ":"
1964 << " CUR: " << std::setw(6) << peer->channels[j].getCurrentDownloadRateKB() <<"kb/s"
1965 << " AVG: " << std::setw(6) << peer->channels[j].getAvgDownloadRateKB() <<"kb/s"
1966 << " MAX: " << std::setw(6) << peer->channels[j].getMaxDownloadRateKB() <<"kb/s"
1968 << " CUR: " << std::setw(6) << peer->channels[j].getCurrentLossRateKB() <<"kb/s"
1969 << " AVG: " << std::setw(6) << peer->channels[j].getAvgLossRateKB() <<"kb/s"
1970 << " MAX: " << std::setw(6) << peer->channels[j].getMaxLossRateKB() <<"kb/s"
1971 << " / WS: " << peer->channels[j].getWindowSize()
1975 fprintf(stderr,"%s\n",output.str().c_str());
1979 END_DEBUG_EXCEPTION_HANDLER(derr_con);
1981 PROFILE(g_profiler->remove(ThreadIdentifier.str()));
1985 // Receive packets from the network and buffers and create ConnectionEvents
1986 void ConnectionReceiveThread::receive()
1988 /* now reorder reliables */
1989 u32 datasize = m_max_packet_size * 2; // Double it just to be safe
1990 // TODO: We can not know how many layers of header there are.
1991 // For now, just assume there are no other than the base headers.
1992 u32 packet_maxsize = datasize + BASE_HEADER_SIZE;
1993 SharedBuffer<u8> packetdata(packet_maxsize);
1995 bool packet_queued = true;
1997 unsigned int loop_count = 0;
1999 /* first of all read packets from socket */
2000 /* check for incoming data available */
2001 while( (loop_count < 10) &&
2002 (m_connection->m_udpSocket.WaitData(50)))
2008 bool no_data_left = false;
2010 SharedBuffer<u8> resultdata;
2011 while(!no_data_left)
2014 no_data_left = !getFromBuffers(peer_id, resultdata);
2015 if (!no_data_left) {
2017 e.dataReceived(peer_id, resultdata);
2018 m_connection->putEvent(e);
2021 catch(ProcessedSilentlyException e) {
2022 /* try reading again */
2025 packet_queued = false;
2029 s32 received_size = m_connection->m_udpSocket.Receive(sender, *packetdata, packet_maxsize);
2031 if ((received_size < 0) ||
2032 (received_size < BASE_HEADER_SIZE) ||
2033 (readU32(&packetdata[0]) != m_connection->GetProtocolID()))
2035 LOG(derr_con<<m_connection->getDesc()
2036 <<"Receive(): Invalid incoming packet, "
2037 <<"size: " << received_size
2038 <<", protocol: " << readU32(&packetdata[0]) <<std::endl);
2041 u16 peer_id = readPeerId(*packetdata);
2042 u8 channelnum = readChannel(*packetdata);
2044 if(channelnum > CHANNEL_COUNT-1){
2045 LOG(derr_con<<m_connection->getDesc()
2046 <<"Receive(): Invalid channel "<<channelnum<<std::endl);
2047 throw InvalidIncomingDataException("Channel doesn't exist");
2050 /* preserve original peer_id for later usage */
2051 u16 packet_peer_id = peer_id;
2053 /* Try to identify peer by sender address (may happen on join) */
2054 if(peer_id == PEER_ID_INEXISTENT)
2056 peer_id = m_connection->lookupPeer(sender);
2059 /* The peer was not found in our lists. Add it. */
2060 if(peer_id == PEER_ID_INEXISTENT)
2062 peer_id = m_connection->createPeer(sender,MINETEST_RELIABLE_UDP,0);
2065 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
2068 LOG(dout_con<<m_connection->getDesc()
2069 <<" got packet from unknown peer_id: "
2070 <<peer_id<<" Ignoring."<<std::endl);
2074 // Validate peer address
2076 Address peer_address;
2078 if (peer->getAddress(UDP,peer_address)) {
2079 if (peer_address != sender) {
2080 LOG(derr_con<<m_connection->getDesc()
2081 <<m_connection->getDesc()
2082 <<" Peer "<<peer_id<<" sending from different address."
2083 " Ignoring."<<std::endl);
2089 bool invalid_address = true;
2090 if (invalid_address) {
2091 LOG(derr_con<<m_connection->getDesc()
2092 <<m_connection->getDesc()
2093 <<" Peer "<<peer_id<<" unknown."
2094 " Ignoring."<<std::endl);
2100 /* mark peer as seen with id */
2101 if (!(packet_peer_id == PEER_ID_INEXISTENT))
2102 peer->setSentWithID();
2104 peer->ResetTimeout();
2106 Channel *channel = 0;
2108 if (dynamic_cast<UDPPeer*>(&peer) != 0)
2110 channel = &(dynamic_cast<UDPPeer*>(&peer)->channels[channelnum]);
2113 // Throw the received packet to channel->processPacket()
2115 // Make a new SharedBuffer from the data without the base headers
2116 SharedBuffer<u8> strippeddata(received_size - BASE_HEADER_SIZE);
2117 memcpy(*strippeddata, &packetdata[BASE_HEADER_SIZE],
2118 strippeddata.getSize());
2121 // Process it (the result is some data with no headers made by us)
2122 SharedBuffer<u8> resultdata = processPacket
2123 (channel, strippeddata, peer_id, channelnum, false);
2125 LOG(dout_con<<m_connection->getDesc()
2126 <<" ProcessPacket from peer_id: " << peer_id
2127 << ",channel: " << channelnum << ", returned "
2128 << resultdata.getSize() << " bytes" <<std::endl);
2131 e.dataReceived(peer_id, resultdata);
2132 m_connection->putEvent(e);
2133 }catch(ProcessedSilentlyException &e){
2134 }catch(ProcessedQueued &e){
2135 packet_queued = true;
2137 }catch(InvalidIncomingDataException &e){
2139 catch(ProcessedSilentlyException &e){
2144 bool ConnectionReceiveThread::getFromBuffers(u16 &peer_id, SharedBuffer<u8> &dst)
2146 std::list<u16> peerids = m_connection->getPeerIDs();
2148 for(std::list<u16>::iterator j = peerids.begin();
2149 j != peerids.end(); ++j)
2151 PeerHelper peer = m_connection->getPeerNoEx(*j);
2155 if(dynamic_cast<UDPPeer*>(&peer) == 0)
2158 for(u16 i=0; i<CHANNEL_COUNT; i++)
2160 Channel *channel = &(dynamic_cast<UDPPeer*>(&peer))->channels[i];
2162 SharedBuffer<u8> resultdata;
2163 bool got = checkIncomingBuffers(channel, peer_id, resultdata);
2173 bool ConnectionReceiveThread::checkIncomingBuffers(Channel *channel, u16 &peer_id,
2174 SharedBuffer<u8> &dst)
2176 u16 firstseqnum = 0;
2177 if (channel->incoming_reliables.getFirstSeqnum(firstseqnum))
2179 if(firstseqnum == channel->readNextIncomingSeqNum())
2181 BufferedPacket p = channel->incoming_reliables.popFirst();
2182 peer_id = readPeerId(*p.data);
2183 u8 channelnum = readChannel(*p.data);
2184 u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]);
2186 LOG(dout_con<<m_connection->getDesc()
2187 <<"UNBUFFERING TYPE_RELIABLE"
2188 <<" seqnum="<<seqnum
2189 <<" peer_id="<<peer_id
2190 <<" channel="<<((int)channelnum&0xff)
2193 channel->incNextIncomingSeqNum();
2195 u32 headers_size = BASE_HEADER_SIZE + RELIABLE_HEADER_SIZE;
2196 // Get out the inside packet and re-process it
2197 SharedBuffer<u8> payload(p.data.getSize() - headers_size);
2198 memcpy(*payload, &p.data[headers_size], payload.getSize());
2200 dst = processPacket(channel, payload, peer_id, channelnum, true);
2207 SharedBuffer<u8> ConnectionReceiveThread::processPacket(Channel *channel,
2208 SharedBuffer<u8> packetdata, u16 peer_id,
2209 u8 channelnum, bool reliable)
2211 PeerHelper peer = m_connection->getPeer(peer_id);
2213 if(packetdata.getSize() < 1)
2214 throw InvalidIncomingDataException("packetdata.getSize() < 1");
2216 u8 type = readU8(&packetdata[0]);
2218 if(type == TYPE_CONTROL)
2220 if(packetdata.getSize() < 2)
2221 throw InvalidIncomingDataException("packetdata.getSize() < 2");
2223 u8 controltype = readU8(&packetdata[1]);
2225 if( (controltype == CONTROLTYPE_ACK)
2226 && (peer_id <= MAX_UDP_PEERS))
2228 assert(channel != 0);
2229 if(packetdata.getSize() < 4)
2230 throw InvalidIncomingDataException
2231 ("packetdata.getSize() < 4 (ACK header size)");
2233 u16 seqnum = readU16(&packetdata[2]);
2234 LOG(dout_con<<m_connection->getDesc()
2235 <<" [ CONTROLTYPE_ACK: channelnum="
2236 <<((int)channelnum&0xff)<<", peer_id="<<peer_id
2237 <<", seqnum="<<seqnum<< " ]"<<std::endl);
2241 channel->outgoing_reliables_sent.popSeqnum(seqnum);
2242 // Get round trip time
2243 unsigned int current_time = porting::getTimeMs();
2245 if (current_time > p.absolute_send_time)
2247 float rtt = (current_time - p.absolute_send_time) / 1000.0;
2249 // Let peer calculate stuff according to it
2250 // (avg_rtt and resend_timeout)
2251 dynamic_cast<UDPPeer*>(&peer)->reportRTT(rtt);
2253 else if (p.totaltime > 0)
2255 float rtt = p.totaltime;
2257 // Let peer calculate stuff according to it
2258 // (avg_rtt and resend_timeout)
2259 dynamic_cast<UDPPeer*>(&peer)->reportRTT(rtt);
2261 //put bytes for max bandwidth calculation
2262 channel->UpdateBytesSent(p.data.getSize(),1);
2264 catch(NotFoundException &e){
2265 LOG(derr_con<<m_connection->getDesc()
2266 <<"WARNING: ACKed packet not "
2269 channel->UpdatePacketTooLateCounter();
2271 throw ProcessedSilentlyException("Got an ACK");
2273 else if((controltype == CONTROLTYPE_SET_PEER_ID)
2274 && (peer_id <= MAX_UDP_PEERS))
2276 // Got a packet to set our peer id
2277 if(packetdata.getSize() < 4)
2278 throw InvalidIncomingDataException
2279 ("packetdata.getSize() < 4 (SET_PEER_ID header size)");
2280 u16 peer_id_new = readU16(&packetdata[2]);
2281 LOG(dout_con<<m_connection->getDesc()
2282 <<"Got new peer id: "<<peer_id_new<<"... "<<std::endl);
2284 if(m_connection->GetPeerID() != PEER_ID_INEXISTENT)
2286 LOG(derr_con<<m_connection->getDesc()
2287 <<"WARNING: Not changing"
2288 " existing peer id."<<std::endl);
2292 LOG(dout_con<<m_connection->getDesc()<<"changing own peer id"<<std::endl);
2293 m_connection->SetPeerID(peer_id_new);
2296 ConnectionCommand cmd;
2298 SharedBuffer<u8> reply(2);
2299 writeU8(&reply[0], TYPE_CONTROL);
2300 writeU8(&reply[1], CONTROLTYPE_ENABLE_BIG_SEND_WINDOW);
2301 cmd.disableLegacy(PEER_ID_SERVER,reply);
2302 m_connection->putCommand(cmd);
2304 throw ProcessedSilentlyException("Got a SET_PEER_ID");
2306 else if((controltype == CONTROLTYPE_PING)
2307 && (peer_id <= MAX_UDP_PEERS))
2309 // Just ignore it, the incoming data already reset
2310 // the timeout counter
2311 LOG(dout_con<<m_connection->getDesc()<<"PING"<<std::endl);
2312 throw ProcessedSilentlyException("Got a PING");
2314 else if(controltype == CONTROLTYPE_DISCO)
2316 // Just ignore it, the incoming data already reset
2317 // the timeout counter
2318 LOG(dout_con<<m_connection->getDesc()
2319 <<"DISCO: Removing peer "<<(peer_id)<<std::endl);
2321 if(m_connection->deletePeer(peer_id, false) == false)
2323 derr_con<<m_connection->getDesc()
2324 <<"DISCO: Peer not found"<<std::endl;
2327 throw ProcessedSilentlyException("Got a DISCO");
2329 else if((controltype == CONTROLTYPE_ENABLE_BIG_SEND_WINDOW)
2330 && (peer_id <= MAX_UDP_PEERS))
2332 dynamic_cast<UDPPeer*>(&peer)->setNonLegacyPeer();
2333 throw ProcessedSilentlyException("Got non legacy control");
2336 LOG(derr_con<<m_connection->getDesc()
2337 <<"INVALID TYPE_CONTROL: invalid controltype="
2338 <<((int)controltype&0xff)<<std::endl);
2339 throw InvalidIncomingDataException("Invalid control type");
2342 else if(type == TYPE_ORIGINAL)
2344 if(packetdata.getSize() < ORIGINAL_HEADER_SIZE)
2345 throw InvalidIncomingDataException
2346 ("packetdata.getSize() < ORIGINAL_HEADER_SIZE");
2347 LOG(dout_con<<m_connection->getDesc()
2348 <<"RETURNING TYPE_ORIGINAL to user"
2350 // Get the inside packet out and return it
2351 SharedBuffer<u8> payload(packetdata.getSize() - ORIGINAL_HEADER_SIZE);
2352 memcpy(*payload, &packetdata[ORIGINAL_HEADER_SIZE], payload.getSize());
2355 else if(type == TYPE_SPLIT)
2357 Address peer_address;
2359 if (peer->getAddress(UDP,peer_address)) {
2361 // We have to create a packet again for buffering
2362 // This isn't actually too bad an idea.
2363 BufferedPacket packet = makePacket(
2366 m_connection->GetProtocolID(),
2370 // Buffer the packet
2371 SharedBuffer<u8> data =
2372 peer->addSpiltPacket(channelnum,packet,reliable);
2374 if(data.getSize() != 0)
2376 LOG(dout_con<<m_connection->getDesc()
2377 <<"RETURNING TYPE_SPLIT: Constructed full data, "
2378 <<"size="<<data.getSize()<<std::endl);
2381 LOG(dout_con<<m_connection->getDesc()<<"BUFFERED TYPE_SPLIT"<<std::endl);
2382 throw ProcessedSilentlyException("Buffered a split packet chunk");
2385 //TODO throw some error
2388 else if((peer_id <= MAX_UDP_PEERS) && (type == TYPE_RELIABLE))
2390 assert(channel != 0);
2391 // Recursive reliable packets not allowed
2393 throw InvalidIncomingDataException("Found nested reliable packets");
2395 if(packetdata.getSize() < RELIABLE_HEADER_SIZE)
2396 throw InvalidIncomingDataException
2397 ("packetdata.getSize() < RELIABLE_HEADER_SIZE");
2399 u16 seqnum = readU16(&packetdata[1]);
2400 bool is_future_packet = false;
2401 bool is_old_packet = false;
2403 /* packet is within our receive window send ack */
2404 if (seqnum_in_window(seqnum, channel->readNextIncomingSeqNum(),MAX_RELIABLE_WINDOW_SIZE))
2406 m_connection->sendAck(peer_id,channelnum,seqnum);
2409 is_future_packet = seqnum_higher(seqnum, channel->readNextIncomingSeqNum());
2410 is_old_packet = seqnum_higher(channel->readNextIncomingSeqNum(), seqnum);
2413 /* packet is not within receive window, don't send ack. *
2414 * if this was a valid packet it's gonna be retransmitted */
2415 if (is_future_packet)
2417 throw ProcessedSilentlyException("Received packet newer then expected, not sending ack");
2420 /* seems like our ack was lost, send another one for a old packet */
2423 LOG(dout_con<<m_connection->getDesc()
2424 << "RE-SENDING ACK: peer_id: " << peer_id
2425 << ", channel: " << (channelnum&0xFF)
2426 << ", seqnum: " << seqnum << std::endl;)
2427 m_connection->sendAck(peer_id,channelnum,seqnum);
2429 // we already have this packet so this one was on wire at least
2430 // the current timeout
2431 dynamic_cast<UDPPeer*>(&peer)->reportRTT(dynamic_cast<UDPPeer*>(&peer)->getResendTimeout());
2433 throw ProcessedSilentlyException("Retransmitting ack for old packet");
2437 if (seqnum != channel->readNextIncomingSeqNum())
2439 Address peer_address;
2441 // this is a reliable packet so we have a udp address for sure
2442 peer->getAddress(MINETEST_RELIABLE_UDP,peer_address);
2443 // This one comes later, buffer it.
2444 // Actually we have to make a packet to buffer one.
2445 // Well, we have all the ingredients, so just do it.
2446 BufferedPacket packet = con::makePacket(
2449 m_connection->GetProtocolID(),
2453 channel->incoming_reliables.insert(packet,channel->readNextIncomingSeqNum());
2455 LOG(dout_con<<m_connection->getDesc()
2456 << "BUFFERING, TYPE_RELIABLE peer_id: " << peer_id
2457 << ", channel: " << (channelnum&0xFF)
2458 << ", seqnum: " << seqnum << std::endl;)
2460 throw ProcessedQueued("Buffered future reliable packet");
2462 catch(AlreadyExistsException &e)
2465 catch(IncomingDataCorruption &e)
2467 ConnectionCommand discon;
2468 discon.disconnect_peer(peer_id);
2469 m_connection->putCommand(discon);
2471 LOG(derr_con<<m_connection->getDesc()
2472 << "INVALID, TYPE_RELIABLE peer_id: " << peer_id
2473 << ", channel: " << (channelnum&0xFF)
2474 << ", seqnum: " << seqnum
2475 << "DROPPING CLIENT!" << std::endl;)
2479 /* we got a packet to process right now */
2480 LOG(dout_con<<m_connection->getDesc()
2481 << "RECURSIVE, TYPE_RELIABLE peer_id: " << peer_id
2482 << ", channel: " << (channelnum&0xFF)
2483 << ", seqnum: " << seqnum << std::endl;)
2486 /* check for resend case */
2487 u16 queued_seqnum = 0;
2488 if (channel->incoming_reliables.getFirstSeqnum(queued_seqnum))
2490 if (queued_seqnum == seqnum)
2492 BufferedPacket queued_packet = channel->incoming_reliables.popFirst();
2493 /** TODO find a way to verify the new against the old packet */
2497 channel->incNextIncomingSeqNum();
2499 // Get out the inside packet and re-process it
2500 SharedBuffer<u8> payload(packetdata.getSize() - RELIABLE_HEADER_SIZE);
2501 memcpy(*payload, &packetdata[RELIABLE_HEADER_SIZE], payload.getSize());
2503 return processPacket(channel, payload, peer_id, channelnum, true);
2507 derr_con<<m_connection->getDesc()
2508 <<"Got invalid type="<<((int)type&0xff)<<std::endl;
2509 throw InvalidIncomingDataException("Invalid packet type");
2512 // We should never get here.
2513 // If you get here, add an exception or a return to some of the
2514 // above conditionals.
2516 throw BaseException("Error in Channel::ProcessPacket()");
2523 Connection::Connection(u32 protocol_id, u32 max_packet_size, float timeout,
2529 m_protocol_id(protocol_id),
2530 m_sendThread(this, max_packet_size, timeout),
2531 m_receiveThread(this, max_packet_size),
2533 m_bc_peerhandler(0),
2534 m_bc_receive_timeout(0),
2535 m_shutting_down(false)
2537 m_udpSocket.setTimeoutMs(5);
2539 m_sendThread.Start();
2540 m_receiveThread.Start();
2543 Connection::Connection(u32 protocol_id, u32 max_packet_size, float timeout,
2544 bool ipv6, PeerHandler *peerhandler):
2549 m_protocol_id(protocol_id),
2550 m_sendThread(this, max_packet_size, timeout),
2551 m_receiveThread(this, max_packet_size),
2553 m_bc_peerhandler(peerhandler),
2554 m_bc_receive_timeout(0),
2555 m_shutting_down(false)
2558 m_udpSocket.setTimeoutMs(5);
2560 m_sendThread.Start();
2561 m_receiveThread.Start();
2566 Connection::~Connection()
2568 m_shutting_down = true;
2569 // request threads to stop
2570 m_sendThread.Stop();
2571 m_receiveThread.Stop();
2573 //TODO for some unkonwn reason send/receive threads do not exit as they're
2574 // supposed to be but wait on peer timeout. To speed up shutdown we reduce
2575 // timeout to half a second.
2576 m_sendThread.setPeerTimeout(0.5);
2578 // wait for threads to finish
2579 m_sendThread.Wait();
2580 m_receiveThread.Wait();
2583 for(std::map<u16, Peer*>::iterator
2584 j = m_peers.begin();
2585 j != m_peers.end(); ++j)
2591 /* Internal stuff */
2592 void Connection::putEvent(ConnectionEvent &e)
2594 assert(e.type != CONNEVENT_NONE);
2595 m_event_queue.push_back(e);
2598 PeerHelper Connection::getPeer(u16 peer_id)
2600 JMutexAutoLock peerlock(m_peers_mutex);
2601 std::map<u16, Peer*>::iterator node = m_peers.find(peer_id);
2603 if(node == m_peers.end()){
2604 throw PeerNotFoundException("GetPeer: Peer not found (possible timeout)");
2608 assert(node->second->id == peer_id);
2610 return PeerHelper(node->second);
2613 PeerHelper Connection::getPeerNoEx(u16 peer_id)
2615 JMutexAutoLock peerlock(m_peers_mutex);
2616 std::map<u16, Peer*>::iterator node = m_peers.find(peer_id);
2618 if(node == m_peers.end()){
2619 return PeerHelper(NULL);
2623 assert(node->second->id == peer_id);
2625 return PeerHelper(node->second);
2628 /* find peer_id for address */
2629 u16 Connection::lookupPeer(Address& sender)
2631 JMutexAutoLock peerlock(m_peers_mutex);
2632 std::map<u16, Peer*>::iterator j;
2633 j = m_peers.begin();
2634 for(; j != m_peers.end(); ++j)
2636 Peer *peer = j->second;
2637 if(peer->isActive())
2642 if ((peer->getAddress(MINETEST_RELIABLE_UDP,tocheck)) && (tocheck == sender))
2645 if ((peer->getAddress(UDP,tocheck)) && (tocheck == sender))
2649 return PEER_ID_INEXISTENT;
2652 std::list<Peer*> Connection::getPeers()
2654 std::list<Peer*> list;
2655 for(std::map<u16, Peer*>::iterator j = m_peers.begin();
2656 j != m_peers.end(); ++j)
2658 Peer *peer = j->second;
2659 list.push_back(peer);
2664 bool Connection::deletePeer(u16 peer_id, bool timeout)
2668 /* lock list as short as possible */
2670 JMutexAutoLock peerlock(m_peers_mutex);
2671 if(m_peers.find(peer_id) == m_peers.end())
2673 peer = m_peers[peer_id];
2674 m_peers.erase(peer_id);
2677 Address peer_address;
2678 //any peer has a primary address this never fails!
2679 peer->getAddress(PRIMARY,peer_address);
2682 e.peerRemoved(peer_id, timeout, peer_address);
2692 ConnectionEvent Connection::getEvent()
2694 if(m_event_queue.empty()){
2696 e.type = CONNEVENT_NONE;
2699 return m_event_queue.pop_frontNoEx();
2702 ConnectionEvent Connection::waitEvent(u32 timeout_ms)
2705 return m_event_queue.pop_front(timeout_ms);
2706 } catch(ItemNotFoundException &ex){
2708 e.type = CONNEVENT_NONE;
2713 void Connection::putCommand(ConnectionCommand &c)
2715 if (!m_shutting_down)
2717 m_command_queue.push_back(c);
2718 m_sendThread.Trigger();
2722 void Connection::Serve(unsigned short port)
2724 ConnectionCommand c;
2729 void Connection::Connect(Address address)
2731 ConnectionCommand c;
2736 bool Connection::Connected()
2738 JMutexAutoLock peerlock(m_peers_mutex);
2740 if(m_peers.size() != 1)
2743 std::map<u16, Peer*>::iterator node = m_peers.find(PEER_ID_SERVER);
2744 if(node == m_peers.end())
2747 if(m_peer_id == PEER_ID_INEXISTENT)
2753 void Connection::Disconnect()
2755 ConnectionCommand c;
2760 u32 Connection::Receive(u16 &peer_id, SharedBuffer<u8> &data)
2763 ConnectionEvent e = waitEvent(m_bc_receive_timeout);
2764 if(e.type != CONNEVENT_NONE)
2765 LOG(dout_con<<getDesc()<<": Receive: got event: "
2766 <<e.describe()<<std::endl);
2768 case CONNEVENT_NONE:
2769 throw NoIncomingDataException("No incoming data");
2770 case CONNEVENT_DATA_RECEIVED:
2771 peer_id = e.peer_id;
2772 data = SharedBuffer<u8>(e.data);
2773 return e.data.getSize();
2774 case CONNEVENT_PEER_ADDED: {
2775 UDPPeer tmp(e.peer_id, e.address, this);
2776 if(m_bc_peerhandler)
2777 m_bc_peerhandler->peerAdded(&tmp);
2779 case CONNEVENT_PEER_REMOVED: {
2780 UDPPeer tmp(e.peer_id, e.address, this);
2781 if(m_bc_peerhandler)
2782 m_bc_peerhandler->deletingPeer(&tmp, e.timeout);
2784 case CONNEVENT_BIND_FAILED:
2785 throw ConnectionBindFailed("Failed to bind socket "
2786 "(port already in use?)");
2789 throw NoIncomingDataException("No incoming data");
2792 void Connection::SendToAll(u8 channelnum, SharedBuffer<u8> data, bool reliable)
2794 assert(channelnum < CHANNEL_COUNT);
2796 ConnectionCommand c;
2797 c.sendToAll(channelnum, data, reliable);
2801 void Connection::Send(u16 peer_id, u8 channelnum,
2802 SharedBuffer<u8> data, bool reliable)
2804 assert(channelnum < CHANNEL_COUNT);
2806 ConnectionCommand c;
2807 c.send(peer_id, channelnum, data, reliable);
2811 void Connection::RunTimeouts(float dtime)
2816 Address Connection::GetPeerAddress(u16 peer_id)
2818 PeerHelper peer = getPeerNoEx(peer_id);
2821 throw PeerNotFoundException("No address for peer found!");
2822 Address peer_address;
2823 peer->getAddress(PRIMARY,peer_address);
2824 return peer_address;
2827 float Connection::GetPeerAvgRTT(u16 peer_id)
2829 PeerHelper peer = getPeerNoEx(peer_id);
2830 if (!peer) return -1;
2831 return peer->getStat(AVG_RTT);
2834 u16 Connection::createPeer(Address& sender, MTProtocols protocol, int fd)
2836 // Somebody wants to make a new connection
2838 // Get a unique peer id (2 or higher)
2839 u16 peer_id_new = 2;
2840 u16 overflow = MAX_UDP_PEERS;
2843 Find an unused peer id
2845 bool out_of_ids = false;
2849 if(m_peers.find(peer_id_new) == m_peers.end())
2851 // Check for overflow
2852 if(peer_id_new == overflow){
2859 errorstream<<getDesc()<<" ran out of peer ids"<<std::endl;
2860 return PEER_ID_INEXISTENT;
2863 LOG(dout_con<<getDesc()
2864 <<"createPeer(): giving peer_id="<<peer_id_new<<std::endl);
2869 peer = new UDPPeer(peer_id_new, sender, this);
2871 m_peers_mutex.Lock();
2872 m_peers[peer->id] = peer;
2873 m_peers_mutex.Unlock();
2875 // Create peer addition event
2877 e.peerAdded(peer_id_new, sender);
2880 ConnectionCommand cmd;
2881 SharedBuffer<u8> reply(4);
2882 writeU8(&reply[0], TYPE_CONTROL);
2883 writeU8(&reply[1], CONTROLTYPE_SET_PEER_ID);
2884 writeU16(&reply[2], peer_id_new);
2885 cmd.createPeer(peer_id_new,reply);
2886 this->putCommand(cmd);
2888 // We're now talking to a valid peer_id
2892 void Connection::DeletePeer(u16 peer_id)
2894 ConnectionCommand c;
2895 c.deletePeer(peer_id);
2899 void Connection::PrintInfo(std::ostream &out)
2901 m_info_mutex.Lock();
2902 out<<getDesc()<<": ";
2903 m_info_mutex.Unlock();
2906 void Connection::PrintInfo()
2908 PrintInfo(dout_con);
2911 const std::string Connection::getDesc()
2913 return std::string("con(")+itos(m_udpSocket.GetHandle())+"/"+itos(m_peer_id)+")";
2916 void Connection::sendAck(u16 peer_id, u8 channelnum, u16 seqnum) {
2918 assert(channelnum < CHANNEL_COUNT);
2920 LOG(dout_con<<getDesc()
2921 <<" Queuing ACK command to peer_id: " << peer_id <<
2922 " channel: " << (channelnum & 0xFF) <<
2923 " seqnum: " << seqnum << std::endl);
2925 ConnectionCommand c;
2926 SharedBuffer<u8> ack(4);
2927 writeU8(&ack[0], TYPE_CONTROL);
2928 writeU8(&ack[1], CONTROLTYPE_ACK);
2929 writeU16(&ack[2], seqnum);
2931 c.ack(peer_id, channelnum, ack);
2933 m_sendThread.Trigger();
2936 UDPPeer* Connection::createServerPeer(Address& address)
2938 if (getPeerNoEx(PEER_ID_SERVER) != 0)
2940 throw ConnectionException("Already connected to a server");
2943 UDPPeer *peer = new UDPPeer(PEER_ID_SERVER, address, this);
2946 JMutexAutoLock lock(m_peers_mutex);
2947 m_peers[peer->id] = peer;
2953 std::list<u16> Connection::getPeerIDs()
2955 std::list<u16> retval;
2957 JMutexAutoLock lock(m_peers_mutex);
2958 for(std::map<u16, Peer*>::iterator j = m_peers.begin();
2959 j != m_peers.end(); ++j)
2961 retval.push_back(j->first);