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"
23 #include "serialization.h"
26 #include "network/networkpacket.h"
27 #include "util/serialize.h"
28 #include "util/numeric.h"
29 #include "util/string.h"
36 /******************************************************************************/
37 /* defines used for debugging and profiling */
38 /******************************************************************************/
42 #undef DEBUG_CONNECTION_KBPS
44 /* this mutex is used to achieve log message consistency */
45 Mutex log_message_mutex;
48 MutexAutoLock loglock(log_message_mutex); \
52 //#define DEBUG_CONNECTION_KBPS
53 #undef DEBUG_CONNECTION_KBPS
57 static inline float CALC_DTIME(u64 lasttime, u64 curtime)
59 float value = ( curtime - lasttime) / 1000.0;
60 return MYMAX(MYMIN(value,0.1),0.0);
63 /* maximum window size to use, 0xFFFF is theoretical maximum don't think about
64 * touching it, the less you're away from it the more likely data corruption
67 #define MAX_RELIABLE_WINDOW_SIZE 0x8000
68 /* starting value for window size */
69 #define MIN_RELIABLE_WINDOW_SIZE 0x40
71 #define MAX_UDP_PEERS 65535
73 #define PING_TIMEOUT 5.0
75 /* maximum number of retries for reliable packets */
76 #define MAX_RELIABLE_RETRY 5
78 static u16 readPeerId(u8 *packetdata)
80 return readU16(&packetdata[4]);
82 static u8 readChannel(u8 *packetdata)
84 return readU8(&packetdata[6]);
87 BufferedPacket makePacket(Address &address, u8 *data, u32 datasize,
88 u32 protocol_id, u16 sender_peer_id, u8 channel)
90 u32 packet_size = datasize + BASE_HEADER_SIZE;
91 BufferedPacket p(packet_size);
94 writeU32(&p.data[0], protocol_id);
95 writeU16(&p.data[4], sender_peer_id);
96 writeU8(&p.data[6], channel);
98 memcpy(&p.data[BASE_HEADER_SIZE], data, datasize);
103 BufferedPacket makePacket(Address &address, SharedBuffer<u8> &data,
104 u32 protocol_id, u16 sender_peer_id, u8 channel)
106 return makePacket(address, *data, data.getSize(),
107 protocol_id, sender_peer_id, channel);
110 SharedBuffer<u8> makeOriginalPacket(
111 SharedBuffer<u8> data)
114 u32 packet_size = data.getSize() + header_size;
115 SharedBuffer<u8> b(packet_size);
117 writeU8(&(b[0]), TYPE_ORIGINAL);
118 if (data.getSize() > 0) {
119 memcpy(&(b[header_size]), *data, data.getSize());
124 std::list<SharedBuffer<u8> > makeSplitPacket(
125 SharedBuffer<u8> data,
129 // Chunk packets, containing the TYPE_SPLIT header
130 std::list<SharedBuffer<u8> > chunks;
132 u32 chunk_header_size = 7;
133 u32 maximum_data_size = chunksize_max - chunk_header_size;
139 end = start + maximum_data_size - 1;
140 if (end > data.getSize() - 1)
141 end = data.getSize() - 1;
143 u32 payload_size = end - start + 1;
144 u32 packet_size = chunk_header_size + payload_size;
146 SharedBuffer<u8> chunk(packet_size);
148 writeU8(&chunk[0], TYPE_SPLIT);
149 writeU16(&chunk[1], seqnum);
150 // [3] u16 chunk_count is written at next stage
151 writeU16(&chunk[5], chunk_num);
152 memcpy(&chunk[chunk_header_size], &data[start], payload_size);
154 chunks.push_back(chunk);
160 while(end != data.getSize() - 1);
162 for(std::list<SharedBuffer<u8> >::iterator i = chunks.begin();
163 i != chunks.end(); ++i)
166 writeU16(&((*i)[3]), chunk_count);
172 std::list<SharedBuffer<u8> > makeAutoSplitPacket(
173 SharedBuffer<u8> data,
177 u32 original_header_size = 1;
178 std::list<SharedBuffer<u8> > list;
179 if (data.getSize() + original_header_size > chunksize_max)
181 list = makeSplitPacket(data, chunksize_max, split_seqnum);
187 list.push_back(makeOriginalPacket(data));
192 SharedBuffer<u8> makeReliablePacket(
193 SharedBuffer<u8> data,
197 u32 packet_size = data.getSize() + header_size;
198 SharedBuffer<u8> b(packet_size);
200 writeU8(&b[0], TYPE_RELIABLE);
201 writeU16(&b[1], seqnum);
203 memcpy(&b[header_size], *data, data.getSize());
212 ReliablePacketBuffer::ReliablePacketBuffer(): m_list_size(0) {}
214 void ReliablePacketBuffer::print()
216 MutexAutoLock 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 MutexAutoLock 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 MutexAutoLock listlock(m_list_mutex);
266 BufferedPacket p = *m_list.begin();
267 result = readU16(&p.data[BASE_HEADER_SIZE+1]);
271 BufferedPacket ReliablePacketBuffer::popFirst()
273 MutexAutoLock 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 =
284 readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]);
288 BufferedPacket ReliablePacketBuffer::popSeqnum(u16 seqnum)
290 MutexAutoLock listlock(m_list_mutex);
291 RPBSearchResult r = findPacket(seqnum);
292 if (r == notFound()) {
293 LOG(dout_con<<"Sequence number: " << seqnum
294 << " not found in reliable buffer"<<std::endl);
295 throw NotFoundException("seqnum not found in buffer");
297 BufferedPacket p = *r;
300 RPBSearchResult next = r;
302 if (next != notFound()) {
303 u16 s = readU16(&(next->data[BASE_HEADER_SIZE+1]));
304 m_oldest_non_answered_ack = s;
310 if (m_list_size == 0)
311 { m_oldest_non_answered_ack = 0; }
313 { m_oldest_non_answered_ack = readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]); }
316 void ReliablePacketBuffer::insert(BufferedPacket &p,u16 next_expected)
318 MutexAutoLock listlock(m_list_mutex);
319 if (p.data.getSize() < BASE_HEADER_SIZE + 3) {
320 errorstream << "ReliablePacketBuffer::insert(): Invalid data size for "
321 "reliable packet" << std::endl;
324 u8 type = readU8(&p.data[BASE_HEADER_SIZE + 0]);
325 if (type != TYPE_RELIABLE) {
326 errorstream << "ReliablePacketBuffer::insert(): type is not reliable"
330 u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE + 1]);
332 if (!seqnum_in_window(seqnum, next_expected, MAX_RELIABLE_WINDOW_SIZE)) {
333 errorstream << "ReliablePacketBuffer::insert(): seqnum is outside of "
334 "expected window " << std::endl;
337 if (seqnum == next_expected) {
338 errorstream << "ReliablePacketBuffer::insert(): seqnum is next expected"
344 sanity_check(m_list_size <= SEQNUM_MAX+1); // FIXME: Handle the error?
346 // Find the right place for the packet and insert it there
347 // If list is empty, just add it
351 m_oldest_non_answered_ack = seqnum;
356 // Otherwise find the right place
357 std::list<BufferedPacket>::iterator i = m_list.begin();
358 // Find the first packet in the list which has a higher seqnum
359 u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
361 /* case seqnum is smaller then next_expected seqnum */
362 /* this is true e.g. on wrap around */
363 if (seqnum < next_expected) {
364 while(((s < seqnum) || (s >= next_expected)) && (i != m_list.end())) {
366 if (i != m_list.end())
367 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
370 /* non wrap around case (at least for incoming and next_expected */
373 while(((s < seqnum) && (s >= next_expected)) && (i != m_list.end())) {
375 if (i != m_list.end())
376 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
382 (readU16(&(i->data[BASE_HEADER_SIZE+1])) != seqnum) ||
383 (i->data.getSize() != p.data.getSize()) ||
384 (i->address != p.address)
387 /* if this happens your maximum transfer window may be to big */
389 "Duplicated seqnum %d non matching packet detected:\n",
391 fprintf(stderr, "Old: seqnum: %05d size: %04d, address: %s\n",
392 readU16(&(i->data[BASE_HEADER_SIZE+1])),i->data.getSize(),
393 i->address.serializeString().c_str());
394 fprintf(stderr, "New: seqnum: %05d size: %04u, address: %s\n",
395 readU16(&(p.data[BASE_HEADER_SIZE+1])),p.data.getSize(),
396 p.address.serializeString().c_str());
397 throw IncomingDataCorruption("duplicated packet isn't same as original one");
400 /* nothing to do this seems to be a resent packet */
401 /* for paranoia reason data should be compared */
404 /* insert or push back */
405 else if (i != m_list.end()) {
412 /* update last packet number */
413 m_oldest_non_answered_ack = readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]);
416 void ReliablePacketBuffer::incrementTimeouts(float dtime)
418 MutexAutoLock listlock(m_list_mutex);
419 for(std::list<BufferedPacket>::iterator i = m_list.begin();
420 i != m_list.end(); ++i)
423 i->totaltime += dtime;
427 std::list<BufferedPacket> ReliablePacketBuffer::getTimedOuts(float timeout,
428 unsigned int max_packets)
430 MutexAutoLock listlock(m_list_mutex);
431 std::list<BufferedPacket> timed_outs;
432 for(std::list<BufferedPacket>::iterator i = m_list.begin();
433 i != m_list.end(); ++i)
435 if (i->time >= timeout) {
436 timed_outs.push_back(*i);
438 //this packet will be sent right afterwards reset timeout here
440 if (timed_outs.size() >= max_packets)
451 IncomingSplitBuffer::~IncomingSplitBuffer()
453 MutexAutoLock listlock(m_map_mutex);
454 for(std::map<u16, IncomingSplitPacket*>::iterator i = m_buf.begin();
455 i != m_buf.end(); ++i)
461 This will throw a GotSplitPacketException when a full
462 split packet is constructed.
464 SharedBuffer<u8> IncomingSplitBuffer::insert(BufferedPacket &p, bool reliable)
466 MutexAutoLock listlock(m_map_mutex);
467 u32 headersize = BASE_HEADER_SIZE + 7;
468 if (p.data.getSize() < headersize) {
469 errorstream << "Invalid data size for split packet" << std::endl;
470 return SharedBuffer<u8>();
472 u8 type = readU8(&p.data[BASE_HEADER_SIZE+0]);
473 u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]);
474 u16 chunk_count = readU16(&p.data[BASE_HEADER_SIZE+3]);
475 u16 chunk_num = readU16(&p.data[BASE_HEADER_SIZE+5]);
477 if (type != TYPE_SPLIT) {
478 errorstream << "IncomingSplitBuffer::insert(): type is not split"
480 return SharedBuffer<u8>();
483 // Add if doesn't exist
484 if (m_buf.find(seqnum) == m_buf.end())
486 IncomingSplitPacket *sp = new IncomingSplitPacket();
487 sp->chunk_count = chunk_count;
488 sp->reliable = reliable;
492 IncomingSplitPacket *sp = m_buf[seqnum];
494 // TODO: These errors should be thrown or something? Dunno.
495 if (chunk_count != sp->chunk_count)
496 LOG(derr_con<<"Connection: WARNING: chunk_count="<<chunk_count
497 <<" != sp->chunk_count="<<sp->chunk_count
499 if (reliable != sp->reliable)
500 LOG(derr_con<<"Connection: WARNING: reliable="<<reliable
501 <<" != sp->reliable="<<sp->reliable
504 // If chunk already exists, ignore it.
505 // Sometimes two identical packets may arrive when there is network
506 // lag and the server re-sends stuff.
507 if (sp->chunks.find(chunk_num) != sp->chunks.end())
508 return SharedBuffer<u8>();
510 // Cut chunk data out of packet
511 u32 chunkdatasize = p.data.getSize() - headersize;
512 SharedBuffer<u8> chunkdata(chunkdatasize);
513 memcpy(*chunkdata, &(p.data[headersize]), chunkdatasize);
515 // Set chunk data in buffer
516 sp->chunks[chunk_num] = chunkdata;
518 // If not all chunks are received, return empty buffer
519 if (sp->allReceived() == false)
520 return SharedBuffer<u8>();
522 // Calculate total size
524 for(std::map<u16, SharedBuffer<u8> >::iterator i = sp->chunks.begin();
525 i != sp->chunks.end(); ++i)
527 totalsize += i->second.getSize();
530 SharedBuffer<u8> fulldata(totalsize);
532 // Copy chunks to data buffer
534 for(u32 chunk_i=0; chunk_i<sp->chunk_count;
537 SharedBuffer<u8> buf = sp->chunks[chunk_i];
538 u16 chunkdatasize = buf.getSize();
539 memcpy(&fulldata[start], *buf, chunkdatasize);
540 start += chunkdatasize;;
543 // Remove sp from buffer
549 void IncomingSplitBuffer::removeUnreliableTimedOuts(float dtime, float timeout)
551 std::list<u16> remove_queue;
553 MutexAutoLock listlock(m_map_mutex);
554 for(std::map<u16, IncomingSplitPacket*>::iterator i = m_buf.begin();
555 i != m_buf.end(); ++i)
557 IncomingSplitPacket *p = i->second;
558 // Reliable ones are not removed by timeout
559 if (p->reliable == true)
562 if (p->time >= timeout)
563 remove_queue.push_back(i->first);
566 for(std::list<u16>::iterator j = remove_queue.begin();
567 j != remove_queue.end(); ++j)
569 MutexAutoLock listlock(m_map_mutex);
570 LOG(dout_con<<"NOTE: Removing timed out unreliable split packet"<<std::endl);
581 window_size(MIN_RELIABLE_WINDOW_SIZE),
582 next_incoming_seqnum(SEQNUM_INITIAL),
583 next_outgoing_seqnum(SEQNUM_INITIAL),
584 next_outgoing_split_seqnum(SEQNUM_INITIAL),
585 current_packet_loss(0),
586 current_packet_too_late(0),
587 current_packet_successfull(0),
588 packet_loss_counter(0),
589 current_bytes_transfered(0),
590 current_bytes_received(0),
591 current_bytes_lost(0),
595 max_incoming_kbps(0.0),
596 cur_incoming_kbps(0.0),
597 avg_incoming_kbps(0.0),
610 u16 Channel::readNextIncomingSeqNum()
612 MutexAutoLock internal(m_internal_mutex);
613 return next_incoming_seqnum;
616 u16 Channel::incNextIncomingSeqNum()
618 MutexAutoLock internal(m_internal_mutex);
619 u16 retval = next_incoming_seqnum;
620 next_incoming_seqnum++;
624 u16 Channel::readNextSplitSeqNum()
626 MutexAutoLock internal(m_internal_mutex);
627 return next_outgoing_split_seqnum;
629 void Channel::setNextSplitSeqNum(u16 seqnum)
631 MutexAutoLock internal(m_internal_mutex);
632 next_outgoing_split_seqnum = seqnum;
635 u16 Channel::getOutgoingSequenceNumber(bool& successful)
637 MutexAutoLock internal(m_internal_mutex);
638 u16 retval = next_outgoing_seqnum;
639 u16 lowest_unacked_seqnumber;
641 /* shortcut if there ain't any packet in outgoing list */
642 if (outgoing_reliables_sent.empty())
644 next_outgoing_seqnum++;
648 if (outgoing_reliables_sent.getFirstSeqnum(lowest_unacked_seqnumber))
650 if (lowest_unacked_seqnumber < next_outgoing_seqnum) {
651 // ugly cast but this one is required in order to tell compiler we
652 // know about difference of two unsigned may be negative in general
653 // but we already made sure it won't happen in this case
654 if (((u16)(next_outgoing_seqnum - lowest_unacked_seqnumber)) > window_size) {
660 // ugly cast but this one is required in order to tell compiler we
661 // know about difference of two unsigned may be negative in general
662 // but we already made sure it won't happen in this case
663 if ((next_outgoing_seqnum + (u16)(SEQNUM_MAX - lowest_unacked_seqnumber)) >
671 next_outgoing_seqnum++;
675 u16 Channel::readOutgoingSequenceNumber()
677 MutexAutoLock internal(m_internal_mutex);
678 return next_outgoing_seqnum;
681 bool Channel::putBackSequenceNumber(u16 seqnum)
683 if (((seqnum + 1) % (SEQNUM_MAX+1)) == next_outgoing_seqnum) {
685 next_outgoing_seqnum = seqnum;
691 void Channel::UpdateBytesSent(unsigned int bytes, unsigned int packets)
693 MutexAutoLock internal(m_internal_mutex);
694 current_bytes_transfered += bytes;
695 current_packet_successfull += packets;
698 void Channel::UpdateBytesReceived(unsigned int bytes) {
699 MutexAutoLock internal(m_internal_mutex);
700 current_bytes_received += bytes;
703 void Channel::UpdateBytesLost(unsigned int bytes)
705 MutexAutoLock internal(m_internal_mutex);
706 current_bytes_lost += bytes;
710 void Channel::UpdatePacketLossCounter(unsigned int count)
712 MutexAutoLock internal(m_internal_mutex);
713 current_packet_loss += count;
716 void Channel::UpdatePacketTooLateCounter()
718 MutexAutoLock internal(m_internal_mutex);
719 current_packet_too_late++;
722 void Channel::UpdateTimers(float dtime,bool legacy_peer)
724 bpm_counter += dtime;
725 packet_loss_counter += dtime;
727 if (packet_loss_counter > 1.0)
729 packet_loss_counter -= 1.0;
731 unsigned int packet_loss = 11; /* use a neutral value for initialization */
732 unsigned int packets_successfull = 0;
733 //unsigned int packet_too_late = 0;
735 bool reasonable_amount_of_data_transmitted = false;
738 MutexAutoLock internal(m_internal_mutex);
739 packet_loss = current_packet_loss;
740 //packet_too_late = current_packet_too_late;
741 packets_successfull = current_packet_successfull;
743 if (current_bytes_transfered > (unsigned int) (window_size*512/2))
745 reasonable_amount_of_data_transmitted = true;
747 current_packet_loss = 0;
748 current_packet_too_late = 0;
749 current_packet_successfull = 0;
752 /* dynamic window size is only available for non legacy peers */
754 float successfull_to_lost_ratio = 0.0;
757 if (packets_successfull > 0) {
758 successfull_to_lost_ratio = packet_loss/packets_successfull;
760 else if (packet_loss > 0)
764 MIN_RELIABLE_WINDOW_SIZE);
770 if ((successfull_to_lost_ratio < 0.01) &&
771 (window_size < MAX_RELIABLE_WINDOW_SIZE))
773 /* don't even think about increasing if we didn't even
774 * use major parts of our window */
775 if (reasonable_amount_of_data_transmitted)
778 MAX_RELIABLE_WINDOW_SIZE);
780 else if ((successfull_to_lost_ratio < 0.05) &&
781 (window_size < MAX_RELIABLE_WINDOW_SIZE))
783 /* don't even think about increasing if we didn't even
784 * use major parts of our window */
785 if (reasonable_amount_of_data_transmitted)
788 MAX_RELIABLE_WINDOW_SIZE);
790 else if (successfull_to_lost_ratio > 0.15)
794 MIN_RELIABLE_WINDOW_SIZE);
796 else if (successfull_to_lost_ratio > 0.1)
800 MIN_RELIABLE_WINDOW_SIZE);
806 if (bpm_counter > 10.0)
809 MutexAutoLock internal(m_internal_mutex);
811 (((float) current_bytes_transfered)/bpm_counter)/1024.0;
812 current_bytes_transfered = 0;
814 (((float) current_bytes_lost)/bpm_counter)/1024.0;
815 current_bytes_lost = 0;
817 (((float) current_bytes_received)/bpm_counter)/1024.0;
818 current_bytes_received = 0;
822 if (cur_kbps > max_kbps)
827 if (cur_kbps_lost > max_kbps_lost)
829 max_kbps_lost = cur_kbps_lost;
832 if (cur_incoming_kbps > max_incoming_kbps) {
833 max_incoming_kbps = cur_incoming_kbps;
836 rate_samples = MYMIN(rate_samples+1,10);
837 float old_fraction = ((float) (rate_samples-1) )/( (float) rate_samples);
838 avg_kbps = avg_kbps * old_fraction +
839 cur_kbps * (1.0 - old_fraction);
840 avg_kbps_lost = avg_kbps_lost * old_fraction +
841 cur_kbps_lost * (1.0 - old_fraction);
842 avg_incoming_kbps = avg_incoming_kbps * old_fraction +
843 cur_incoming_kbps * (1.0 - old_fraction);
852 PeerHelper::PeerHelper() :
856 PeerHelper::PeerHelper(Peer* peer) :
861 if (!peer->IncUseCount())
868 PeerHelper::~PeerHelper()
871 m_peer->DecUseCount();
876 PeerHelper& PeerHelper::operator=(Peer* peer)
881 if (!peer->IncUseCount())
889 Peer* PeerHelper::operator->() const
894 Peer* PeerHelper::operator&() const
899 bool PeerHelper::operator!() {
903 bool PeerHelper::operator!=(void* ptr)
905 return ((void*) m_peer != ptr);
908 bool Peer::IncUseCount()
910 MutexAutoLock lock(m_exclusive_access_mutex);
912 if (!m_pending_deletion)
921 void Peer::DecUseCount()
924 MutexAutoLock lock(m_exclusive_access_mutex);
925 sanity_check(m_usage > 0);
928 if (!((m_pending_deletion) && (m_usage == 0)))
934 void Peer::RTTStatistics(float rtt, const std::string &profiler_id,
935 unsigned int num_samples) {
937 if (m_last_rtt > 0) {
938 /* set min max values */
939 if (rtt < m_rtt.min_rtt)
941 if (rtt >= m_rtt.max_rtt)
944 /* do average calculation */
945 if (m_rtt.avg_rtt < 0.0)
948 m_rtt.avg_rtt = m_rtt.avg_rtt * (num_samples/(num_samples-1)) +
949 rtt * (1/num_samples);
951 /* do jitter calculation */
953 //just use some neutral value at beginning
954 float jitter = m_rtt.jitter_min;
956 if (rtt > m_last_rtt)
957 jitter = rtt-m_last_rtt;
959 if (rtt <= m_last_rtt)
960 jitter = m_last_rtt - rtt;
962 if (jitter < m_rtt.jitter_min)
963 m_rtt.jitter_min = jitter;
964 if (jitter >= m_rtt.jitter_max)
965 m_rtt.jitter_max = jitter;
967 if (m_rtt.jitter_avg < 0.0)
968 m_rtt.jitter_avg = jitter;
970 m_rtt.jitter_avg = m_rtt.jitter_avg * (num_samples/(num_samples-1)) +
971 jitter * (1/num_samples);
973 if (profiler_id != "") {
974 g_profiler->graphAdd(profiler_id + "_rtt", rtt);
975 g_profiler->graphAdd(profiler_id + "_jitter", jitter);
978 /* save values required for next loop */
982 bool Peer::isTimedOut(float timeout)
984 MutexAutoLock lock(m_exclusive_access_mutex);
985 u64 current_time = porting::getTimeMs();
987 float dtime = CALC_DTIME(m_last_timeout_check,current_time);
988 m_last_timeout_check = current_time;
990 m_timeout_counter += dtime;
992 return m_timeout_counter > timeout;
998 MutexAutoLock usage_lock(m_exclusive_access_mutex);
999 m_pending_deletion = true;
1004 PROFILE(std::stringstream peerIdentifier1);
1005 PROFILE(peerIdentifier1 << "runTimeouts[" << m_connection->getDesc()
1006 << ";" << id << ";RELIABLE]");
1007 PROFILE(g_profiler->remove(peerIdentifier1.str()));
1008 PROFILE(std::stringstream peerIdentifier2);
1009 PROFILE(peerIdentifier2 << "sendPackets[" << m_connection->getDesc()
1010 << ";" << id << ";RELIABLE]");
1011 PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier2.str(), SPT_AVG));
1016 UDPPeer::UDPPeer(u16 a_id, Address a_address, Connection* connection) :
1017 Peer(a_address,a_id,connection),
1018 m_pending_disconnect(false),
1019 resend_timeout(0.5),
1024 bool UDPPeer::getAddress(MTProtocols type,Address& toset)
1026 if ((type == MTP_UDP) || (type == MTP_MINETEST_RELIABLE_UDP) || (type == MTP_PRIMARY))
1035 void UDPPeer::setNonLegacyPeer()
1037 m_legacy_peer = false;
1038 for(unsigned int i=0; i< CHANNEL_COUNT; i++)
1040 channels->setWindowSize(g_settings->getU16("max_packets_per_iteration"));
1044 void UDPPeer::reportRTT(float rtt)
1049 RTTStatistics(rtt,"rudp",MAX_RELIABLE_WINDOW_SIZE*10);
1051 float timeout = getStat(AVG_RTT) * RESEND_TIMEOUT_FACTOR;
1052 if (timeout < RESEND_TIMEOUT_MIN)
1053 timeout = RESEND_TIMEOUT_MIN;
1054 if (timeout > RESEND_TIMEOUT_MAX)
1055 timeout = RESEND_TIMEOUT_MAX;
1057 MutexAutoLock usage_lock(m_exclusive_access_mutex);
1058 resend_timeout = timeout;
1061 bool UDPPeer::Ping(float dtime,SharedBuffer<u8>& data)
1063 m_ping_timer += dtime;
1064 if (m_ping_timer >= PING_TIMEOUT)
1066 // Create and send PING packet
1067 writeU8(&data[0], TYPE_CONTROL);
1068 writeU8(&data[1], CONTROLTYPE_PING);
1075 void UDPPeer::PutReliableSendCommand(ConnectionCommand &c,
1076 unsigned int max_packet_size)
1078 if (m_pending_disconnect)
1081 if ( channels[c.channelnum].queued_commands.empty() &&
1082 /* don't queue more packets then window size */
1083 (channels[c.channelnum].queued_reliables.size()
1084 < (channels[c.channelnum].getWindowSize()/2))) {
1085 LOG(dout_con<<m_connection->getDesc()
1086 <<" processing reliable command for peer id: " << c.peer_id
1087 <<" data size: " << c.data.getSize() << std::endl);
1088 if (!processReliableSendCommand(c,max_packet_size)) {
1089 channels[c.channelnum].queued_commands.push_back(c);
1093 LOG(dout_con<<m_connection->getDesc()
1094 <<" Queueing reliable command for peer id: " << c.peer_id
1095 <<" data size: " << c.data.getSize() <<std::endl);
1096 channels[c.channelnum].queued_commands.push_back(c);
1100 bool UDPPeer::processReliableSendCommand(
1101 ConnectionCommand &c,
1102 unsigned int max_packet_size)
1104 if (m_pending_disconnect)
1107 u32 chunksize_max = max_packet_size
1109 - RELIABLE_HEADER_SIZE;
1111 sanity_check(c.data.getSize() < MAX_RELIABLE_WINDOW_SIZE*512);
1113 std::list<SharedBuffer<u8> > originals;
1114 u16 split_sequence_number = channels[c.channelnum].readNextSplitSeqNum();
1118 originals.push_back(c.data);
1121 originals = makeAutoSplitPacket(c.data, chunksize_max,split_sequence_number);
1122 channels[c.channelnum].setNextSplitSeqNum(split_sequence_number);
1125 bool have_sequence_number = true;
1126 bool have_initial_sequence_number = false;
1127 std::queue<BufferedPacket> toadd;
1128 volatile u16 initial_sequence_number = 0;
1130 for(std::list<SharedBuffer<u8> >::iterator i = originals.begin();
1131 i != originals.end(); ++i)
1133 u16 seqnum = channels[c.channelnum].getOutgoingSequenceNumber(have_sequence_number);
1135 /* oops, we don't have enough sequence numbers to send this packet */
1136 if (!have_sequence_number)
1139 if (!have_initial_sequence_number)
1141 initial_sequence_number = seqnum;
1142 have_initial_sequence_number = true;
1145 SharedBuffer<u8> reliable = makeReliablePacket(*i, seqnum);
1147 // Add base headers and make a packet
1148 BufferedPacket p = con::makePacket(address, reliable,
1149 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1155 if (have_sequence_number) {
1156 volatile u16 pcount = 0;
1157 while(toadd.size() > 0) {
1158 BufferedPacket p = toadd.front();
1160 // LOG(dout_con<<connection->getDesc()
1161 // << " queuing reliable packet for peer_id: " << c.peer_id
1162 // << " channel: " << (c.channelnum&0xFF)
1163 // << " seqnum: " << readU16(&p.data[BASE_HEADER_SIZE+1])
1165 channels[c.channelnum].queued_reliables.push(p);
1168 sanity_check(channels[c.channelnum].queued_reliables.size() < 0xFFFF);
1172 volatile u16 packets_available = toadd.size();
1173 /* we didn't get a single sequence number no need to fill queue */
1174 if (!have_initial_sequence_number)
1178 while(toadd.size() > 0) {
1182 bool successfully_put_back_sequence_number
1183 = channels[c.channelnum].putBackSequenceNumber(
1184 (initial_sequence_number+toadd.size() % (SEQNUM_MAX+1)));
1186 FATAL_ERROR_IF(!successfully_put_back_sequence_number, "error");
1188 LOG(dout_con<<m_connection->getDesc()
1189 << " Windowsize exceeded on reliable sending "
1190 << c.data.getSize() << " bytes"
1191 << std::endl << "\t\tinitial_sequence_number: "
1192 << initial_sequence_number
1193 << std::endl << "\t\tgot at most : "
1194 << packets_available << " packets"
1195 << std::endl << "\t\tpackets queued : "
1196 << channels[c.channelnum].outgoing_reliables_sent.size()
1202 void UDPPeer::RunCommandQueues(
1203 unsigned int max_packet_size,
1204 unsigned int maxcommands,
1205 unsigned int maxtransfer)
1208 for (unsigned int i = 0; i < CHANNEL_COUNT; i++) {
1209 unsigned int commands_processed = 0;
1211 if ((channels[i].queued_commands.size() > 0) &&
1212 (channels[i].queued_reliables.size() < maxtransfer) &&
1213 (commands_processed < maxcommands)) {
1215 ConnectionCommand c = channels[i].queued_commands.front();
1217 LOG(dout_con << m_connection->getDesc()
1218 << " processing queued reliable command " << std::endl);
1220 // Packet is processed, remove it from queue
1221 if (processReliableSendCommand(c,max_packet_size)) {
1222 channels[i].queued_commands.pop_front();
1224 LOG(dout_con << m_connection->getDesc()
1225 << " Failed to queue packets for peer_id: " << c.peer_id
1226 << ", delaying sending of " << c.data.getSize()
1227 << " bytes" << std::endl);
1230 catch (ItemNotFoundException &e) {
1231 // intentionally empty
1237 u16 UDPPeer::getNextSplitSequenceNumber(u8 channel)
1239 assert(channel < CHANNEL_COUNT); // Pre-condition
1240 return channels[channel].readNextSplitSeqNum();
1243 void UDPPeer::setNextSplitSequenceNumber(u8 channel, u16 seqnum)
1245 assert(channel < CHANNEL_COUNT); // Pre-condition
1246 channels[channel].setNextSplitSeqNum(seqnum);
1249 SharedBuffer<u8> UDPPeer::addSpiltPacket(u8 channel,
1250 BufferedPacket toadd,
1253 assert(channel < CHANNEL_COUNT); // Pre-condition
1254 return channels[channel].incoming_splits.insert(toadd,reliable);
1257 /******************************************************************************/
1258 /* Connection Threads */
1259 /******************************************************************************/
1261 ConnectionSendThread::ConnectionSendThread(unsigned int max_packet_size,
1263 Thread("ConnectionSend"),
1265 m_max_packet_size(max_packet_size),
1267 m_max_commands_per_iteration(1),
1268 m_max_data_packets_per_iteration(g_settings->getU16("max_packets_per_iteration")),
1269 m_max_packets_requeued(256)
1273 void * ConnectionSendThread::run()
1275 assert(m_connection);
1277 LOG(dout_con<<m_connection->getDesc()
1278 <<"ConnectionSend thread started"<<std::endl);
1280 u64 curtime = porting::getTimeMs();
1281 u64 lasttime = curtime;
1283 PROFILE(std::stringstream ThreadIdentifier);
1284 PROFILE(ThreadIdentifier << "ConnectionSend: [" << m_connection->getDesc() << "]");
1286 /* if stop is requested don't stop immediately but try to send all */
1288 while(!stopRequested() || packetsQueued()) {
1289 BEGIN_DEBUG_EXCEPTION_HANDLER
1290 PROFILE(ScopeProfiler sp(g_profiler, ThreadIdentifier.str(), SPT_AVG));
1292 m_iteration_packets_avaialble = m_max_data_packets_per_iteration;
1294 /* wait for trigger or timeout */
1295 m_send_sleep_semaphore.wait(50);
1297 /* remove all triggers */
1298 while(m_send_sleep_semaphore.wait(0)) {}
1301 curtime = porting::getTimeMs();
1302 float dtime = CALC_DTIME(lasttime,curtime);
1304 /* first do all the reliable stuff */
1307 /* translate commands to packets */
1308 ConnectionCommand c = m_connection->m_command_queue.pop_frontNoEx(0);
1309 while(c.type != CONNCMD_NONE)
1312 processReliableCommand(c);
1314 processNonReliableCommand(c);
1316 c = m_connection->m_command_queue.pop_frontNoEx(0);
1319 /* send non reliable packets */
1322 END_DEBUG_EXCEPTION_HANDLER
1325 PROFILE(g_profiler->remove(ThreadIdentifier.str()));
1329 void ConnectionSendThread::Trigger()
1331 m_send_sleep_semaphore.post();
1334 bool ConnectionSendThread::packetsQueued()
1336 std::list<u16> peerIds = m_connection->getPeerIDs();
1338 if (!m_outgoing_queue.empty() && !peerIds.empty())
1341 for(std::list<u16>::iterator j = peerIds.begin();
1342 j != peerIds.end(); ++j)
1344 PeerHelper peer = m_connection->getPeerNoEx(*j);
1349 if (dynamic_cast<UDPPeer*>(&peer) == 0)
1352 for(u16 i=0; i < CHANNEL_COUNT; i++) {
1353 Channel *channel = &(dynamic_cast<UDPPeer*>(&peer))->channels[i];
1355 if (channel->queued_commands.size() > 0) {
1365 void ConnectionSendThread::runTimeouts(float dtime)
1367 std::list<u16> timeouted_peers;
1368 std::list<u16> peerIds = m_connection->getPeerIDs();
1370 for(std::list<u16>::iterator j = peerIds.begin();
1371 j != peerIds.end(); ++j)
1373 PeerHelper peer = m_connection->getPeerNoEx(*j);
1378 if (dynamic_cast<UDPPeer*>(&peer) == 0)
1381 PROFILE(std::stringstream peerIdentifier);
1382 PROFILE(peerIdentifier << "runTimeouts[" << m_connection->getDesc()
1383 << ";" << *j << ";RELIABLE]");
1384 PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier.str(), SPT_AVG));
1386 SharedBuffer<u8> data(2); // data for sending ping, required here because of goto
1391 if (peer->isTimedOut(m_timeout))
1393 infostream<<m_connection->getDesc()
1394 <<"RunTimeouts(): Peer "<<peer->id
1396 <<" (source=peer->timeout_counter)"
1398 // Add peer to the list
1399 timeouted_peers.push_back(peer->id);
1400 // Don't bother going through the buffers of this one
1404 float resend_timeout = dynamic_cast<UDPPeer*>(&peer)->getResendTimeout();
1405 bool retry_count_exceeded = false;
1406 for(u16 i=0; i<CHANNEL_COUNT; i++)
1408 std::list<BufferedPacket> timed_outs;
1409 Channel *channel = &(dynamic_cast<UDPPeer*>(&peer))->channels[i];
1411 if (dynamic_cast<UDPPeer*>(&peer)->getLegacyPeer())
1412 channel->setWindowSize(g_settings->getU16("workaround_window_size"));
1414 // Remove timed out incomplete unreliable split packets
1415 channel->incoming_splits.removeUnreliableTimedOuts(dtime, m_timeout);
1417 // Increment reliable packet times
1418 channel->outgoing_reliables_sent.incrementTimeouts(dtime);
1420 unsigned int numpeers = m_connection->m_peers.size();
1425 // Re-send timed out outgoing reliables
1426 timed_outs = channel->
1427 outgoing_reliables_sent.getTimedOuts(resend_timeout,
1428 (m_max_data_packets_per_iteration/numpeers));
1430 channel->UpdatePacketLossCounter(timed_outs.size());
1431 g_profiler->graphAdd("packets_lost", timed_outs.size());
1433 m_iteration_packets_avaialble -= timed_outs.size();
1435 for(std::list<BufferedPacket>::iterator k = timed_outs.begin();
1436 k != timed_outs.end(); ++k)
1438 u16 peer_id = readPeerId(*(k->data));
1439 u8 channelnum = readChannel(*(k->data));
1440 u16 seqnum = readU16(&(k->data[BASE_HEADER_SIZE+1]));
1442 channel->UpdateBytesLost(k->data.getSize());
1445 if (k-> resend_count > MAX_RELIABLE_RETRY) {
1446 retry_count_exceeded = true;
1447 timeouted_peers.push_back(peer->id);
1448 /* no need to check additional packets if a single one did timeout*/
1452 LOG(derr_con<<m_connection->getDesc()
1453 <<"RE-SENDING timed-out RELIABLE to "
1454 << k->address.serializeString()
1455 << "(t/o="<<resend_timeout<<"): "
1456 <<"from_peer_id="<<peer_id
1457 <<", channel="<<((int)channelnum&0xff)
1458 <<", seqnum="<<seqnum
1463 // do not handle rtt here as we can't decide if this packet was
1464 // lost or really takes more time to transmit
1467 if (retry_count_exceeded) {
1468 break; /* no need to check other channels if we already did timeout */
1471 channel->UpdateTimers(dtime,dynamic_cast<UDPPeer*>(&peer)->getLegacyPeer());
1474 /* skip to next peer if we did timeout */
1475 if (retry_count_exceeded)
1478 /* send ping if necessary */
1479 if (dynamic_cast<UDPPeer*>(&peer)->Ping(dtime,data)) {
1480 LOG(dout_con<<m_connection->getDesc()
1481 <<"Sending ping for peer_id: "
1482 << dynamic_cast<UDPPeer*>(&peer)->id <<std::endl);
1483 /* this may fail if there ain't a sequence number left */
1484 if (!rawSendAsPacket(dynamic_cast<UDPPeer*>(&peer)->id, 0, data, true))
1486 //retrigger with reduced ping interval
1487 dynamic_cast<UDPPeer*>(&peer)->Ping(4.0,data);
1491 dynamic_cast<UDPPeer*>(&peer)->RunCommandQueues(m_max_packet_size,
1492 m_max_commands_per_iteration,
1493 m_max_packets_requeued);
1496 // Remove timed out peers
1497 for(std::list<u16>::iterator i = timeouted_peers.begin();
1498 i != timeouted_peers.end(); ++i)
1500 LOG(derr_con<<m_connection->getDesc()
1501 <<"RunTimeouts(): Removing peer "<<(*i)<<std::endl);
1502 m_connection->deletePeer(*i, true);
1506 void ConnectionSendThread::rawSend(const BufferedPacket &packet)
1509 m_connection->m_udpSocket.Send(packet.address, *packet.data,
1510 packet.data.getSize());
1511 LOG(dout_con <<m_connection->getDesc()
1512 << " rawSend: " << packet.data.getSize()
1513 << " bytes sent" << std::endl);
1514 } catch(SendFailedException &e) {
1515 LOG(derr_con<<m_connection->getDesc()
1516 <<"Connection::rawSend(): SendFailedException: "
1517 <<packet.address.serializeString()<<std::endl);
1521 void ConnectionSendThread::sendAsPacketReliable(BufferedPacket& p, Channel* channel)
1524 p.absolute_send_time = porting::getTimeMs();
1525 // Buffer the packet
1526 channel->outgoing_reliables_sent.insert(p,
1527 (channel->readOutgoingSequenceNumber() - MAX_RELIABLE_WINDOW_SIZE)
1528 % (MAX_RELIABLE_WINDOW_SIZE+1));
1530 catch(AlreadyExistsException &e)
1532 LOG(derr_con<<m_connection->getDesc()
1533 <<"WARNING: Going to send a reliable packet"
1534 <<" in outgoing buffer" <<std::endl);
1541 bool ConnectionSendThread::rawSendAsPacket(u16 peer_id, u8 channelnum,
1542 SharedBuffer<u8> data, bool reliable)
1544 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
1546 LOG(dout_con<<m_connection->getDesc()
1547 <<" INFO: dropped packet for non existent peer_id: "
1548 << peer_id << std::endl);
1549 FATAL_ERROR_IF(!reliable, "Trying to send raw packet reliable but no peer found!");
1552 Channel *channel = &(dynamic_cast<UDPPeer*>(&peer)->channels[channelnum]);
1556 bool have_sequence_number_for_raw_packet = true;
1558 channel->getOutgoingSequenceNumber(have_sequence_number_for_raw_packet);
1560 if (!have_sequence_number_for_raw_packet)
1563 SharedBuffer<u8> reliable = makeReliablePacket(data, seqnum);
1564 Address peer_address;
1565 peer->getAddress(MTP_MINETEST_RELIABLE_UDP, peer_address);
1567 // Add base headers and make a packet
1568 BufferedPacket p = con::makePacket(peer_address, reliable,
1569 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1572 // first check if our send window is already maxed out
1573 if (channel->outgoing_reliables_sent.size()
1574 < channel->getWindowSize()) {
1575 LOG(dout_con<<m_connection->getDesc()
1576 <<" INFO: sending a reliable packet to peer_id " << peer_id
1577 <<" channel: " << channelnum
1578 <<" seqnum: " << seqnum << std::endl);
1579 sendAsPacketReliable(p,channel);
1583 LOG(dout_con<<m_connection->getDesc()
1584 <<" INFO: queueing reliable packet for peer_id: " << peer_id
1585 <<" channel: " << channelnum
1586 <<" seqnum: " << seqnum << std::endl);
1587 channel->queued_reliables.push(p);
1593 Address peer_address;
1595 if (peer->getAddress(MTP_UDP, peer_address))
1597 // Add base headers and make a packet
1598 BufferedPacket p = con::makePacket(peer_address, data,
1599 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1607 LOG(dout_con<<m_connection->getDesc()
1608 <<" INFO: dropped unreliable packet for peer_id: " << peer_id
1609 <<" because of (yet) missing udp address" << std::endl);
1618 void ConnectionSendThread::processReliableCommand(ConnectionCommand &c)
1620 assert(c.reliable); // Pre-condition
1624 LOG(dout_con<<m_connection->getDesc()
1625 <<"UDP processing reliable CONNCMD_NONE"<<std::endl);
1629 LOG(dout_con<<m_connection->getDesc()
1630 <<"UDP processing reliable CONNCMD_SEND"<<std::endl);
1634 case CONNCMD_SEND_TO_ALL:
1635 LOG(dout_con<<m_connection->getDesc()
1636 <<"UDP processing CONNCMD_SEND_TO_ALL"<<std::endl);
1637 sendToAllReliable(c);
1640 case CONCMD_CREATE_PEER:
1641 LOG(dout_con<<m_connection->getDesc()
1642 <<"UDP processing reliable CONCMD_CREATE_PEER"<<std::endl);
1643 if (!rawSendAsPacket(c.peer_id,c.channelnum,c.data,c.reliable))
1645 /* put to queue if we couldn't send it immediately */
1650 case CONCMD_DISABLE_LEGACY:
1651 LOG(dout_con<<m_connection->getDesc()
1652 <<"UDP processing reliable CONCMD_DISABLE_LEGACY"<<std::endl);
1653 if (!rawSendAsPacket(c.peer_id,c.channelnum,c.data,c.reliable))
1655 /* put to queue if we couldn't send it immediately */
1661 case CONNCMD_CONNECT:
1662 case CONNCMD_DISCONNECT:
1664 FATAL_ERROR("Got command that shouldn't be reliable as reliable command");
1666 LOG(dout_con<<m_connection->getDesc()
1667 <<" Invalid reliable command type: " << c.type <<std::endl);
1672 void ConnectionSendThread::processNonReliableCommand(ConnectionCommand &c)
1674 assert(!c.reliable); // Pre-condition
1678 LOG(dout_con<<m_connection->getDesc()
1679 <<" UDP processing CONNCMD_NONE"<<std::endl);
1682 LOG(dout_con<<m_connection->getDesc()
1683 <<" UDP processing CONNCMD_SERVE port="
1684 <<c.address.serializeString()<<std::endl);
1687 case CONNCMD_CONNECT:
1688 LOG(dout_con<<m_connection->getDesc()
1689 <<" UDP processing CONNCMD_CONNECT"<<std::endl);
1692 case CONNCMD_DISCONNECT:
1693 LOG(dout_con<<m_connection->getDesc()
1694 <<" UDP processing CONNCMD_DISCONNECT"<<std::endl);
1697 case CONNCMD_DISCONNECT_PEER:
1698 LOG(dout_con<<m_connection->getDesc()
1699 <<" UDP processing CONNCMD_DISCONNECT_PEER"<<std::endl);
1700 disconnect_peer(c.peer_id);
1703 LOG(dout_con<<m_connection->getDesc()
1704 <<" UDP processing CONNCMD_SEND"<<std::endl);
1705 send(c.peer_id, c.channelnum, c.data);
1707 case CONNCMD_SEND_TO_ALL:
1708 LOG(dout_con<<m_connection->getDesc()
1709 <<" UDP processing CONNCMD_SEND_TO_ALL"<<std::endl);
1710 sendToAll(c.channelnum, c.data);
1713 LOG(dout_con<<m_connection->getDesc()
1714 <<" UDP processing CONCMD_ACK"<<std::endl);
1715 sendAsPacket(c.peer_id,c.channelnum,c.data,true);
1717 case CONCMD_CREATE_PEER:
1718 FATAL_ERROR("Got command that should be reliable as unreliable command");
1720 LOG(dout_con<<m_connection->getDesc()
1721 <<" Invalid command type: " << c.type <<std::endl);
1725 void ConnectionSendThread::serve(Address bind_address)
1727 LOG(dout_con<<m_connection->getDesc()
1728 <<"UDP serving at port " << bind_address.serializeString() <<std::endl);
1730 m_connection->m_udpSocket.Bind(bind_address);
1731 m_connection->SetPeerID(PEER_ID_SERVER);
1733 catch(SocketException &e) {
1737 m_connection->putEvent(ce);
1741 void ConnectionSendThread::connect(Address address)
1743 LOG(dout_con<<m_connection->getDesc()<<" connecting to "<<address.serializeString()
1744 <<":"<<address.getPort()<<std::endl);
1746 UDPPeer *peer = m_connection->createServerPeer(address);
1750 e.peerAdded(peer->id, peer->address);
1751 m_connection->putEvent(e);
1755 if (address.isIPv6())
1756 bind_addr.setAddress((IPv6AddressBytes*) NULL);
1758 bind_addr.setAddress(0,0,0,0);
1760 m_connection->m_udpSocket.Bind(bind_addr);
1762 // Send a dummy packet to server with peer_id = PEER_ID_INEXISTENT
1763 m_connection->SetPeerID(PEER_ID_INEXISTENT);
1764 NetworkPacket pkt(0,0);
1765 m_connection->Send(PEER_ID_SERVER, 0, &pkt, true);
1768 void ConnectionSendThread::disconnect()
1770 LOG(dout_con<<m_connection->getDesc()<<" disconnecting"<<std::endl);
1772 // Create and send DISCO packet
1773 SharedBuffer<u8> data(2);
1774 writeU8(&data[0], TYPE_CONTROL);
1775 writeU8(&data[1], CONTROLTYPE_DISCO);
1779 std::list<u16> peerids = m_connection->getPeerIDs();
1781 for (std::list<u16>::iterator i = peerids.begin();
1785 sendAsPacket(*i, 0,data,false);
1789 void ConnectionSendThread::disconnect_peer(u16 peer_id)
1791 LOG(dout_con<<m_connection->getDesc()<<" disconnecting peer"<<std::endl);
1793 // Create and send DISCO packet
1794 SharedBuffer<u8> data(2);
1795 writeU8(&data[0], TYPE_CONTROL);
1796 writeU8(&data[1], CONTROLTYPE_DISCO);
1797 sendAsPacket(peer_id, 0,data,false);
1799 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
1804 if (dynamic_cast<UDPPeer*>(&peer) == 0)
1809 dynamic_cast<UDPPeer*>(&peer)->m_pending_disconnect = true;
1812 void ConnectionSendThread::send(u16 peer_id, u8 channelnum,
1813 SharedBuffer<u8> data)
1815 assert(channelnum < CHANNEL_COUNT); // Pre-condition
1817 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
1820 LOG(dout_con<<m_connection->getDesc()<<" peer: peer_id="<<peer_id
1821 << ">>>NOT<<< found on sending packet"
1822 << ", channel " << (channelnum % 0xFF)
1823 << ", size: " << data.getSize() <<std::endl);
1827 LOG(dout_con<<m_connection->getDesc()<<" sending to peer_id="<<peer_id
1828 << ", channel " << (channelnum % 0xFF)
1829 << ", size: " << data.getSize() <<std::endl);
1831 u16 split_sequence_number = peer->getNextSplitSequenceNumber(channelnum);
1833 u32 chunksize_max = m_max_packet_size - BASE_HEADER_SIZE;
1834 std::list<SharedBuffer<u8> > originals;
1836 originals = makeAutoSplitPacket(data, chunksize_max,split_sequence_number);
1838 peer->setNextSplitSequenceNumber(channelnum,split_sequence_number);
1840 for(std::list<SharedBuffer<u8> >::iterator i = originals.begin();
1841 i != originals.end(); ++i)
1843 SharedBuffer<u8> original = *i;
1844 sendAsPacket(peer_id, channelnum, original);
1848 void ConnectionSendThread::sendReliable(ConnectionCommand &c)
1850 PeerHelper peer = m_connection->getPeerNoEx(c.peer_id);
1854 peer->PutReliableSendCommand(c,m_max_packet_size);
1857 void ConnectionSendThread::sendToAll(u8 channelnum, SharedBuffer<u8> data)
1859 std::list<u16> peerids = m_connection->getPeerIDs();
1861 for (std::list<u16>::iterator i = peerids.begin();
1865 send(*i, channelnum, data);
1869 void ConnectionSendThread::sendToAllReliable(ConnectionCommand &c)
1871 std::list<u16> peerids = m_connection->getPeerIDs();
1873 for (std::list<u16>::iterator i = peerids.begin();
1877 PeerHelper peer = m_connection->getPeerNoEx(*i);
1882 peer->PutReliableSendCommand(c,m_max_packet_size);
1886 void ConnectionSendThread::sendPackets(float dtime)
1888 std::list<u16> peerIds = m_connection->getPeerIDs();
1889 std::list<u16> pendingDisconnect;
1890 std::map<u16,bool> pending_unreliable;
1892 for(std::list<u16>::iterator
1893 j = peerIds.begin();
1894 j != peerIds.end(); ++j)
1896 PeerHelper peer = m_connection->getPeerNoEx(*j);
1897 //peer may have been removed
1899 LOG(dout_con<<m_connection->getDesc()<< " Peer not found: peer_id=" << *j << std::endl);
1902 peer->m_increment_packets_remaining = m_iteration_packets_avaialble/m_connection->m_peers.size();
1904 if (dynamic_cast<UDPPeer*>(&peer) == 0)
1909 if (dynamic_cast<UDPPeer*>(&peer)->m_pending_disconnect)
1911 pendingDisconnect.push_back(*j);
1914 PROFILE(std::stringstream peerIdentifier);
1915 PROFILE(peerIdentifier << "sendPackets[" << m_connection->getDesc() << ";" << *j << ";RELIABLE]");
1916 PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier.str(), SPT_AVG));
1918 LOG(dout_con<<m_connection->getDesc()
1919 << " Handle per peer queues: peer_id=" << *j
1920 << " packet quota: " << peer->m_increment_packets_remaining << std::endl);
1921 // first send queued reliable packets for all peers (if possible)
1922 for (unsigned int i=0; i < CHANNEL_COUNT; i++)
1924 u16 next_to_ack = 0;
1925 dynamic_cast<UDPPeer*>(&peer)->channels[i].outgoing_reliables_sent.getFirstSeqnum(next_to_ack);
1926 u16 next_to_receive = 0;
1927 dynamic_cast<UDPPeer*>(&peer)->channels[i].incoming_reliables.getFirstSeqnum(next_to_receive);
1929 LOG(dout_con<<m_connection->getDesc()<< "\t channel: "
1930 << i << ", peer quota:"
1931 << peer->m_increment_packets_remaining
1933 << "\t\t\treliables on wire: "
1934 << dynamic_cast<UDPPeer*>(&peer)->channels[i].outgoing_reliables_sent.size()
1935 << ", waiting for ack for " << next_to_ack
1937 << "\t\t\tincoming_reliables: "
1938 << dynamic_cast<UDPPeer*>(&peer)->channels[i].incoming_reliables.size()
1939 << ", next reliable packet: "
1940 << dynamic_cast<UDPPeer*>(&peer)->channels[i].readNextIncomingSeqNum()
1941 << ", next queued: " << next_to_receive
1943 << "\t\t\treliables queued : "
1944 << dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.size()
1946 << "\t\t\tqueued commands : "
1947 << dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_commands.size()
1950 while ((dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.size() > 0) &&
1951 (dynamic_cast<UDPPeer*>(&peer)->channels[i].outgoing_reliables_sent.size()
1952 < dynamic_cast<UDPPeer*>(&peer)->channels[i].getWindowSize())&&
1953 (peer->m_increment_packets_remaining > 0))
1955 BufferedPacket p = dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.front();
1956 dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.pop();
1957 Channel* channel = &(dynamic_cast<UDPPeer*>(&peer)->channels[i]);
1958 LOG(dout_con<<m_connection->getDesc()
1959 <<" INFO: sending a queued reliable packet "
1961 <<", seqnum: " << readU16(&p.data[BASE_HEADER_SIZE+1])
1963 sendAsPacketReliable(p,channel);
1964 peer->m_increment_packets_remaining--;
1969 if (m_outgoing_queue.size())
1971 LOG(dout_con<<m_connection->getDesc()
1972 << " Handle non reliable queue ("
1973 << m_outgoing_queue.size() << " pkts)" << std::endl);
1976 unsigned int initial_queuesize = m_outgoing_queue.size();
1977 /* send non reliable packets*/
1978 for(unsigned int i=0;i < initial_queuesize;i++) {
1979 OutgoingPacket packet = m_outgoing_queue.front();
1980 m_outgoing_queue.pop();
1982 if (packet.reliable)
1985 PeerHelper peer = m_connection->getPeerNoEx(packet.peer_id);
1987 LOG(dout_con<<m_connection->getDesc()
1988 <<" Outgoing queue: peer_id="<<packet.peer_id
1989 << ">>>NOT<<< found on sending packet"
1990 << ", channel " << (packet.channelnum % 0xFF)
1991 << ", size: " << packet.data.getSize() <<std::endl);
1994 /* send acks immediately */
1995 else if (packet.ack)
1997 rawSendAsPacket(packet.peer_id, packet.channelnum,
1998 packet.data, packet.reliable);
1999 peer->m_increment_packets_remaining =
2000 MYMIN(0,peer->m_increment_packets_remaining--);
2003 ( peer->m_increment_packets_remaining > 0) ||
2004 (stopRequested())) {
2005 rawSendAsPacket(packet.peer_id, packet.channelnum,
2006 packet.data, packet.reliable);
2007 peer->m_increment_packets_remaining--;
2010 m_outgoing_queue.push(packet);
2011 pending_unreliable[packet.peer_id] = true;
2015 for(std::list<u16>::iterator
2016 k = pendingDisconnect.begin();
2017 k != pendingDisconnect.end(); ++k)
2019 if (!pending_unreliable[*k])
2021 m_connection->deletePeer(*k,false);
2026 void ConnectionSendThread::sendAsPacket(u16 peer_id, u8 channelnum,
2027 SharedBuffer<u8> data, bool ack)
2029 OutgoingPacket packet(peer_id, channelnum, data, false, ack);
2030 m_outgoing_queue.push(packet);
2033 ConnectionReceiveThread::ConnectionReceiveThread(unsigned int max_packet_size) :
2034 Thread("ConnectionReceive"),
2039 void * ConnectionReceiveThread::run()
2041 assert(m_connection);
2043 LOG(dout_con<<m_connection->getDesc()
2044 <<"ConnectionReceive thread started"<<std::endl);
2046 PROFILE(std::stringstream ThreadIdentifier);
2047 PROFILE(ThreadIdentifier << "ConnectionReceive: [" << m_connection->getDesc() << "]");
2049 #ifdef DEBUG_CONNECTION_KBPS
2050 u64 curtime = porting::getTimeMs();
2051 u64 lasttime = curtime;
2052 float debug_print_timer = 0.0;
2055 while(!stopRequested()) {
2056 BEGIN_DEBUG_EXCEPTION_HANDLER
2057 PROFILE(ScopeProfiler sp(g_profiler, ThreadIdentifier.str(), SPT_AVG));
2059 #ifdef DEBUG_CONNECTION_KBPS
2061 curtime = porting::getTimeMs();
2062 float dtime = CALC_DTIME(lasttime,curtime);
2065 /* receive packets */
2068 #ifdef DEBUG_CONNECTION_KBPS
2069 debug_print_timer += dtime;
2070 if (debug_print_timer > 20.0) {
2071 debug_print_timer -= 20.0;
2073 std::list<u16> peerids = m_connection->getPeerIDs();
2075 for (std::list<u16>::iterator i = peerids.begin();
2079 PeerHelper peer = m_connection->getPeerNoEx(*i);
2083 float peer_current = 0.0;
2084 float peer_loss = 0.0;
2085 float avg_rate = 0.0;
2086 float avg_loss = 0.0;
2088 for(u16 j=0; j<CHANNEL_COUNT; j++)
2090 peer_current +=peer->channels[j].getCurrentDownloadRateKB();
2091 peer_loss += peer->channels[j].getCurrentLossRateKB();
2092 avg_rate += peer->channels[j].getAvgDownloadRateKB();
2093 avg_loss += peer->channels[j].getAvgLossRateKB();
2096 std::stringstream output;
2097 output << std::fixed << std::setprecision(1);
2098 output << "OUT to Peer " << *i << " RATES (good / loss) " << std::endl;
2099 output << "\tcurrent (sum): " << peer_current << "kb/s "<< peer_loss << "kb/s" << std::endl;
2100 output << "\taverage (sum): " << avg_rate << "kb/s "<< avg_loss << "kb/s" << std::endl;
2101 output << std::setfill(' ');
2102 for(u16 j=0; j<CHANNEL_COUNT; j++)
2104 output << "\tcha " << j << ":"
2105 << " CUR: " << std::setw(6) << peer->channels[j].getCurrentDownloadRateKB() <<"kb/s"
2106 << " AVG: " << std::setw(6) << peer->channels[j].getAvgDownloadRateKB() <<"kb/s"
2107 << " MAX: " << std::setw(6) << peer->channels[j].getMaxDownloadRateKB() <<"kb/s"
2109 << " CUR: " << std::setw(6) << peer->channels[j].getCurrentLossRateKB() <<"kb/s"
2110 << " AVG: " << std::setw(6) << peer->channels[j].getAvgLossRateKB() <<"kb/s"
2111 << " MAX: " << std::setw(6) << peer->channels[j].getMaxLossRateKB() <<"kb/s"
2112 << " / WS: " << peer->channels[j].getWindowSize()
2116 fprintf(stderr,"%s\n",output.str().c_str());
2120 END_DEBUG_EXCEPTION_HANDLER
2123 PROFILE(g_profiler->remove(ThreadIdentifier.str()));
2127 // Receive packets from the network and buffers and create ConnectionEvents
2128 void ConnectionReceiveThread::receive()
2130 // use IPv6 minimum allowed MTU as receive buffer size as this is
2131 // theoretical reliable upper boundary of a udp packet for all IPv6 enabled
2133 unsigned int packet_maxsize = 1500;
2134 SharedBuffer<u8> packetdata(packet_maxsize);
2136 bool packet_queued = true;
2138 unsigned int loop_count = 0;
2140 /* first of all read packets from socket */
2141 /* check for incoming data available */
2142 while( (loop_count < 10) &&
2143 (m_connection->m_udpSocket.WaitData(50))) {
2146 if (packet_queued) {
2147 bool data_left = true;
2149 SharedBuffer<u8> resultdata;
2152 data_left = getFromBuffers(peer_id, resultdata);
2155 e.dataReceived(peer_id, resultdata);
2156 m_connection->putEvent(e);
2159 catch(ProcessedSilentlyException &e) {
2160 /* try reading again */
2163 packet_queued = false;
2167 s32 received_size = m_connection->m_udpSocket.Receive(sender, *packetdata, packet_maxsize);
2169 if ((received_size < BASE_HEADER_SIZE) ||
2170 (readU32(&packetdata[0]) != m_connection->GetProtocolID()))
2172 LOG(derr_con<<m_connection->getDesc()
2173 <<"Receive(): Invalid incoming packet, "
2174 <<"size: " << received_size
2176 << ((received_size >= 4) ? readU32(&packetdata[0]) : -1)
2181 u16 peer_id = readPeerId(*packetdata);
2182 u8 channelnum = readChannel(*packetdata);
2184 if (channelnum > CHANNEL_COUNT-1) {
2185 LOG(derr_con<<m_connection->getDesc()
2186 <<"Receive(): Invalid channel "<<channelnum<<std::endl);
2187 throw InvalidIncomingDataException("Channel doesn't exist");
2190 /* Try to identify peer by sender address (may happen on join) */
2191 if (peer_id == PEER_ID_INEXISTENT) {
2192 peer_id = m_connection->lookupPeer(sender);
2193 // We do not have to remind the peer of its
2194 // peer id as the CONTROLTYPE_SET_PEER_ID
2195 // command was sent reliably.
2198 /* The peer was not found in our lists. Add it. */
2199 if (peer_id == PEER_ID_INEXISTENT) {
2200 peer_id = m_connection->createPeer(sender, MTP_MINETEST_RELIABLE_UDP, 0);
2203 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
2206 LOG(dout_con<<m_connection->getDesc()
2207 <<" got packet from unknown peer_id: "
2208 <<peer_id<<" Ignoring."<<std::endl);
2212 // Validate peer address
2214 Address peer_address;
2216 if (peer->getAddress(MTP_UDP, peer_address)) {
2217 if (peer_address != sender) {
2218 LOG(derr_con<<m_connection->getDesc()
2219 <<m_connection->getDesc()
2220 <<" Peer "<<peer_id<<" sending from different address."
2221 " Ignoring."<<std::endl);
2227 bool invalid_address = true;
2228 if (invalid_address) {
2229 LOG(derr_con<<m_connection->getDesc()
2230 <<m_connection->getDesc()
2231 <<" Peer "<<peer_id<<" unknown."
2232 " Ignoring."<<std::endl);
2237 peer->ResetTimeout();
2239 Channel *channel = 0;
2241 if (dynamic_cast<UDPPeer*>(&peer) != 0)
2243 channel = &(dynamic_cast<UDPPeer*>(&peer)->channels[channelnum]);
2247 channel->UpdateBytesReceived(received_size);
2250 // Throw the received packet to channel->processPacket()
2252 // Make a new SharedBuffer from the data without the base headers
2253 SharedBuffer<u8> strippeddata(received_size - BASE_HEADER_SIZE);
2254 memcpy(*strippeddata, &packetdata[BASE_HEADER_SIZE],
2255 strippeddata.getSize());
2258 // Process it (the result is some data with no headers made by us)
2259 SharedBuffer<u8> resultdata = processPacket
2260 (channel, strippeddata, peer_id, channelnum, false);
2262 LOG(dout_con<<m_connection->getDesc()
2263 <<" ProcessPacket from peer_id: " << peer_id
2264 << ",channel: " << (channelnum & 0xFF) << ", returned "
2265 << resultdata.getSize() << " bytes" <<std::endl);
2268 e.dataReceived(peer_id, resultdata);
2269 m_connection->putEvent(e);
2271 catch(ProcessedSilentlyException &e) {
2273 catch(ProcessedQueued &e) {
2274 packet_queued = true;
2277 catch(InvalidIncomingDataException &e) {
2279 catch(ProcessedSilentlyException &e) {
2284 bool ConnectionReceiveThread::getFromBuffers(u16 &peer_id, SharedBuffer<u8> &dst)
2286 std::list<u16> peerids = m_connection->getPeerIDs();
2288 for(std::list<u16>::iterator j = peerids.begin();
2289 j != peerids.end(); ++j)
2291 PeerHelper peer = m_connection->getPeerNoEx(*j);
2295 if (dynamic_cast<UDPPeer*>(&peer) == 0)
2298 for(u16 i=0; i<CHANNEL_COUNT; i++)
2300 Channel *channel = &(dynamic_cast<UDPPeer*>(&peer))->channels[i];
2302 if (checkIncomingBuffers(channel, peer_id, dst)) {
2310 bool ConnectionReceiveThread::checkIncomingBuffers(Channel *channel,
2311 u16 &peer_id, SharedBuffer<u8> &dst)
2313 u16 firstseqnum = 0;
2314 if (channel->incoming_reliables.getFirstSeqnum(firstseqnum))
2316 if (firstseqnum == channel->readNextIncomingSeqNum())
2318 BufferedPacket p = channel->incoming_reliables.popFirst();
2319 peer_id = readPeerId(*p.data);
2320 u8 channelnum = readChannel(*p.data);
2321 u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]);
2323 LOG(dout_con<<m_connection->getDesc()
2324 <<"UNBUFFERING TYPE_RELIABLE"
2325 <<" seqnum="<<seqnum
2326 <<" peer_id="<<peer_id
2327 <<" channel="<<((int)channelnum&0xff)
2330 channel->incNextIncomingSeqNum();
2332 u32 headers_size = BASE_HEADER_SIZE + RELIABLE_HEADER_SIZE;
2333 // Get out the inside packet and re-process it
2334 SharedBuffer<u8> payload(p.data.getSize() - headers_size);
2335 memcpy(*payload, &p.data[headers_size], payload.getSize());
2337 dst = processPacket(channel, payload, peer_id, channelnum, true);
2344 SharedBuffer<u8> ConnectionReceiveThread::processPacket(Channel *channel,
2345 SharedBuffer<u8> packetdata, u16 peer_id, u8 channelnum, bool reliable)
2347 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
2350 errorstream << "Peer not found (possible timeout)" << std::endl;
2351 throw ProcessedSilentlyException("Peer not found (possible timeout)");
2354 if (packetdata.getSize() < 1)
2355 throw InvalidIncomingDataException("packetdata.getSize() < 1");
2357 u8 type = readU8(&(packetdata[0]));
2359 if (MAX_UDP_PEERS <= 65535 && peer_id >= MAX_UDP_PEERS) {
2360 std::string errmsg = "Invalid peer_id=" + itos(peer_id);
2361 errorstream << errmsg << std::endl;
2362 throw InvalidIncomingDataException(errmsg.c_str());
2365 if (type == TYPE_CONTROL)
2367 if (packetdata.getSize() < 2)
2368 throw InvalidIncomingDataException("packetdata.getSize() < 2");
2370 u8 controltype = readU8(&(packetdata[1]));
2372 if (controltype == CONTROLTYPE_ACK)
2374 assert(channel != NULL);
2376 if (packetdata.getSize() < 4) {
2377 throw InvalidIncomingDataException(
2378 "packetdata.getSize() < 4 (ACK header size)");
2381 u16 seqnum = readU16(&packetdata[2]);
2382 LOG(dout_con<<m_connection->getDesc()
2383 <<" [ CONTROLTYPE_ACK: channelnum="
2384 <<((int)channelnum&0xff)<<", peer_id="<<peer_id
2385 <<", seqnum="<<seqnum<< " ]"<<std::endl);
2389 channel->outgoing_reliables_sent.popSeqnum(seqnum);
2391 // only calculate rtt from straight sent packets
2392 if (p.resend_count == 0) {
2393 // Get round trip time
2394 u64 current_time = porting::getTimeMs();
2396 // a overflow is quite unlikely but as it'd result in major
2397 // rtt miscalculation we handle it here
2398 if (current_time > p.absolute_send_time)
2400 float rtt = (current_time - p.absolute_send_time) / 1000.0;
2402 // Let peer calculate stuff according to it
2403 // (avg_rtt and resend_timeout)
2404 dynamic_cast<UDPPeer*>(&peer)->reportRTT(rtt);
2406 else if (p.totaltime > 0)
2408 float rtt = p.totaltime;
2410 // Let peer calculate stuff according to it
2411 // (avg_rtt and resend_timeout)
2412 dynamic_cast<UDPPeer*>(&peer)->reportRTT(rtt);
2415 //put bytes for max bandwidth calculation
2416 channel->UpdateBytesSent(p.data.getSize(),1);
2417 if (channel->outgoing_reliables_sent.size() == 0)
2419 m_connection->TriggerSend();
2422 catch(NotFoundException &e) {
2423 LOG(derr_con<<m_connection->getDesc()
2424 <<"WARNING: ACKed packet not "
2427 channel->UpdatePacketTooLateCounter();
2429 throw ProcessedSilentlyException("Got an ACK");
2431 else if (controltype == CONTROLTYPE_SET_PEER_ID) {
2432 // Got a packet to set our peer id
2433 if (packetdata.getSize() < 4)
2434 throw InvalidIncomingDataException
2435 ("packetdata.getSize() < 4 (SET_PEER_ID header size)");
2436 u16 peer_id_new = readU16(&packetdata[2]);
2437 LOG(dout_con<<m_connection->getDesc()
2438 <<"Got new peer id: "<<peer_id_new<<"... "<<std::endl);
2440 if (m_connection->GetPeerID() != PEER_ID_INEXISTENT)
2442 LOG(derr_con<<m_connection->getDesc()
2443 <<"WARNING: Not changing"
2444 " existing peer id."<<std::endl);
2448 LOG(dout_con<<m_connection->getDesc()<<"changing own peer id"<<std::endl);
2449 m_connection->SetPeerID(peer_id_new);
2452 ConnectionCommand cmd;
2454 SharedBuffer<u8> reply(2);
2455 writeU8(&reply[0], TYPE_CONTROL);
2456 writeU8(&reply[1], CONTROLTYPE_ENABLE_BIG_SEND_WINDOW);
2457 cmd.disableLegacy(PEER_ID_SERVER,reply);
2458 m_connection->putCommand(cmd);
2460 throw ProcessedSilentlyException("Got a SET_PEER_ID");
2462 else if (controltype == CONTROLTYPE_PING)
2464 // Just ignore it, the incoming data already reset
2465 // the timeout counter
2466 LOG(dout_con<<m_connection->getDesc()<<"PING"<<std::endl);
2467 throw ProcessedSilentlyException("Got a PING");
2469 else if (controltype == CONTROLTYPE_DISCO)
2471 // Just ignore it, the incoming data already reset
2472 // the timeout counter
2473 LOG(dout_con<<m_connection->getDesc()
2474 <<"DISCO: Removing peer "<<(peer_id)<<std::endl);
2476 if (m_connection->deletePeer(peer_id, false) == false)
2478 derr_con<<m_connection->getDesc()
2479 <<"DISCO: Peer not found"<<std::endl;
2482 throw ProcessedSilentlyException("Got a DISCO");
2484 else if (controltype == CONTROLTYPE_ENABLE_BIG_SEND_WINDOW)
2486 dynamic_cast<UDPPeer*>(&peer)->setNonLegacyPeer();
2487 throw ProcessedSilentlyException("Got non legacy control");
2490 LOG(derr_con<<m_connection->getDesc()
2491 <<"INVALID TYPE_CONTROL: invalid controltype="
2492 <<((int)controltype&0xff)<<std::endl);
2493 throw InvalidIncomingDataException("Invalid control type");
2496 else if (type == TYPE_ORIGINAL)
2498 if (packetdata.getSize() <= ORIGINAL_HEADER_SIZE)
2499 throw InvalidIncomingDataException
2500 ("packetdata.getSize() <= ORIGINAL_HEADER_SIZE");
2501 LOG(dout_con<<m_connection->getDesc()
2502 <<"RETURNING TYPE_ORIGINAL to user"
2504 // Get the inside packet out and return it
2505 SharedBuffer<u8> payload(packetdata.getSize() - ORIGINAL_HEADER_SIZE);
2506 memcpy(*payload, &(packetdata[ORIGINAL_HEADER_SIZE]), payload.getSize());
2509 else if (type == TYPE_SPLIT)
2511 Address peer_address;
2513 if (peer->getAddress(MTP_UDP, peer_address)) {
2515 // We have to create a packet again for buffering
2516 // This isn't actually too bad an idea.
2517 BufferedPacket packet = makePacket(
2520 m_connection->GetProtocolID(),
2524 // Buffer the packet
2525 SharedBuffer<u8> data =
2526 peer->addSpiltPacket(channelnum,packet,reliable);
2528 if (data.getSize() != 0)
2530 LOG(dout_con<<m_connection->getDesc()
2531 <<"RETURNING TYPE_SPLIT: Constructed full data, "
2532 <<"size="<<data.getSize()<<std::endl);
2535 LOG(dout_con<<m_connection->getDesc()<<"BUFFERED TYPE_SPLIT"<<std::endl);
2536 throw ProcessedSilentlyException("Buffered a split packet chunk");
2539 //TODO throw some error
2542 else if (type == TYPE_RELIABLE)
2544 assert(channel != NULL);
2546 // Recursive reliable packets not allowed
2548 throw InvalidIncomingDataException("Found nested reliable packets");
2550 if (packetdata.getSize() < RELIABLE_HEADER_SIZE)
2551 throw InvalidIncomingDataException
2552 ("packetdata.getSize() < RELIABLE_HEADER_SIZE");
2554 u16 seqnum = readU16(&packetdata[1]);
2555 bool is_future_packet = false;
2556 bool is_old_packet = false;
2558 /* packet is within our receive window send ack */
2559 if (seqnum_in_window(seqnum, channel->readNextIncomingSeqNum(),MAX_RELIABLE_WINDOW_SIZE))
2561 m_connection->sendAck(peer_id,channelnum,seqnum);
2564 is_future_packet = seqnum_higher(seqnum, channel->readNextIncomingSeqNum());
2565 is_old_packet = seqnum_higher(channel->readNextIncomingSeqNum(), seqnum);
2568 /* packet is not within receive window, don't send ack. *
2569 * if this was a valid packet it's gonna be retransmitted */
2570 if (is_future_packet)
2572 throw ProcessedSilentlyException("Received packet newer then expected, not sending ack");
2575 /* seems like our ack was lost, send another one for a old packet */
2578 LOG(dout_con<<m_connection->getDesc()
2579 << "RE-SENDING ACK: peer_id: " << peer_id
2580 << ", channel: " << (channelnum&0xFF)
2581 << ", seqnum: " << seqnum << std::endl;)
2582 m_connection->sendAck(peer_id,channelnum,seqnum);
2584 // we already have this packet so this one was on wire at least
2585 // the current timeout
2586 // we don't know how long this packet was on wire don't do silly guessing
2587 // dynamic_cast<UDPPeer*>(&peer)->reportRTT(dynamic_cast<UDPPeer*>(&peer)->getResendTimeout());
2589 throw ProcessedSilentlyException("Retransmitting ack for old packet");
2593 if (seqnum != channel->readNextIncomingSeqNum())
2595 Address peer_address;
2597 // this is a reliable packet so we have a udp address for sure
2598 peer->getAddress(MTP_MINETEST_RELIABLE_UDP, peer_address);
2599 // This one comes later, buffer it.
2600 // Actually we have to make a packet to buffer one.
2601 // Well, we have all the ingredients, so just do it.
2602 BufferedPacket packet = con::makePacket(
2605 m_connection->GetProtocolID(),
2609 channel->incoming_reliables.insert(packet,channel->readNextIncomingSeqNum());
2611 LOG(dout_con<<m_connection->getDesc()
2612 << "BUFFERING, TYPE_RELIABLE peer_id: " << peer_id
2613 << ", channel: " << (channelnum&0xFF)
2614 << ", seqnum: " << seqnum << std::endl;)
2616 throw ProcessedQueued("Buffered future reliable packet");
2618 catch(AlreadyExistsException &e)
2621 catch(IncomingDataCorruption &e)
2623 ConnectionCommand discon;
2624 discon.disconnect_peer(peer_id);
2625 m_connection->putCommand(discon);
2627 LOG(derr_con<<m_connection->getDesc()
2628 << "INVALID, TYPE_RELIABLE peer_id: " << peer_id
2629 << ", channel: " << (channelnum&0xFF)
2630 << ", seqnum: " << seqnum
2631 << "DROPPING CLIENT!" << std::endl;)
2635 /* we got a packet to process right now */
2636 LOG(dout_con<<m_connection->getDesc()
2637 << "RECURSIVE, TYPE_RELIABLE peer_id: " << peer_id
2638 << ", channel: " << (channelnum&0xFF)
2639 << ", seqnum: " << seqnum << std::endl;)
2642 /* check for resend case */
2643 u16 queued_seqnum = 0;
2644 if (channel->incoming_reliables.getFirstSeqnum(queued_seqnum))
2646 if (queued_seqnum == seqnum)
2648 BufferedPacket queued_packet = channel->incoming_reliables.popFirst();
2649 /** TODO find a way to verify the new against the old packet */
2653 channel->incNextIncomingSeqNum();
2655 // Get out the inside packet and re-process it
2656 SharedBuffer<u8> payload(packetdata.getSize() - RELIABLE_HEADER_SIZE);
2657 memcpy(*payload, &packetdata[RELIABLE_HEADER_SIZE], payload.getSize());
2659 return processPacket(channel, payload, peer_id, channelnum, true);
2663 derr_con<<m_connection->getDesc()
2664 <<"Got invalid type="<<((int)type&0xff)<<std::endl;
2665 throw InvalidIncomingDataException("Invalid packet type");
2668 // We should never get here.
2669 FATAL_ERROR("Invalid execution point");
2676 Connection::Connection(u32 protocol_id, u32 max_packet_size, float timeout,
2677 bool ipv6, PeerHandler *peerhandler) :
2682 m_protocol_id(protocol_id),
2683 m_sendThread(max_packet_size, timeout),
2684 m_receiveThread(max_packet_size),
2686 m_bc_peerhandler(peerhandler),
2687 m_bc_receive_timeout(0),
2688 m_shutting_down(false),
2689 m_next_remote_peer_id(2)
2692 m_udpSocket.setTimeoutMs(5);
2694 m_sendThread.setParent(this);
2695 m_receiveThread.setParent(this);
2697 m_sendThread.start();
2698 m_receiveThread.start();
2703 Connection::~Connection()
2705 m_shutting_down = true;
2706 // request threads to stop
2707 m_sendThread.stop();
2708 m_receiveThread.stop();
2710 //TODO for some unkonwn reason send/receive threads do not exit as they're
2711 // supposed to be but wait on peer timeout. To speed up shutdown we reduce
2712 // timeout to half a second.
2713 m_sendThread.setPeerTimeout(0.5);
2715 // wait for threads to finish
2716 m_sendThread.wait();
2717 m_receiveThread.wait();
2720 for(std::map<u16, Peer*>::iterator
2721 j = m_peers.begin();
2722 j != m_peers.end(); ++j)
2728 /* Internal stuff */
2729 void Connection::putEvent(ConnectionEvent &e)
2731 assert(e.type != CONNEVENT_NONE); // Pre-condition
2732 m_event_queue.push_back(e);
2735 PeerHelper Connection::getPeer(u16 peer_id)
2737 MutexAutoLock peerlock(m_peers_mutex);
2738 std::map<u16, Peer*>::iterator node = m_peers.find(peer_id);
2740 if (node == m_peers.end()) {
2741 throw PeerNotFoundException("GetPeer: Peer not found (possible timeout)");
2745 FATAL_ERROR_IF(node->second->id != peer_id, "Invalid peer id");
2747 return PeerHelper(node->second);
2750 PeerHelper Connection::getPeerNoEx(u16 peer_id)
2752 MutexAutoLock peerlock(m_peers_mutex);
2753 std::map<u16, Peer*>::iterator node = m_peers.find(peer_id);
2755 if (node == m_peers.end()) {
2756 return PeerHelper(NULL);
2760 FATAL_ERROR_IF(node->second->id != peer_id, "Invalid peer id");
2762 return PeerHelper(node->second);
2765 /* find peer_id for address */
2766 u16 Connection::lookupPeer(Address& sender)
2768 MutexAutoLock peerlock(m_peers_mutex);
2769 std::map<u16, Peer*>::iterator j;
2770 j = m_peers.begin();
2771 for(; j != m_peers.end(); ++j)
2773 Peer *peer = j->second;
2774 if (peer->isPendingDeletion())
2779 if ((peer->getAddress(MTP_MINETEST_RELIABLE_UDP, tocheck)) && (tocheck == sender))
2782 if ((peer->getAddress(MTP_UDP, tocheck)) && (tocheck == sender))
2786 return PEER_ID_INEXISTENT;
2789 std::list<Peer*> Connection::getPeers()
2791 std::list<Peer*> list;
2792 for(std::map<u16, Peer*>::iterator j = m_peers.begin();
2793 j != m_peers.end(); ++j)
2795 Peer *peer = j->second;
2796 list.push_back(peer);
2801 bool Connection::deletePeer(u16 peer_id, bool timeout)
2805 /* lock list as short as possible */
2807 MutexAutoLock peerlock(m_peers_mutex);
2808 if (m_peers.find(peer_id) == m_peers.end())
2810 peer = m_peers[peer_id];
2811 m_peers.erase(peer_id);
2812 m_peer_ids.remove(peer_id);
2815 Address peer_address;
2816 //any peer has a primary address this never fails!
2817 peer->getAddress(MTP_PRIMARY, peer_address);
2820 e.peerRemoved(peer_id, timeout, peer_address);
2830 ConnectionEvent Connection::waitEvent(u32 timeout_ms)
2833 return m_event_queue.pop_front(timeout_ms);
2834 } catch(ItemNotFoundException &ex) {
2836 e.type = CONNEVENT_NONE;
2841 void Connection::putCommand(ConnectionCommand &c)
2843 if (!m_shutting_down) {
2844 m_command_queue.push_back(c);
2845 m_sendThread.Trigger();
2849 void Connection::Serve(Address bind_addr)
2851 ConnectionCommand c;
2856 void Connection::Connect(Address address)
2858 ConnectionCommand c;
2863 bool Connection::Connected()
2865 MutexAutoLock peerlock(m_peers_mutex);
2867 if (m_peers.size() != 1)
2870 std::map<u16, Peer*>::iterator node = m_peers.find(PEER_ID_SERVER);
2871 if (node == m_peers.end())
2874 if (m_peer_id == PEER_ID_INEXISTENT)
2880 void Connection::Disconnect()
2882 ConnectionCommand c;
2887 void Connection::Receive(NetworkPacket* pkt)
2890 ConnectionEvent e = waitEvent(m_bc_receive_timeout);
2891 if (e.type != CONNEVENT_NONE)
2892 LOG(dout_con << getDesc() << ": Receive: got event: "
2893 << e.describe() << std::endl);
2895 case CONNEVENT_NONE:
2896 throw NoIncomingDataException("No incoming data");
2897 case CONNEVENT_DATA_RECEIVED:
2898 // Data size is lesser than command size, ignoring packet
2899 if (e.data.getSize() < 2) {
2903 pkt->putRawPacket(*e.data, e.data.getSize(), e.peer_id);
2905 case CONNEVENT_PEER_ADDED: {
2906 UDPPeer tmp(e.peer_id, e.address, this);
2907 if (m_bc_peerhandler)
2908 m_bc_peerhandler->peerAdded(&tmp);
2911 case CONNEVENT_PEER_REMOVED: {
2912 UDPPeer tmp(e.peer_id, e.address, this);
2913 if (m_bc_peerhandler)
2914 m_bc_peerhandler->deletingPeer(&tmp, e.timeout);
2917 case CONNEVENT_BIND_FAILED:
2918 throw ConnectionBindFailed("Failed to bind socket "
2919 "(port already in use?)");
2922 throw NoIncomingDataException("No incoming data");
2925 void Connection::Send(u16 peer_id, u8 channelnum,
2926 NetworkPacket* pkt, bool reliable)
2928 assert(channelnum < CHANNEL_COUNT); // Pre-condition
2930 ConnectionCommand c;
2932 c.send(peer_id, channelnum, pkt, reliable);
2936 Address Connection::GetPeerAddress(u16 peer_id)
2938 PeerHelper peer = getPeerNoEx(peer_id);
2941 throw PeerNotFoundException("No address for peer found!");
2942 Address peer_address;
2943 peer->getAddress(MTP_PRIMARY, peer_address);
2944 return peer_address;
2947 float Connection::getPeerStat(u16 peer_id, rtt_stat_type type)
2949 PeerHelper peer = getPeerNoEx(peer_id);
2950 if (!peer) return -1;
2951 return peer->getStat(type);
2954 float Connection::getLocalStat(rate_stat_type type)
2956 PeerHelper peer = getPeerNoEx(PEER_ID_SERVER);
2958 FATAL_ERROR_IF(!peer, "Connection::getLocalStat we couldn't get our own peer? are you serious???");
2962 for (u16 j=0; j<CHANNEL_COUNT; j++) {
2965 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getCurrentDownloadRateKB();
2968 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getAvgDownloadRateKB();
2971 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getCurrentIncomingRateKB();
2974 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getAvgIncomingRateKB();
2977 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getAvgLossRateKB();
2980 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getCurrentLossRateKB();
2983 FATAL_ERROR("Connection::getLocalStat Invalid stat type");
2989 u16 Connection::createPeer(Address& sender, MTProtocols protocol, int fd)
2991 // Somebody wants to make a new connection
2993 // Get a unique peer id (2 or higher)
2994 u16 peer_id_new = m_next_remote_peer_id;
2995 u16 overflow = MAX_UDP_PEERS;
2998 Find an unused peer id
3000 MutexAutoLock lock(m_peers_mutex);
3001 bool out_of_ids = false;
3004 if (m_peers.find(peer_id_new) == m_peers.end())
3007 // Check for overflow
3008 if (peer_id_new == overflow) {
3016 errorstream << getDesc() << " ran out of peer ids" << std::endl;
3017 return PEER_ID_INEXISTENT;
3022 peer = new UDPPeer(peer_id_new, sender, this);
3024 m_peers[peer->id] = peer;
3025 m_peer_ids.push_back(peer->id);
3027 m_next_remote_peer_id = (peer_id_new +1 ) % MAX_UDP_PEERS;
3029 LOG(dout_con << getDesc()
3030 << "createPeer(): giving peer_id=" << peer_id_new << std::endl);
3032 ConnectionCommand cmd;
3033 SharedBuffer<u8> reply(4);
3034 writeU8(&reply[0], TYPE_CONTROL);
3035 writeU8(&reply[1], CONTROLTYPE_SET_PEER_ID);
3036 writeU16(&reply[2], peer_id_new);
3037 cmd.createPeer(peer_id_new,reply);
3040 // Create peer addition event
3042 e.peerAdded(peer_id_new, sender);
3045 // We're now talking to a valid peer_id
3049 void Connection::PrintInfo(std::ostream &out)
3051 m_info_mutex.lock();
3052 out<<getDesc()<<": ";
3053 m_info_mutex.unlock();
3056 void Connection::PrintInfo()
3058 PrintInfo(dout_con);
3061 const std::string Connection::getDesc()
3063 return std::string("con(")+
3064 itos(m_udpSocket.GetHandle())+"/"+itos(m_peer_id)+")";
3067 void Connection::DisconnectPeer(u16 peer_id)
3069 ConnectionCommand discon;
3070 discon.disconnect_peer(peer_id);
3074 void Connection::sendAck(u16 peer_id, u8 channelnum, u16 seqnum)
3076 assert(channelnum < CHANNEL_COUNT); // Pre-condition
3078 LOG(dout_con<<getDesc()
3079 <<" Queuing ACK command to peer_id: " << peer_id <<
3080 " channel: " << (channelnum & 0xFF) <<
3081 " seqnum: " << seqnum << std::endl);
3083 ConnectionCommand c;
3084 SharedBuffer<u8> ack(4);
3085 writeU8(&ack[0], TYPE_CONTROL);
3086 writeU8(&ack[1], CONTROLTYPE_ACK);
3087 writeU16(&ack[2], seqnum);
3089 c.ack(peer_id, channelnum, ack);
3091 m_sendThread.Trigger();
3094 UDPPeer* Connection::createServerPeer(Address& address)
3096 if (getPeerNoEx(PEER_ID_SERVER) != 0)
3098 throw ConnectionException("Already connected to a server");
3101 UDPPeer *peer = new UDPPeer(PEER_ID_SERVER, address, this);
3104 MutexAutoLock lock(m_peers_mutex);
3105 m_peers[peer->id] = peer;
3106 m_peer_ids.push_back(peer->id);