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(unsigned int lasttime, unsigned int curtime) {
58 float value = ( curtime - lasttime) / 1000.0;
59 return MYMAX(MYMIN(value,0.1),0.0);
62 /* maximum window size to use, 0xFFFF is theoretical maximum don't think about
63 * touching it, the less you're away from it the more likely data corruption
66 #define MAX_RELIABLE_WINDOW_SIZE 0x8000
67 /* starting value for window size */
68 #define MIN_RELIABLE_WINDOW_SIZE 0x40
70 #define MAX_UDP_PEERS 65535
72 #define PING_TIMEOUT 5.0
74 static u16 readPeerId(u8 *packetdata)
76 return readU16(&packetdata[4]);
78 static u8 readChannel(u8 *packetdata)
80 return readU8(&packetdata[6]);
83 BufferedPacket makePacket(Address &address, u8 *data, u32 datasize,
84 u32 protocol_id, u16 sender_peer_id, u8 channel)
86 u32 packet_size = datasize + BASE_HEADER_SIZE;
87 BufferedPacket p(packet_size);
90 writeU32(&p.data[0], protocol_id);
91 writeU16(&p.data[4], sender_peer_id);
92 writeU8(&p.data[6], channel);
94 memcpy(&p.data[BASE_HEADER_SIZE], data, datasize);
99 BufferedPacket makePacket(Address &address, SharedBuffer<u8> &data,
100 u32 protocol_id, u16 sender_peer_id, u8 channel)
102 return makePacket(address, *data, data.getSize(),
103 protocol_id, sender_peer_id, channel);
106 SharedBuffer<u8> makeOriginalPacket(
107 SharedBuffer<u8> data)
110 u32 packet_size = data.getSize() + header_size;
111 SharedBuffer<u8> b(packet_size);
113 writeU8(&(b[0]), TYPE_ORIGINAL);
114 if (data.getSize() > 0) {
115 memcpy(&(b[header_size]), *data, data.getSize());
120 std::list<SharedBuffer<u8> > makeSplitPacket(
121 SharedBuffer<u8> data,
125 // Chunk packets, containing the TYPE_SPLIT header
126 std::list<SharedBuffer<u8> > chunks;
128 u32 chunk_header_size = 7;
129 u32 maximum_data_size = chunksize_max - chunk_header_size;
135 end = start + maximum_data_size - 1;
136 if (end > data.getSize() - 1)
137 end = data.getSize() - 1;
139 u32 payload_size = end - start + 1;
140 u32 packet_size = chunk_header_size + payload_size;
142 SharedBuffer<u8> chunk(packet_size);
144 writeU8(&chunk[0], TYPE_SPLIT);
145 writeU16(&chunk[1], seqnum);
146 // [3] u16 chunk_count is written at next stage
147 writeU16(&chunk[5], chunk_num);
148 memcpy(&chunk[chunk_header_size], &data[start], payload_size);
150 chunks.push_back(chunk);
156 while(end != data.getSize() - 1);
158 for(std::list<SharedBuffer<u8> >::iterator i = chunks.begin();
159 i != chunks.end(); ++i)
162 writeU16(&((*i)[3]), chunk_count);
168 std::list<SharedBuffer<u8> > makeAutoSplitPacket(
169 SharedBuffer<u8> data,
173 u32 original_header_size = 1;
174 std::list<SharedBuffer<u8> > list;
175 if (data.getSize() + original_header_size > chunksize_max)
177 list = makeSplitPacket(data, chunksize_max, split_seqnum);
183 list.push_back(makeOriginalPacket(data));
188 SharedBuffer<u8> makeReliablePacket(
189 SharedBuffer<u8> data,
193 u32 packet_size = data.getSize() + header_size;
194 SharedBuffer<u8> b(packet_size);
196 writeU8(&b[0], TYPE_RELIABLE);
197 writeU16(&b[1], seqnum);
199 memcpy(&b[header_size], *data, data.getSize());
208 ReliablePacketBuffer::ReliablePacketBuffer(): m_list_size(0) {}
210 void ReliablePacketBuffer::print()
212 MutexAutoLock listlock(m_list_mutex);
213 LOG(dout_con<<"Dump of ReliablePacketBuffer:" << std::endl);
214 unsigned int index = 0;
215 for(std::list<BufferedPacket>::iterator i = m_list.begin();
219 u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
220 LOG(dout_con<<index<< ":" << s << std::endl);
224 bool ReliablePacketBuffer::empty()
226 MutexAutoLock listlock(m_list_mutex);
227 return m_list.empty();
230 u32 ReliablePacketBuffer::size()
235 bool ReliablePacketBuffer::containsPacket(u16 seqnum)
237 return !(findPacket(seqnum) == m_list.end());
240 RPBSearchResult ReliablePacketBuffer::findPacket(u16 seqnum)
242 std::list<BufferedPacket>::iterator i = m_list.begin();
243 for(; i != m_list.end(); ++i)
245 u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
246 /*dout_con<<"findPacket(): finding seqnum="<<seqnum
247 <<", comparing to s="<<s<<std::endl;*/
253 RPBSearchResult ReliablePacketBuffer::notFound()
257 bool ReliablePacketBuffer::getFirstSeqnum(u16& result)
259 MutexAutoLock listlock(m_list_mutex);
262 BufferedPacket p = *m_list.begin();
263 result = readU16(&p.data[BASE_HEADER_SIZE+1]);
267 BufferedPacket ReliablePacketBuffer::popFirst()
269 MutexAutoLock listlock(m_list_mutex);
271 throw NotFoundException("Buffer is empty");
272 BufferedPacket p = *m_list.begin();
273 m_list.erase(m_list.begin());
276 if (m_list_size == 0) {
277 m_oldest_non_answered_ack = 0;
279 m_oldest_non_answered_ack =
280 readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]);
284 BufferedPacket ReliablePacketBuffer::popSeqnum(u16 seqnum)
286 MutexAutoLock listlock(m_list_mutex);
287 RPBSearchResult r = findPacket(seqnum);
288 if (r == notFound()) {
289 LOG(dout_con<<"Sequence number: " << seqnum
290 << " not found in reliable buffer"<<std::endl);
291 throw NotFoundException("seqnum not found in buffer");
293 BufferedPacket p = *r;
296 RPBSearchResult next = r;
298 if (next != notFound()) {
299 u16 s = readU16(&(next->data[BASE_HEADER_SIZE+1]));
300 m_oldest_non_answered_ack = s;
306 if (m_list_size == 0)
307 { m_oldest_non_answered_ack = 0; }
309 { m_oldest_non_answered_ack = readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]); }
312 void ReliablePacketBuffer::insert(BufferedPacket &p,u16 next_expected)
314 MutexAutoLock listlock(m_list_mutex);
315 if (p.data.getSize() < BASE_HEADER_SIZE + 3) {
316 errorstream << "ReliablePacketBuffer::insert(): Invalid data size for "
317 "reliable packet" << std::endl;
320 u8 type = readU8(&p.data[BASE_HEADER_SIZE + 0]);
321 if (type != TYPE_RELIABLE) {
322 errorstream << "ReliablePacketBuffer::insert(): type is not reliable"
326 u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE + 1]);
328 if (!seqnum_in_window(seqnum, next_expected, MAX_RELIABLE_WINDOW_SIZE)) {
329 errorstream << "ReliablePacketBuffer::insert(): seqnum is outside of "
330 "expected window " << std::endl;
333 if (seqnum == next_expected) {
334 errorstream << "ReliablePacketBuffer::insert(): seqnum is next expected"
340 sanity_check(m_list_size <= SEQNUM_MAX+1); // FIXME: Handle the error?
342 // Find the right place for the packet and insert it there
343 // If list is empty, just add it
347 m_oldest_non_answered_ack = seqnum;
352 // Otherwise find the right place
353 std::list<BufferedPacket>::iterator i = m_list.begin();
354 // Find the first packet in the list which has a higher seqnum
355 u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
357 /* case seqnum is smaller then next_expected seqnum */
358 /* this is true e.g. on wrap around */
359 if (seqnum < next_expected) {
360 while(((s < seqnum) || (s >= next_expected)) && (i != m_list.end())) {
362 if (i != m_list.end())
363 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
366 /* non wrap around case (at least for incoming and next_expected */
369 while(((s < seqnum) && (s >= next_expected)) && (i != m_list.end())) {
371 if (i != m_list.end())
372 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
378 (readU16(&(i->data[BASE_HEADER_SIZE+1])) != seqnum) ||
379 (i->data.getSize() != p.data.getSize()) ||
380 (i->address != p.address)
383 /* if this happens your maximum transfer window may be to big */
385 "Duplicated seqnum %d non matching packet detected:\n",
387 fprintf(stderr, "Old: seqnum: %05d size: %04d, address: %s\n",
388 readU16(&(i->data[BASE_HEADER_SIZE+1])),i->data.getSize(),
389 i->address.serializeString().c_str());
390 fprintf(stderr, "New: seqnum: %05d size: %04u, address: %s\n",
391 readU16(&(p.data[BASE_HEADER_SIZE+1])),p.data.getSize(),
392 p.address.serializeString().c_str());
393 throw IncomingDataCorruption("duplicated packet isn't same as original one");
396 /* nothing to do this seems to be a resent packet */
397 /* for paranoia reason data should be compared */
400 /* insert or push back */
401 else if (i != m_list.end()) {
408 /* update last packet number */
409 m_oldest_non_answered_ack = readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]);
412 void ReliablePacketBuffer::incrementTimeouts(float dtime)
414 MutexAutoLock listlock(m_list_mutex);
415 for(std::list<BufferedPacket>::iterator i = m_list.begin();
416 i != m_list.end(); ++i)
419 i->totaltime += dtime;
423 std::list<BufferedPacket> ReliablePacketBuffer::getTimedOuts(float timeout,
424 unsigned int max_packets)
426 MutexAutoLock listlock(m_list_mutex);
427 std::list<BufferedPacket> timed_outs;
428 for(std::list<BufferedPacket>::iterator i = m_list.begin();
429 i != m_list.end(); ++i)
431 if (i->time >= timeout) {
432 timed_outs.push_back(*i);
434 //this packet will be sent right afterwards reset timeout here
436 if (timed_outs.size() >= max_packets)
447 IncomingSplitBuffer::~IncomingSplitBuffer()
449 MutexAutoLock listlock(m_map_mutex);
450 for(std::map<u16, IncomingSplitPacket*>::iterator i = m_buf.begin();
451 i != m_buf.end(); ++i)
457 This will throw a GotSplitPacketException when a full
458 split packet is constructed.
460 SharedBuffer<u8> IncomingSplitBuffer::insert(BufferedPacket &p, bool reliable)
462 MutexAutoLock listlock(m_map_mutex);
463 u32 headersize = BASE_HEADER_SIZE + 7;
464 if (p.data.getSize() < headersize) {
465 errorstream << "Invalid data size for split packet" << std::endl;
466 return SharedBuffer<u8>();
468 u8 type = readU8(&p.data[BASE_HEADER_SIZE+0]);
469 u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]);
470 u16 chunk_count = readU16(&p.data[BASE_HEADER_SIZE+3]);
471 u16 chunk_num = readU16(&p.data[BASE_HEADER_SIZE+5]);
473 if (type != TYPE_SPLIT) {
474 errorstream << "IncomingSplitBuffer::insert(): type is not split"
476 return SharedBuffer<u8>();
479 // Add if doesn't exist
480 if (m_buf.find(seqnum) == m_buf.end())
482 IncomingSplitPacket *sp = new IncomingSplitPacket();
483 sp->chunk_count = chunk_count;
484 sp->reliable = reliable;
488 IncomingSplitPacket *sp = m_buf[seqnum];
490 // TODO: These errors should be thrown or something? Dunno.
491 if (chunk_count != sp->chunk_count)
492 LOG(derr_con<<"Connection: WARNING: chunk_count="<<chunk_count
493 <<" != sp->chunk_count="<<sp->chunk_count
495 if (reliable != sp->reliable)
496 LOG(derr_con<<"Connection: WARNING: reliable="<<reliable
497 <<" != sp->reliable="<<sp->reliable
500 // If chunk already exists, ignore it.
501 // Sometimes two identical packets may arrive when there is network
502 // lag and the server re-sends stuff.
503 if (sp->chunks.find(chunk_num) != sp->chunks.end())
504 return SharedBuffer<u8>();
506 // Cut chunk data out of packet
507 u32 chunkdatasize = p.data.getSize() - headersize;
508 SharedBuffer<u8> chunkdata(chunkdatasize);
509 memcpy(*chunkdata, &(p.data[headersize]), chunkdatasize);
511 // Set chunk data in buffer
512 sp->chunks[chunk_num] = chunkdata;
514 // If not all chunks are received, return empty buffer
515 if (sp->allReceived() == false)
516 return SharedBuffer<u8>();
518 // Calculate total size
520 for(std::map<u16, SharedBuffer<u8> >::iterator i = sp->chunks.begin();
521 i != sp->chunks.end(); ++i)
523 totalsize += i->second.getSize();
526 SharedBuffer<u8> fulldata(totalsize);
528 // Copy chunks to data buffer
530 for(u32 chunk_i=0; chunk_i<sp->chunk_count;
533 SharedBuffer<u8> buf = sp->chunks[chunk_i];
534 u16 chunkdatasize = buf.getSize();
535 memcpy(&fulldata[start], *buf, chunkdatasize);
536 start += chunkdatasize;;
539 // Remove sp from buffer
545 void IncomingSplitBuffer::removeUnreliableTimedOuts(float dtime, float timeout)
547 std::list<u16> remove_queue;
549 MutexAutoLock listlock(m_map_mutex);
550 for(std::map<u16, IncomingSplitPacket*>::iterator i = m_buf.begin();
551 i != m_buf.end(); ++i)
553 IncomingSplitPacket *p = i->second;
554 // Reliable ones are not removed by timeout
555 if (p->reliable == true)
558 if (p->time >= timeout)
559 remove_queue.push_back(i->first);
562 for(std::list<u16>::iterator j = remove_queue.begin();
563 j != remove_queue.end(); ++j)
565 MutexAutoLock listlock(m_map_mutex);
566 LOG(dout_con<<"NOTE: Removing timed out unreliable split packet"<<std::endl);
577 window_size(MIN_RELIABLE_WINDOW_SIZE),
578 next_incoming_seqnum(SEQNUM_INITIAL),
579 next_outgoing_seqnum(SEQNUM_INITIAL),
580 next_outgoing_split_seqnum(SEQNUM_INITIAL),
581 current_packet_loss(0),
582 current_packet_too_late(0),
583 current_packet_successfull(0),
584 packet_loss_counter(0),
585 current_bytes_transfered(0),
586 current_bytes_received(0),
587 current_bytes_lost(0),
591 max_incoming_kbps(0.0),
592 cur_incoming_kbps(0.0),
593 avg_incoming_kbps(0.0),
606 u16 Channel::readNextIncomingSeqNum()
608 MutexAutoLock internal(m_internal_mutex);
609 return next_incoming_seqnum;
612 u16 Channel::incNextIncomingSeqNum()
614 MutexAutoLock internal(m_internal_mutex);
615 u16 retval = next_incoming_seqnum;
616 next_incoming_seqnum++;
620 u16 Channel::readNextSplitSeqNum()
622 MutexAutoLock internal(m_internal_mutex);
623 return next_outgoing_split_seqnum;
625 void Channel::setNextSplitSeqNum(u16 seqnum)
627 MutexAutoLock internal(m_internal_mutex);
628 next_outgoing_split_seqnum = seqnum;
631 u16 Channel::getOutgoingSequenceNumber(bool& successful)
633 MutexAutoLock internal(m_internal_mutex);
634 u16 retval = next_outgoing_seqnum;
635 u16 lowest_unacked_seqnumber;
637 /* shortcut if there ain't any packet in outgoing list */
638 if (outgoing_reliables_sent.empty())
640 next_outgoing_seqnum++;
644 if (outgoing_reliables_sent.getFirstSeqnum(lowest_unacked_seqnumber))
646 if (lowest_unacked_seqnumber < next_outgoing_seqnum) {
647 // ugly cast but this one is required in order to tell compiler we
648 // know about difference of two unsigned may be negative in general
649 // but we already made sure it won't happen in this case
650 if (((u16)(next_outgoing_seqnum - lowest_unacked_seqnumber)) > window_size) {
656 // ugly cast but this one is required in order to tell compiler we
657 // know about difference of two unsigned may be negative in general
658 // but we already made sure it won't happen in this case
659 if ((next_outgoing_seqnum + (u16)(SEQNUM_MAX - lowest_unacked_seqnumber)) >
667 next_outgoing_seqnum++;
671 u16 Channel::readOutgoingSequenceNumber()
673 MutexAutoLock internal(m_internal_mutex);
674 return next_outgoing_seqnum;
677 bool Channel::putBackSequenceNumber(u16 seqnum)
679 if (((seqnum + 1) % (SEQNUM_MAX+1)) == next_outgoing_seqnum) {
681 next_outgoing_seqnum = seqnum;
687 void Channel::UpdateBytesSent(unsigned int bytes, unsigned int packets)
689 MutexAutoLock internal(m_internal_mutex);
690 current_bytes_transfered += bytes;
691 current_packet_successfull += packets;
694 void Channel::UpdateBytesReceived(unsigned int bytes) {
695 MutexAutoLock internal(m_internal_mutex);
696 current_bytes_received += bytes;
699 void Channel::UpdateBytesLost(unsigned int bytes)
701 MutexAutoLock internal(m_internal_mutex);
702 current_bytes_lost += bytes;
706 void Channel::UpdatePacketLossCounter(unsigned int count)
708 MutexAutoLock internal(m_internal_mutex);
709 current_packet_loss += count;
712 void Channel::UpdatePacketTooLateCounter()
714 MutexAutoLock internal(m_internal_mutex);
715 current_packet_too_late++;
718 void Channel::UpdateTimers(float dtime,bool legacy_peer)
720 bpm_counter += dtime;
721 packet_loss_counter += dtime;
723 if (packet_loss_counter > 1.0)
725 packet_loss_counter -= 1.0;
727 unsigned int packet_loss = 11; /* use a neutral value for initialization */
728 unsigned int packets_successfull = 0;
729 //unsigned int packet_too_late = 0;
731 bool reasonable_amount_of_data_transmitted = false;
734 MutexAutoLock internal(m_internal_mutex);
735 packet_loss = current_packet_loss;
736 //packet_too_late = current_packet_too_late;
737 packets_successfull = current_packet_successfull;
739 if (current_bytes_transfered > (unsigned int) (window_size*512/2))
741 reasonable_amount_of_data_transmitted = true;
743 current_packet_loss = 0;
744 current_packet_too_late = 0;
745 current_packet_successfull = 0;
748 /* dynamic window size is only available for non legacy peers */
750 float successfull_to_lost_ratio = 0.0;
753 if (packets_successfull > 0) {
754 successfull_to_lost_ratio = packet_loss/packets_successfull;
756 else if (packet_loss > 0)
760 MIN_RELIABLE_WINDOW_SIZE);
766 if ((successfull_to_lost_ratio < 0.01) &&
767 (window_size < MAX_RELIABLE_WINDOW_SIZE))
769 /* don't even think about increasing if we didn't even
770 * use major parts of our window */
771 if (reasonable_amount_of_data_transmitted)
774 MAX_RELIABLE_WINDOW_SIZE);
776 else if ((successfull_to_lost_ratio < 0.05) &&
777 (window_size < MAX_RELIABLE_WINDOW_SIZE))
779 /* don't even think about increasing if we didn't even
780 * use major parts of our window */
781 if (reasonable_amount_of_data_transmitted)
784 MAX_RELIABLE_WINDOW_SIZE);
786 else if (successfull_to_lost_ratio > 0.15)
790 MIN_RELIABLE_WINDOW_SIZE);
792 else if (successfull_to_lost_ratio > 0.1)
796 MIN_RELIABLE_WINDOW_SIZE);
802 if (bpm_counter > 10.0)
805 MutexAutoLock internal(m_internal_mutex);
807 (((float) current_bytes_transfered)/bpm_counter)/1024.0;
808 current_bytes_transfered = 0;
810 (((float) current_bytes_lost)/bpm_counter)/1024.0;
811 current_bytes_lost = 0;
813 (((float) current_bytes_received)/bpm_counter)/1024.0;
814 current_bytes_received = 0;
818 if (cur_kbps > max_kbps)
823 if (cur_kbps_lost > max_kbps_lost)
825 max_kbps_lost = cur_kbps_lost;
828 if (cur_incoming_kbps > max_incoming_kbps) {
829 max_incoming_kbps = cur_incoming_kbps;
832 rate_samples = MYMIN(rate_samples+1,10);
833 float old_fraction = ((float) (rate_samples-1) )/( (float) rate_samples);
834 avg_kbps = avg_kbps * old_fraction +
835 cur_kbps * (1.0 - old_fraction);
836 avg_kbps_lost = avg_kbps_lost * old_fraction +
837 cur_kbps_lost * (1.0 - old_fraction);
838 avg_incoming_kbps = avg_incoming_kbps * old_fraction +
839 cur_incoming_kbps * (1.0 - old_fraction);
848 PeerHelper::PeerHelper() :
852 PeerHelper::PeerHelper(Peer* peer) :
857 if (!peer->IncUseCount())
864 PeerHelper::~PeerHelper()
867 m_peer->DecUseCount();
872 PeerHelper& PeerHelper::operator=(Peer* peer)
877 if (!peer->IncUseCount())
885 Peer* PeerHelper::operator->() const
890 Peer* PeerHelper::operator&() const
895 bool PeerHelper::operator!() {
899 bool PeerHelper::operator!=(void* ptr)
901 return ((void*) m_peer != ptr);
904 bool Peer::IncUseCount()
906 MutexAutoLock lock(m_exclusive_access_mutex);
908 if (!m_pending_deletion)
917 void Peer::DecUseCount()
920 MutexAutoLock lock(m_exclusive_access_mutex);
921 sanity_check(m_usage > 0);
924 if (!((m_pending_deletion) && (m_usage == 0)))
930 void Peer::RTTStatistics(float rtt, std::string profiler_id,
931 unsigned int num_samples) {
933 if (m_last_rtt > 0) {
934 /* set min max values */
935 if (rtt < m_rtt.min_rtt)
937 if (rtt >= m_rtt.max_rtt)
940 /* do average calculation */
941 if (m_rtt.avg_rtt < 0.0)
944 m_rtt.avg_rtt = m_rtt.avg_rtt * (num_samples/(num_samples-1)) +
945 rtt * (1/num_samples);
947 /* do jitter calculation */
949 //just use some neutral value at beginning
950 float jitter = m_rtt.jitter_min;
952 if (rtt > m_last_rtt)
953 jitter = rtt-m_last_rtt;
955 if (rtt <= m_last_rtt)
956 jitter = m_last_rtt - rtt;
958 if (jitter < m_rtt.jitter_min)
959 m_rtt.jitter_min = jitter;
960 if (jitter >= m_rtt.jitter_max)
961 m_rtt.jitter_max = jitter;
963 if (m_rtt.jitter_avg < 0.0)
964 m_rtt.jitter_avg = jitter;
966 m_rtt.jitter_avg = m_rtt.jitter_avg * (num_samples/(num_samples-1)) +
967 jitter * (1/num_samples);
969 if (profiler_id != "")
971 g_profiler->graphAdd(profiler_id + "_rtt", rtt);
972 g_profiler->graphAdd(profiler_id + "_jitter", jitter);
975 /* save values required for next loop */
979 bool Peer::isTimedOut(float timeout)
981 MutexAutoLock lock(m_exclusive_access_mutex);
982 u32 current_time = porting::getTimeMs();
984 float dtime = CALC_DTIME(m_last_timeout_check,current_time);
985 m_last_timeout_check = current_time;
987 m_timeout_counter += dtime;
989 return m_timeout_counter > timeout;
995 MutexAutoLock usage_lock(m_exclusive_access_mutex);
996 m_pending_deletion = true;
1001 PROFILE(std::stringstream peerIdentifier1);
1002 PROFILE(peerIdentifier1 << "runTimeouts[" << m_connection->getDesc()
1003 << ";" << id << ";RELIABLE]");
1004 PROFILE(g_profiler->remove(peerIdentifier1.str()));
1005 PROFILE(std::stringstream peerIdentifier2);
1006 PROFILE(peerIdentifier2 << "sendPackets[" << m_connection->getDesc()
1007 << ";" << id << ";RELIABLE]");
1008 PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier2.str(), SPT_AVG));
1013 UDPPeer::UDPPeer(u16 a_id, Address a_address, Connection* connection) :
1014 Peer(a_address,a_id,connection),
1015 m_pending_disconnect(false),
1016 resend_timeout(0.5),
1021 bool UDPPeer::getAddress(MTProtocols type,Address& toset)
1023 if ((type == MTP_UDP) || (type == MTP_MINETEST_RELIABLE_UDP) || (type == MTP_PRIMARY))
1032 void UDPPeer::setNonLegacyPeer()
1034 m_legacy_peer = false;
1035 for(unsigned int i=0; i< CHANNEL_COUNT; i++)
1037 channels->setWindowSize(g_settings->getU16("max_packets_per_iteration"));
1041 void UDPPeer::reportRTT(float rtt)
1046 RTTStatistics(rtt,"rudp",MAX_RELIABLE_WINDOW_SIZE*10);
1048 float timeout = getStat(AVG_RTT) * RESEND_TIMEOUT_FACTOR;
1049 if (timeout < RESEND_TIMEOUT_MIN)
1050 timeout = RESEND_TIMEOUT_MIN;
1051 if (timeout > RESEND_TIMEOUT_MAX)
1052 timeout = RESEND_TIMEOUT_MAX;
1054 MutexAutoLock usage_lock(m_exclusive_access_mutex);
1055 resend_timeout = timeout;
1058 bool UDPPeer::Ping(float dtime,SharedBuffer<u8>& data)
1060 m_ping_timer += dtime;
1061 if (m_ping_timer >= PING_TIMEOUT)
1063 // Create and send PING packet
1064 writeU8(&data[0], TYPE_CONTROL);
1065 writeU8(&data[1], CONTROLTYPE_PING);
1072 void UDPPeer::PutReliableSendCommand(ConnectionCommand &c,
1073 unsigned int max_packet_size)
1075 if (m_pending_disconnect)
1078 if ( channels[c.channelnum].queued_commands.empty() &&
1079 /* don't queue more packets then window size */
1080 (channels[c.channelnum].queued_reliables.size()
1081 < (channels[c.channelnum].getWindowSize()/2))) {
1082 LOG(dout_con<<m_connection->getDesc()
1083 <<" processing reliable command for peer id: " << c.peer_id
1084 <<" data size: " << c.data.getSize() << std::endl);
1085 if (!processReliableSendCommand(c,max_packet_size)) {
1086 channels[c.channelnum].queued_commands.push_back(c);
1090 LOG(dout_con<<m_connection->getDesc()
1091 <<" Queueing reliable command for peer id: " << c.peer_id
1092 <<" data size: " << c.data.getSize() <<std::endl);
1093 channels[c.channelnum].queued_commands.push_back(c);
1097 bool UDPPeer::processReliableSendCommand(
1098 ConnectionCommand &c,
1099 unsigned int max_packet_size)
1101 if (m_pending_disconnect)
1104 u32 chunksize_max = max_packet_size
1106 - RELIABLE_HEADER_SIZE;
1108 sanity_check(c.data.getSize() < MAX_RELIABLE_WINDOW_SIZE*512);
1110 std::list<SharedBuffer<u8> > originals;
1111 u16 split_sequence_number = channels[c.channelnum].readNextSplitSeqNum();
1115 originals.push_back(c.data);
1118 originals = makeAutoSplitPacket(c.data, chunksize_max,split_sequence_number);
1119 channels[c.channelnum].setNextSplitSeqNum(split_sequence_number);
1122 bool have_sequence_number = true;
1123 bool have_initial_sequence_number = false;
1124 std::queue<BufferedPacket> toadd;
1125 volatile u16 initial_sequence_number = 0;
1127 for(std::list<SharedBuffer<u8> >::iterator i = originals.begin();
1128 i != originals.end(); ++i)
1130 u16 seqnum = channels[c.channelnum].getOutgoingSequenceNumber(have_sequence_number);
1132 /* oops, we don't have enough sequence numbers to send this packet */
1133 if (!have_sequence_number)
1136 if (!have_initial_sequence_number)
1138 initial_sequence_number = seqnum;
1139 have_initial_sequence_number = true;
1142 SharedBuffer<u8> reliable = makeReliablePacket(*i, seqnum);
1144 // Add base headers and make a packet
1145 BufferedPacket p = con::makePacket(address, reliable,
1146 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1152 if (have_sequence_number) {
1153 volatile u16 pcount = 0;
1154 while(toadd.size() > 0) {
1155 BufferedPacket p = toadd.front();
1157 // LOG(dout_con<<connection->getDesc()
1158 // << " queuing reliable packet for peer_id: " << c.peer_id
1159 // << " channel: " << (c.channelnum&0xFF)
1160 // << " seqnum: " << readU16(&p.data[BASE_HEADER_SIZE+1])
1162 channels[c.channelnum].queued_reliables.push(p);
1165 sanity_check(channels[c.channelnum].queued_reliables.size() < 0xFFFF);
1169 volatile u16 packets_available = toadd.size();
1170 /* we didn't get a single sequence number no need to fill queue */
1171 if (!have_initial_sequence_number)
1175 while(toadd.size() > 0) {
1179 bool successfully_put_back_sequence_number
1180 = channels[c.channelnum].putBackSequenceNumber(
1181 (initial_sequence_number+toadd.size() % (SEQNUM_MAX+1)));
1183 FATAL_ERROR_IF(!successfully_put_back_sequence_number, "error");
1185 LOG(dout_con<<m_connection->getDesc()
1186 << " Windowsize exceeded on reliable sending "
1187 << c.data.getSize() << " bytes"
1188 << std::endl << "\t\tinitial_sequence_number: "
1189 << initial_sequence_number
1190 << std::endl << "\t\tgot at most : "
1191 << packets_available << " packets"
1192 << std::endl << "\t\tpackets queued : "
1193 << channels[c.channelnum].outgoing_reliables_sent.size()
1199 void UDPPeer::RunCommandQueues(
1200 unsigned int max_packet_size,
1201 unsigned int maxcommands,
1202 unsigned int maxtransfer)
1205 for (unsigned int i = 0; i < CHANNEL_COUNT; i++) {
1206 unsigned int commands_processed = 0;
1208 if ((channels[i].queued_commands.size() > 0) &&
1209 (channels[i].queued_reliables.size() < maxtransfer) &&
1210 (commands_processed < maxcommands)) {
1212 ConnectionCommand c = channels[i].queued_commands.front();
1214 LOG(dout_con << m_connection->getDesc()
1215 << " processing queued reliable command " << std::endl);
1217 // Packet is processed, remove it from queue
1218 if (processReliableSendCommand(c,max_packet_size)) {
1219 channels[i].queued_commands.pop_front();
1221 LOG(dout_con << m_connection->getDesc()
1222 << " Failed to queue packets for peer_id: " << c.peer_id
1223 << ", delaying sending of " << c.data.getSize()
1224 << " bytes" << std::endl);
1227 catch (ItemNotFoundException &e) {
1228 // intentionally empty
1234 u16 UDPPeer::getNextSplitSequenceNumber(u8 channel)
1236 assert(channel < CHANNEL_COUNT); // Pre-condition
1237 return channels[channel].readNextIncomingSeqNum();
1240 void UDPPeer::setNextSplitSequenceNumber(u8 channel, u16 seqnum)
1242 assert(channel < CHANNEL_COUNT); // Pre-condition
1243 channels[channel].setNextSplitSeqNum(seqnum);
1246 SharedBuffer<u8> UDPPeer::addSpiltPacket(u8 channel,
1247 BufferedPacket toadd,
1250 assert(channel < CHANNEL_COUNT); // Pre-condition
1251 return channels[channel].incoming_splits.insert(toadd,reliable);
1254 /******************************************************************************/
1255 /* Connection Threads */
1256 /******************************************************************************/
1258 ConnectionSendThread::ConnectionSendThread(unsigned int max_packet_size,
1260 Thread("ConnectionSend"),
1262 m_max_packet_size(max_packet_size),
1264 m_max_commands_per_iteration(1),
1265 m_max_data_packets_per_iteration(g_settings->getU16("max_packets_per_iteration")),
1266 m_max_packets_requeued(256)
1270 void * ConnectionSendThread::run()
1272 assert(m_connection);
1274 LOG(dout_con<<m_connection->getDesc()
1275 <<"ConnectionSend thread started"<<std::endl);
1277 u32 curtime = porting::getTimeMs();
1278 u32 lasttime = curtime;
1280 PROFILE(std::stringstream ThreadIdentifier);
1281 PROFILE(ThreadIdentifier << "ConnectionSend: [" << m_connection->getDesc() << "]");
1283 /* if stop is requested don't stop immediately but try to send all */
1285 while(!stopRequested() || packetsQueued()) {
1286 BEGIN_DEBUG_EXCEPTION_HANDLER
1287 PROFILE(ScopeProfiler sp(g_profiler, ThreadIdentifier.str(), SPT_AVG));
1289 m_iteration_packets_avaialble = m_max_data_packets_per_iteration;
1291 /* wait for trigger or timeout */
1292 m_send_sleep_semaphore.wait(50);
1294 /* remove all triggers */
1295 while(m_send_sleep_semaphore.wait(0)) {}
1298 curtime = porting::getTimeMs();
1299 float dtime = CALC_DTIME(lasttime,curtime);
1301 /* first do all the reliable stuff */
1304 /* translate commands to packets */
1305 ConnectionCommand c = m_connection->m_command_queue.pop_frontNoEx(0);
1306 while(c.type != CONNCMD_NONE)
1309 processReliableCommand(c);
1311 processNonReliableCommand(c);
1313 c = m_connection->m_command_queue.pop_frontNoEx(0);
1316 /* send non reliable packets */
1319 END_DEBUG_EXCEPTION_HANDLER(errorstream);
1322 PROFILE(g_profiler->remove(ThreadIdentifier.str()));
1326 void ConnectionSendThread::Trigger()
1328 m_send_sleep_semaphore.post();
1331 bool ConnectionSendThread::packetsQueued()
1333 std::list<u16> peerIds = m_connection->getPeerIDs();
1335 if (!m_outgoing_queue.empty() && !peerIds.empty())
1338 for(std::list<u16>::iterator j = peerIds.begin();
1339 j != peerIds.end(); ++j)
1341 PeerHelper peer = m_connection->getPeerNoEx(*j);
1346 if (dynamic_cast<UDPPeer*>(&peer) == 0)
1349 for(u16 i=0; i < CHANNEL_COUNT; i++) {
1350 Channel *channel = &(dynamic_cast<UDPPeer*>(&peer))->channels[i];
1352 if (channel->queued_commands.size() > 0) {
1362 void ConnectionSendThread::runTimeouts(float dtime)
1364 std::list<u16> timeouted_peers;
1365 std::list<u16> peerIds = m_connection->getPeerIDs();
1367 for(std::list<u16>::iterator j = peerIds.begin();
1368 j != peerIds.end(); ++j)
1370 PeerHelper peer = m_connection->getPeerNoEx(*j);
1375 if (dynamic_cast<UDPPeer*>(&peer) == 0)
1378 PROFILE(std::stringstream peerIdentifier);
1379 PROFILE(peerIdentifier << "runTimeouts[" << m_connection->getDesc()
1380 << ";" << *j << ";RELIABLE]");
1381 PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier.str(), SPT_AVG));
1383 SharedBuffer<u8> data(2); // data for sending ping, required here because of goto
1388 if (peer->isTimedOut(m_timeout))
1390 infostream<<m_connection->getDesc()
1391 <<"RunTimeouts(): Peer "<<peer->id
1393 <<" (source=peer->timeout_counter)"
1395 // Add peer to the list
1396 timeouted_peers.push_back(peer->id);
1397 // Don't bother going through the buffers of this one
1401 float resend_timeout = dynamic_cast<UDPPeer*>(&peer)->getResendTimeout();
1402 for(u16 i=0; i<CHANNEL_COUNT; i++)
1404 std::list<BufferedPacket> timed_outs;
1405 Channel *channel = &(dynamic_cast<UDPPeer*>(&peer))->channels[i];
1407 if (dynamic_cast<UDPPeer*>(&peer)->getLegacyPeer())
1408 channel->setWindowSize(g_settings->getU16("workaround_window_size"));
1410 // Remove timed out incomplete unreliable split packets
1411 channel->incoming_splits.removeUnreliableTimedOuts(dtime, m_timeout);
1413 // Increment reliable packet times
1414 channel->outgoing_reliables_sent.incrementTimeouts(dtime);
1416 unsigned int numpeers = m_connection->m_peers.size();
1421 // Re-send timed out outgoing reliables
1422 timed_outs = channel->
1423 outgoing_reliables_sent.getTimedOuts(resend_timeout,
1424 (m_max_data_packets_per_iteration/numpeers));
1426 channel->UpdatePacketLossCounter(timed_outs.size());
1427 g_profiler->graphAdd("packets_lost", timed_outs.size());
1429 m_iteration_packets_avaialble -= timed_outs.size();
1431 for(std::list<BufferedPacket>::iterator k = timed_outs.begin();
1432 k != timed_outs.end(); ++k)
1434 u16 peer_id = readPeerId(*(k->data));
1435 u8 channelnum = readChannel(*(k->data));
1436 u16 seqnum = readU16(&(k->data[BASE_HEADER_SIZE+1]));
1438 channel->UpdateBytesLost(k->data.getSize());
1441 LOG(derr_con<<m_connection->getDesc()
1442 <<"RE-SENDING timed-out RELIABLE to "
1443 << k->address.serializeString()
1444 << "(t/o="<<resend_timeout<<"): "
1445 <<"from_peer_id="<<peer_id
1446 <<", channel="<<((int)channelnum&0xff)
1447 <<", seqnum="<<seqnum
1452 // do not handle rtt here as we can't decide if this packet was
1453 // lost or really takes more time to transmit
1455 channel->UpdateTimers(dtime,dynamic_cast<UDPPeer*>(&peer)->getLegacyPeer());
1458 /* send ping if necessary */
1459 if (dynamic_cast<UDPPeer*>(&peer)->Ping(dtime,data)) {
1460 LOG(dout_con<<m_connection->getDesc()
1461 <<"Sending ping for peer_id: "
1462 << dynamic_cast<UDPPeer*>(&peer)->id <<std::endl);
1463 /* this may fail if there ain't a sequence number left */
1464 if (!rawSendAsPacket(dynamic_cast<UDPPeer*>(&peer)->id, 0, data, true))
1466 //retrigger with reduced ping interval
1467 dynamic_cast<UDPPeer*>(&peer)->Ping(4.0,data);
1471 dynamic_cast<UDPPeer*>(&peer)->RunCommandQueues(m_max_packet_size,
1472 m_max_commands_per_iteration,
1473 m_max_packets_requeued);
1476 // Remove timed out peers
1477 for(std::list<u16>::iterator i = timeouted_peers.begin();
1478 i != timeouted_peers.end(); ++i)
1480 LOG(derr_con<<m_connection->getDesc()
1481 <<"RunTimeouts(): Removing peer "<<(*i)<<std::endl);
1482 m_connection->deletePeer(*i, true);
1486 void ConnectionSendThread::rawSend(const BufferedPacket &packet)
1489 m_connection->m_udpSocket.Send(packet.address, *packet.data,
1490 packet.data.getSize());
1491 LOG(dout_con <<m_connection->getDesc()
1492 << " rawSend: " << packet.data.getSize()
1493 << " bytes sent" << std::endl);
1494 } catch(SendFailedException &e) {
1495 LOG(derr_con<<m_connection->getDesc()
1496 <<"Connection::rawSend(): SendFailedException: "
1497 <<packet.address.serializeString()<<std::endl);
1501 void ConnectionSendThread::sendAsPacketReliable(BufferedPacket& p, Channel* channel)
1504 p.absolute_send_time = porting::getTimeMs();
1505 // Buffer the packet
1506 channel->outgoing_reliables_sent.insert(p,
1507 (channel->readOutgoingSequenceNumber() - MAX_RELIABLE_WINDOW_SIZE)
1508 % (MAX_RELIABLE_WINDOW_SIZE+1));
1510 catch(AlreadyExistsException &e)
1512 LOG(derr_con<<m_connection->getDesc()
1513 <<"WARNING: Going to send a reliable packet"
1514 <<" in outgoing buffer" <<std::endl);
1521 bool ConnectionSendThread::rawSendAsPacket(u16 peer_id, u8 channelnum,
1522 SharedBuffer<u8> data, bool reliable)
1524 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
1526 LOG(dout_con<<m_connection->getDesc()
1527 <<" INFO: dropped packet for non existent peer_id: "
1528 << peer_id << std::endl);
1529 FATAL_ERROR_IF(!reliable, "Trying to send raw packet reliable but no peer found!");
1532 Channel *channel = &(dynamic_cast<UDPPeer*>(&peer)->channels[channelnum]);
1536 bool have_sequence_number_for_raw_packet = true;
1538 channel->getOutgoingSequenceNumber(have_sequence_number_for_raw_packet);
1540 if (!have_sequence_number_for_raw_packet)
1543 SharedBuffer<u8> reliable = makeReliablePacket(data, seqnum);
1544 Address peer_address;
1545 peer->getAddress(MTP_MINETEST_RELIABLE_UDP, peer_address);
1547 // Add base headers and make a packet
1548 BufferedPacket p = con::makePacket(peer_address, reliable,
1549 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1552 // first check if our send window is already maxed out
1553 if (channel->outgoing_reliables_sent.size()
1554 < channel->getWindowSize()) {
1555 LOG(dout_con<<m_connection->getDesc()
1556 <<" INFO: sending a reliable packet to peer_id " << peer_id
1557 <<" channel: " << channelnum
1558 <<" seqnum: " << seqnum << std::endl);
1559 sendAsPacketReliable(p,channel);
1563 LOG(dout_con<<m_connection->getDesc()
1564 <<" INFO: queueing reliable packet for peer_id: " << peer_id
1565 <<" channel: " << channelnum
1566 <<" seqnum: " << seqnum << std::endl);
1567 channel->queued_reliables.push(p);
1573 Address peer_address;
1575 if (peer->getAddress(MTP_UDP, peer_address))
1577 // Add base headers and make a packet
1578 BufferedPacket p = con::makePacket(peer_address, data,
1579 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1587 LOG(dout_con<<m_connection->getDesc()
1588 <<" INFO: dropped unreliable packet for peer_id: " << peer_id
1589 <<" because of (yet) missing udp address" << std::endl);
1598 void ConnectionSendThread::processReliableCommand(ConnectionCommand &c)
1600 assert(c.reliable); // Pre-condition
1604 LOG(dout_con<<m_connection->getDesc()
1605 <<"UDP processing reliable CONNCMD_NONE"<<std::endl);
1609 LOG(dout_con<<m_connection->getDesc()
1610 <<"UDP processing reliable CONNCMD_SEND"<<std::endl);
1614 case CONNCMD_SEND_TO_ALL:
1615 LOG(dout_con<<m_connection->getDesc()
1616 <<"UDP processing CONNCMD_SEND_TO_ALL"<<std::endl);
1617 sendToAllReliable(c);
1620 case CONCMD_CREATE_PEER:
1621 LOG(dout_con<<m_connection->getDesc()
1622 <<"UDP processing reliable CONCMD_CREATE_PEER"<<std::endl);
1623 if (!rawSendAsPacket(c.peer_id,c.channelnum,c.data,c.reliable))
1625 /* put to queue if we couldn't send it immediately */
1630 case CONCMD_DISABLE_LEGACY:
1631 LOG(dout_con<<m_connection->getDesc()
1632 <<"UDP processing reliable CONCMD_DISABLE_LEGACY"<<std::endl);
1633 if (!rawSendAsPacket(c.peer_id,c.channelnum,c.data,c.reliable))
1635 /* put to queue if we couldn't send it immediately */
1641 case CONNCMD_CONNECT:
1642 case CONNCMD_DISCONNECT:
1644 FATAL_ERROR("Got command that shouldn't be reliable as reliable command");
1646 LOG(dout_con<<m_connection->getDesc()
1647 <<" Invalid reliable command type: " << c.type <<std::endl);
1652 void ConnectionSendThread::processNonReliableCommand(ConnectionCommand &c)
1654 assert(!c.reliable); // Pre-condition
1658 LOG(dout_con<<m_connection->getDesc()
1659 <<" UDP processing CONNCMD_NONE"<<std::endl);
1662 LOG(dout_con<<m_connection->getDesc()
1663 <<" UDP processing CONNCMD_SERVE port="
1664 <<c.address.serializeString()<<std::endl);
1667 case CONNCMD_CONNECT:
1668 LOG(dout_con<<m_connection->getDesc()
1669 <<" UDP processing CONNCMD_CONNECT"<<std::endl);
1672 case CONNCMD_DISCONNECT:
1673 LOG(dout_con<<m_connection->getDesc()
1674 <<" UDP processing CONNCMD_DISCONNECT"<<std::endl);
1677 case CONNCMD_DISCONNECT_PEER:
1678 LOG(dout_con<<m_connection->getDesc()
1679 <<" UDP processing CONNCMD_DISCONNECT_PEER"<<std::endl);
1680 disconnect_peer(c.peer_id);
1683 LOG(dout_con<<m_connection->getDesc()
1684 <<" UDP processing CONNCMD_SEND"<<std::endl);
1685 send(c.peer_id, c.channelnum, c.data);
1687 case CONNCMD_SEND_TO_ALL:
1688 LOG(dout_con<<m_connection->getDesc()
1689 <<" UDP processing CONNCMD_SEND_TO_ALL"<<std::endl);
1690 sendToAll(c.channelnum, c.data);
1693 LOG(dout_con<<m_connection->getDesc()
1694 <<" UDP processing CONCMD_ACK"<<std::endl);
1695 sendAsPacket(c.peer_id,c.channelnum,c.data,true);
1697 case CONCMD_CREATE_PEER:
1698 FATAL_ERROR("Got command that should be reliable as unreliable command");
1700 LOG(dout_con<<m_connection->getDesc()
1701 <<" Invalid command type: " << c.type <<std::endl);
1705 void ConnectionSendThread::serve(Address bind_address)
1707 LOG(dout_con<<m_connection->getDesc()
1708 <<"UDP serving at port " << bind_address.serializeString() <<std::endl);
1710 m_connection->m_udpSocket.Bind(bind_address);
1711 m_connection->SetPeerID(PEER_ID_SERVER);
1713 catch(SocketException &e) {
1717 m_connection->putEvent(ce);
1721 void ConnectionSendThread::connect(Address address)
1723 LOG(dout_con<<m_connection->getDesc()<<" connecting to "<<address.serializeString()
1724 <<":"<<address.getPort()<<std::endl);
1726 UDPPeer *peer = m_connection->createServerPeer(address);
1730 e.peerAdded(peer->id, peer->address);
1731 m_connection->putEvent(e);
1735 if (address.isIPv6())
1736 bind_addr.setAddress((IPv6AddressBytes*) NULL);
1738 bind_addr.setAddress(0,0,0,0);
1740 m_connection->m_udpSocket.Bind(bind_addr);
1742 // Send a dummy packet to server with peer_id = PEER_ID_INEXISTENT
1743 m_connection->SetPeerID(PEER_ID_INEXISTENT);
1744 NetworkPacket pkt(0,0);
1745 m_connection->Send(PEER_ID_SERVER, 0, &pkt, true);
1748 void ConnectionSendThread::disconnect()
1750 LOG(dout_con<<m_connection->getDesc()<<" disconnecting"<<std::endl);
1752 // Create and send DISCO packet
1753 SharedBuffer<u8> data(2);
1754 writeU8(&data[0], TYPE_CONTROL);
1755 writeU8(&data[1], CONTROLTYPE_DISCO);
1759 std::list<u16> peerids = m_connection->getPeerIDs();
1761 for (std::list<u16>::iterator i = peerids.begin();
1765 sendAsPacket(*i, 0,data,false);
1769 void ConnectionSendThread::disconnect_peer(u16 peer_id)
1771 LOG(dout_con<<m_connection->getDesc()<<" disconnecting peer"<<std::endl);
1773 // Create and send DISCO packet
1774 SharedBuffer<u8> data(2);
1775 writeU8(&data[0], TYPE_CONTROL);
1776 writeU8(&data[1], CONTROLTYPE_DISCO);
1777 sendAsPacket(peer_id, 0,data,false);
1779 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
1784 if (dynamic_cast<UDPPeer*>(&peer) == 0)
1789 dynamic_cast<UDPPeer*>(&peer)->m_pending_disconnect = true;
1792 void ConnectionSendThread::send(u16 peer_id, u8 channelnum,
1793 SharedBuffer<u8> data)
1795 assert(channelnum < CHANNEL_COUNT); // Pre-condition
1797 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
1800 LOG(dout_con<<m_connection->getDesc()<<" peer: peer_id="<<peer_id
1801 << ">>>NOT<<< found on sending packet"
1802 << ", channel " << (channelnum % 0xFF)
1803 << ", size: " << data.getSize() <<std::endl);
1807 LOG(dout_con<<m_connection->getDesc()<<" sending to peer_id="<<peer_id
1808 << ", channel " << (channelnum % 0xFF)
1809 << ", size: " << data.getSize() <<std::endl);
1811 u16 split_sequence_number = peer->getNextSplitSequenceNumber(channelnum);
1813 u32 chunksize_max = m_max_packet_size - BASE_HEADER_SIZE;
1814 std::list<SharedBuffer<u8> > originals;
1816 originals = makeAutoSplitPacket(data, chunksize_max,split_sequence_number);
1818 peer->setNextSplitSequenceNumber(channelnum,split_sequence_number);
1820 for(std::list<SharedBuffer<u8> >::iterator i = originals.begin();
1821 i != originals.end(); ++i)
1823 SharedBuffer<u8> original = *i;
1824 sendAsPacket(peer_id, channelnum, original);
1828 void ConnectionSendThread::sendReliable(ConnectionCommand &c)
1830 PeerHelper peer = m_connection->getPeerNoEx(c.peer_id);
1834 peer->PutReliableSendCommand(c,m_max_packet_size);
1837 void ConnectionSendThread::sendToAll(u8 channelnum, SharedBuffer<u8> data)
1839 std::list<u16> peerids = m_connection->getPeerIDs();
1841 for (std::list<u16>::iterator i = peerids.begin();
1845 send(*i, channelnum, data);
1849 void ConnectionSendThread::sendToAllReliable(ConnectionCommand &c)
1851 std::list<u16> peerids = m_connection->getPeerIDs();
1853 for (std::list<u16>::iterator i = peerids.begin();
1857 PeerHelper peer = m_connection->getPeerNoEx(*i);
1862 peer->PutReliableSendCommand(c,m_max_packet_size);
1866 void ConnectionSendThread::sendPackets(float dtime)
1868 std::list<u16> peerIds = m_connection->getPeerIDs();
1869 std::list<u16> pendingDisconnect;
1870 std::map<u16,bool> pending_unreliable;
1872 for(std::list<u16>::iterator
1873 j = peerIds.begin();
1874 j != peerIds.end(); ++j)
1876 PeerHelper peer = m_connection->getPeerNoEx(*j);
1877 //peer may have been removed
1879 LOG(dout_con<<m_connection->getDesc()<< " Peer not found: peer_id=" << *j << std::endl);
1882 peer->m_increment_packets_remaining = m_iteration_packets_avaialble/m_connection->m_peers.size();
1884 if (dynamic_cast<UDPPeer*>(&peer) == 0)
1889 if (dynamic_cast<UDPPeer*>(&peer)->m_pending_disconnect)
1891 pendingDisconnect.push_back(*j);
1894 PROFILE(std::stringstream peerIdentifier);
1895 PROFILE(peerIdentifier << "sendPackets[" << m_connection->getDesc() << ";" << *j << ";RELIABLE]");
1896 PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier.str(), SPT_AVG));
1898 LOG(dout_con<<m_connection->getDesc()
1899 << " Handle per peer queues: peer_id=" << *j
1900 << " packet quota: " << peer->m_increment_packets_remaining << std::endl);
1901 // first send queued reliable packets for all peers (if possible)
1902 for (unsigned int i=0; i < CHANNEL_COUNT; i++)
1904 u16 next_to_ack = 0;
1905 dynamic_cast<UDPPeer*>(&peer)->channels[i].outgoing_reliables_sent.getFirstSeqnum(next_to_ack);
1906 u16 next_to_receive = 0;
1907 dynamic_cast<UDPPeer*>(&peer)->channels[i].incoming_reliables.getFirstSeqnum(next_to_receive);
1909 LOG(dout_con<<m_connection->getDesc()<< "\t channel: "
1910 << i << ", peer quota:"
1911 << peer->m_increment_packets_remaining
1913 << "\t\t\treliables on wire: "
1914 << dynamic_cast<UDPPeer*>(&peer)->channels[i].outgoing_reliables_sent.size()
1915 << ", waiting for ack for " << next_to_ack
1917 << "\t\t\tincoming_reliables: "
1918 << dynamic_cast<UDPPeer*>(&peer)->channels[i].incoming_reliables.size()
1919 << ", next reliable packet: "
1920 << dynamic_cast<UDPPeer*>(&peer)->channels[i].readNextIncomingSeqNum()
1921 << ", next queued: " << next_to_receive
1923 << "\t\t\treliables queued : "
1924 << dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.size()
1926 << "\t\t\tqueued commands : "
1927 << dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_commands.size()
1930 while ((dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.size() > 0) &&
1931 (dynamic_cast<UDPPeer*>(&peer)->channels[i].outgoing_reliables_sent.size()
1932 < dynamic_cast<UDPPeer*>(&peer)->channels[i].getWindowSize())&&
1933 (peer->m_increment_packets_remaining > 0))
1935 BufferedPacket p = dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.front();
1936 dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.pop();
1937 Channel* channel = &(dynamic_cast<UDPPeer*>(&peer)->channels[i]);
1938 LOG(dout_con<<m_connection->getDesc()
1939 <<" INFO: sending a queued reliable packet "
1941 <<", seqnum: " << readU16(&p.data[BASE_HEADER_SIZE+1])
1943 sendAsPacketReliable(p,channel);
1944 peer->m_increment_packets_remaining--;
1949 if (m_outgoing_queue.size())
1951 LOG(dout_con<<m_connection->getDesc()
1952 << " Handle non reliable queue ("
1953 << m_outgoing_queue.size() << " pkts)" << std::endl);
1956 unsigned int initial_queuesize = m_outgoing_queue.size();
1957 /* send non reliable packets*/
1958 for(unsigned int i=0;i < initial_queuesize;i++) {
1959 OutgoingPacket packet = m_outgoing_queue.front();
1960 m_outgoing_queue.pop();
1962 if (packet.reliable)
1965 PeerHelper peer = m_connection->getPeerNoEx(packet.peer_id);
1967 LOG(dout_con<<m_connection->getDesc()
1968 <<" Outgoing queue: peer_id="<<packet.peer_id
1969 << ">>>NOT<<< found on sending packet"
1970 << ", channel " << (packet.channelnum % 0xFF)
1971 << ", size: " << packet.data.getSize() <<std::endl);
1974 /* send acks immediately */
1975 else if (packet.ack)
1977 rawSendAsPacket(packet.peer_id, packet.channelnum,
1978 packet.data, packet.reliable);
1979 peer->m_increment_packets_remaining =
1980 MYMIN(0,peer->m_increment_packets_remaining--);
1983 ( peer->m_increment_packets_remaining > 0) ||
1984 (stopRequested())) {
1985 rawSendAsPacket(packet.peer_id, packet.channelnum,
1986 packet.data, packet.reliable);
1987 peer->m_increment_packets_remaining--;
1990 m_outgoing_queue.push(packet);
1991 pending_unreliable[packet.peer_id] = true;
1995 for(std::list<u16>::iterator
1996 k = pendingDisconnect.begin();
1997 k != pendingDisconnect.end(); ++k)
1999 if (!pending_unreliable[*k])
2001 m_connection->deletePeer(*k,false);
2006 void ConnectionSendThread::sendAsPacket(u16 peer_id, u8 channelnum,
2007 SharedBuffer<u8> data, bool ack)
2009 OutgoingPacket packet(peer_id, channelnum, data, false, ack);
2010 m_outgoing_queue.push(packet);
2013 ConnectionReceiveThread::ConnectionReceiveThread(unsigned int max_packet_size) :
2014 Thread("ConnectionReceive"),
2019 void * ConnectionReceiveThread::run()
2021 assert(m_connection);
2023 LOG(dout_con<<m_connection->getDesc()
2024 <<"ConnectionReceive thread started"<<std::endl);
2026 PROFILE(std::stringstream ThreadIdentifier);
2027 PROFILE(ThreadIdentifier << "ConnectionReceive: [" << m_connection->getDesc() << "]");
2029 #ifdef DEBUG_CONNECTION_KBPS
2030 u32 curtime = porting::getTimeMs();
2031 u32 lasttime = curtime;
2032 float debug_print_timer = 0.0;
2035 while(!stopRequested()) {
2036 BEGIN_DEBUG_EXCEPTION_HANDLER
2037 PROFILE(ScopeProfiler sp(g_profiler, ThreadIdentifier.str(), SPT_AVG));
2039 #ifdef DEBUG_CONNECTION_KBPS
2041 curtime = porting::getTimeMs();
2042 float dtime = CALC_DTIME(lasttime,curtime);
2045 /* receive packets */
2048 #ifdef DEBUG_CONNECTION_KBPS
2049 debug_print_timer += dtime;
2050 if (debug_print_timer > 20.0) {
2051 debug_print_timer -= 20.0;
2053 std::list<u16> peerids = m_connection->getPeerIDs();
2055 for (std::list<u16>::iterator i = peerids.begin();
2059 PeerHelper peer = m_connection->getPeerNoEx(*i);
2063 float peer_current = 0.0;
2064 float peer_loss = 0.0;
2065 float avg_rate = 0.0;
2066 float avg_loss = 0.0;
2068 for(u16 j=0; j<CHANNEL_COUNT; j++)
2070 peer_current +=peer->channels[j].getCurrentDownloadRateKB();
2071 peer_loss += peer->channels[j].getCurrentLossRateKB();
2072 avg_rate += peer->channels[j].getAvgDownloadRateKB();
2073 avg_loss += peer->channels[j].getAvgLossRateKB();
2076 std::stringstream output;
2077 output << std::fixed << std::setprecision(1);
2078 output << "OUT to Peer " << *i << " RATES (good / loss) " << std::endl;
2079 output << "\tcurrent (sum): " << peer_current << "kb/s "<< peer_loss << "kb/s" << std::endl;
2080 output << "\taverage (sum): " << avg_rate << "kb/s "<< avg_loss << "kb/s" << std::endl;
2081 output << std::setfill(' ');
2082 for(u16 j=0; j<CHANNEL_COUNT; j++)
2084 output << "\tcha " << j << ":"
2085 << " CUR: " << std::setw(6) << peer->channels[j].getCurrentDownloadRateKB() <<"kb/s"
2086 << " AVG: " << std::setw(6) << peer->channels[j].getAvgDownloadRateKB() <<"kb/s"
2087 << " MAX: " << std::setw(6) << peer->channels[j].getMaxDownloadRateKB() <<"kb/s"
2089 << " CUR: " << std::setw(6) << peer->channels[j].getCurrentLossRateKB() <<"kb/s"
2090 << " AVG: " << std::setw(6) << peer->channels[j].getAvgLossRateKB() <<"kb/s"
2091 << " MAX: " << std::setw(6) << peer->channels[j].getMaxLossRateKB() <<"kb/s"
2092 << " / WS: " << peer->channels[j].getWindowSize()
2096 fprintf(stderr,"%s\n",output.str().c_str());
2100 END_DEBUG_EXCEPTION_HANDLER(errorstream);
2103 PROFILE(g_profiler->remove(ThreadIdentifier.str()));
2107 // Receive packets from the network and buffers and create ConnectionEvents
2108 void ConnectionReceiveThread::receive()
2110 // use IPv6 minimum allowed MTU as receive buffer size as this is
2111 // theoretical reliable upper boundary of a udp packet for all IPv6 enabled
2113 unsigned int packet_maxsize = 1500;
2114 SharedBuffer<u8> packetdata(packet_maxsize);
2116 bool packet_queued = true;
2118 unsigned int loop_count = 0;
2120 /* first of all read packets from socket */
2121 /* check for incoming data available */
2122 while( (loop_count < 10) &&
2123 (m_connection->m_udpSocket.WaitData(50))) {
2126 if (packet_queued) {
2127 bool data_left = true;
2129 SharedBuffer<u8> resultdata;
2132 data_left = getFromBuffers(peer_id, resultdata);
2135 e.dataReceived(peer_id, resultdata);
2136 m_connection->putEvent(e);
2139 catch(ProcessedSilentlyException &e) {
2140 /* try reading again */
2143 packet_queued = false;
2147 s32 received_size = m_connection->m_udpSocket.Receive(sender, *packetdata, packet_maxsize);
2149 if ((received_size < BASE_HEADER_SIZE) ||
2150 (readU32(&packetdata[0]) != m_connection->GetProtocolID()))
2152 LOG(derr_con<<m_connection->getDesc()
2153 <<"Receive(): Invalid incoming packet, "
2154 <<"size: " << received_size
2156 << ((received_size >= 4) ? readU32(&packetdata[0]) : -1)
2161 u16 peer_id = readPeerId(*packetdata);
2162 u8 channelnum = readChannel(*packetdata);
2164 if (channelnum > CHANNEL_COUNT-1) {
2165 LOG(derr_con<<m_connection->getDesc()
2166 <<"Receive(): Invalid channel "<<channelnum<<std::endl);
2167 throw InvalidIncomingDataException("Channel doesn't exist");
2170 /* preserve original peer_id for later usage */
2171 u16 packet_peer_id = peer_id;
2173 /* Try to identify peer by sender address (may happen on join) */
2174 if (peer_id == PEER_ID_INEXISTENT) {
2175 peer_id = m_connection->lookupPeer(sender);
2178 /* The peer was not found in our lists. Add it. */
2179 if (peer_id == PEER_ID_INEXISTENT) {
2180 peer_id = m_connection->createPeer(sender, MTP_MINETEST_RELIABLE_UDP, 0);
2183 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
2186 LOG(dout_con<<m_connection->getDesc()
2187 <<" got packet from unknown peer_id: "
2188 <<peer_id<<" Ignoring."<<std::endl);
2192 // Validate peer address
2194 Address peer_address;
2196 if (peer->getAddress(MTP_UDP, peer_address)) {
2197 if (peer_address != sender) {
2198 LOG(derr_con<<m_connection->getDesc()
2199 <<m_connection->getDesc()
2200 <<" Peer "<<peer_id<<" sending from different address."
2201 " Ignoring."<<std::endl);
2207 bool invalid_address = true;
2208 if (invalid_address) {
2209 LOG(derr_con<<m_connection->getDesc()
2210 <<m_connection->getDesc()
2211 <<" Peer "<<peer_id<<" unknown."
2212 " Ignoring."<<std::endl);
2218 /* mark peer as seen with id */
2219 if (!(packet_peer_id == PEER_ID_INEXISTENT))
2220 peer->setSentWithID();
2222 peer->ResetTimeout();
2224 Channel *channel = 0;
2226 if (dynamic_cast<UDPPeer*>(&peer) != 0)
2228 channel = &(dynamic_cast<UDPPeer*>(&peer)->channels[channelnum]);
2232 channel->UpdateBytesReceived(received_size);
2235 // Throw the received packet to channel->processPacket()
2237 // Make a new SharedBuffer from the data without the base headers
2238 SharedBuffer<u8> strippeddata(received_size - BASE_HEADER_SIZE);
2239 memcpy(*strippeddata, &packetdata[BASE_HEADER_SIZE],
2240 strippeddata.getSize());
2243 // Process it (the result is some data with no headers made by us)
2244 SharedBuffer<u8> resultdata = processPacket
2245 (channel, strippeddata, peer_id, channelnum, false);
2247 LOG(dout_con<<m_connection->getDesc()
2248 <<" ProcessPacket from peer_id: " << peer_id
2249 << ",channel: " << (channelnum & 0xFF) << ", returned "
2250 << resultdata.getSize() << " bytes" <<std::endl);
2253 e.dataReceived(peer_id, resultdata);
2254 m_connection->putEvent(e);
2256 catch(ProcessedSilentlyException &e) {
2258 catch(ProcessedQueued &e) {
2259 packet_queued = true;
2262 catch(InvalidIncomingDataException &e) {
2264 catch(ProcessedSilentlyException &e) {
2269 bool ConnectionReceiveThread::getFromBuffers(u16 &peer_id, SharedBuffer<u8> &dst)
2271 std::list<u16> peerids = m_connection->getPeerIDs();
2273 for(std::list<u16>::iterator j = peerids.begin();
2274 j != peerids.end(); ++j)
2276 PeerHelper peer = m_connection->getPeerNoEx(*j);
2280 if (dynamic_cast<UDPPeer*>(&peer) == 0)
2283 for(u16 i=0; i<CHANNEL_COUNT; i++)
2285 Channel *channel = &(dynamic_cast<UDPPeer*>(&peer))->channels[i];
2287 if (checkIncomingBuffers(channel, peer_id, dst)) {
2295 bool ConnectionReceiveThread::checkIncomingBuffers(Channel *channel,
2296 u16 &peer_id, SharedBuffer<u8> &dst)
2298 u16 firstseqnum = 0;
2299 if (channel->incoming_reliables.getFirstSeqnum(firstseqnum))
2301 if (firstseqnum == channel->readNextIncomingSeqNum())
2303 BufferedPacket p = channel->incoming_reliables.popFirst();
2304 peer_id = readPeerId(*p.data);
2305 u8 channelnum = readChannel(*p.data);
2306 u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]);
2308 LOG(dout_con<<m_connection->getDesc()
2309 <<"UNBUFFERING TYPE_RELIABLE"
2310 <<" seqnum="<<seqnum
2311 <<" peer_id="<<peer_id
2312 <<" channel="<<((int)channelnum&0xff)
2315 channel->incNextIncomingSeqNum();
2317 u32 headers_size = BASE_HEADER_SIZE + RELIABLE_HEADER_SIZE;
2318 // Get out the inside packet and re-process it
2319 SharedBuffer<u8> payload(p.data.getSize() - headers_size);
2320 memcpy(*payload, &p.data[headers_size], payload.getSize());
2322 dst = processPacket(channel, payload, peer_id, channelnum, true);
2329 SharedBuffer<u8> ConnectionReceiveThread::processPacket(Channel *channel,
2330 SharedBuffer<u8> packetdata, u16 peer_id, u8 channelnum, bool reliable)
2332 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
2335 errorstream << "Peer not found (possible timeout)" << std::endl;
2336 throw ProcessedSilentlyException("Peer not found (possible timeout)");
2339 if (packetdata.getSize() < 1)
2340 throw InvalidIncomingDataException("packetdata.getSize() < 1");
2342 u8 type = readU8(&(packetdata[0]));
2344 if (MAX_UDP_PEERS <= 65535 && peer_id >= MAX_UDP_PEERS) {
2345 std::string errmsg = "Invalid peer_id=" + itos(peer_id);
2346 errorstream << errmsg << std::endl;
2347 throw InvalidIncomingDataException(errmsg.c_str());
2350 if (type == TYPE_CONTROL)
2352 if (packetdata.getSize() < 2)
2353 throw InvalidIncomingDataException("packetdata.getSize() < 2");
2355 u8 controltype = readU8(&(packetdata[1]));
2357 if (controltype == CONTROLTYPE_ACK)
2359 assert(channel != NULL);
2361 if (packetdata.getSize() < 4) {
2362 throw InvalidIncomingDataException(
2363 "packetdata.getSize() < 4 (ACK header size)");
2366 u16 seqnum = readU16(&packetdata[2]);
2367 LOG(dout_con<<m_connection->getDesc()
2368 <<" [ CONTROLTYPE_ACK: channelnum="
2369 <<((int)channelnum&0xff)<<", peer_id="<<peer_id
2370 <<", seqnum="<<seqnum<< " ]"<<std::endl);
2374 channel->outgoing_reliables_sent.popSeqnum(seqnum);
2376 // only calculate rtt from straight sent packets
2377 if (p.resend_count == 0) {
2378 // Get round trip time
2379 unsigned int current_time = porting::getTimeMs();
2381 // a overflow is quite unlikely but as it'd result in major
2382 // rtt miscalculation we handle it here
2383 if (current_time > p.absolute_send_time)
2385 float rtt = (current_time - p.absolute_send_time) / 1000.0;
2387 // Let peer calculate stuff according to it
2388 // (avg_rtt and resend_timeout)
2389 dynamic_cast<UDPPeer*>(&peer)->reportRTT(rtt);
2391 else if (p.totaltime > 0)
2393 float rtt = p.totaltime;
2395 // Let peer calculate stuff according to it
2396 // (avg_rtt and resend_timeout)
2397 dynamic_cast<UDPPeer*>(&peer)->reportRTT(rtt);
2400 //put bytes for max bandwidth calculation
2401 channel->UpdateBytesSent(p.data.getSize(),1);
2402 if (channel->outgoing_reliables_sent.size() == 0)
2404 m_connection->TriggerSend();
2407 catch(NotFoundException &e) {
2408 LOG(derr_con<<m_connection->getDesc()
2409 <<"WARNING: ACKed packet not "
2412 channel->UpdatePacketTooLateCounter();
2414 throw ProcessedSilentlyException("Got an ACK");
2416 else if (controltype == CONTROLTYPE_SET_PEER_ID) {
2417 // Got a packet to set our peer id
2418 if (packetdata.getSize() < 4)
2419 throw InvalidIncomingDataException
2420 ("packetdata.getSize() < 4 (SET_PEER_ID header size)");
2421 u16 peer_id_new = readU16(&packetdata[2]);
2422 LOG(dout_con<<m_connection->getDesc()
2423 <<"Got new peer id: "<<peer_id_new<<"... "<<std::endl);
2425 if (m_connection->GetPeerID() != PEER_ID_INEXISTENT)
2427 LOG(derr_con<<m_connection->getDesc()
2428 <<"WARNING: Not changing"
2429 " existing peer id."<<std::endl);
2433 LOG(dout_con<<m_connection->getDesc()<<"changing own peer id"<<std::endl);
2434 m_connection->SetPeerID(peer_id_new);
2437 ConnectionCommand cmd;
2439 SharedBuffer<u8> reply(2);
2440 writeU8(&reply[0], TYPE_CONTROL);
2441 writeU8(&reply[1], CONTROLTYPE_ENABLE_BIG_SEND_WINDOW);
2442 cmd.disableLegacy(PEER_ID_SERVER,reply);
2443 m_connection->putCommand(cmd);
2445 throw ProcessedSilentlyException("Got a SET_PEER_ID");
2447 else if (controltype == CONTROLTYPE_PING)
2449 // Just ignore it, the incoming data already reset
2450 // the timeout counter
2451 LOG(dout_con<<m_connection->getDesc()<<"PING"<<std::endl);
2452 throw ProcessedSilentlyException("Got a PING");
2454 else if (controltype == CONTROLTYPE_DISCO)
2456 // Just ignore it, the incoming data already reset
2457 // the timeout counter
2458 LOG(dout_con<<m_connection->getDesc()
2459 <<"DISCO: Removing peer "<<(peer_id)<<std::endl);
2461 if (m_connection->deletePeer(peer_id, false) == false)
2463 derr_con<<m_connection->getDesc()
2464 <<"DISCO: Peer not found"<<std::endl;
2467 throw ProcessedSilentlyException("Got a DISCO");
2469 else if (controltype == CONTROLTYPE_ENABLE_BIG_SEND_WINDOW)
2471 dynamic_cast<UDPPeer*>(&peer)->setNonLegacyPeer();
2472 throw ProcessedSilentlyException("Got non legacy control");
2475 LOG(derr_con<<m_connection->getDesc()
2476 <<"INVALID TYPE_CONTROL: invalid controltype="
2477 <<((int)controltype&0xff)<<std::endl);
2478 throw InvalidIncomingDataException("Invalid control type");
2481 else if (type == TYPE_ORIGINAL)
2483 if (packetdata.getSize() <= ORIGINAL_HEADER_SIZE)
2484 throw InvalidIncomingDataException
2485 ("packetdata.getSize() <= ORIGINAL_HEADER_SIZE");
2486 LOG(dout_con<<m_connection->getDesc()
2487 <<"RETURNING TYPE_ORIGINAL to user"
2489 // Get the inside packet out and return it
2490 SharedBuffer<u8> payload(packetdata.getSize() - ORIGINAL_HEADER_SIZE);
2491 memcpy(*payload, &(packetdata[ORIGINAL_HEADER_SIZE]), payload.getSize());
2494 else if (type == TYPE_SPLIT)
2496 Address peer_address;
2498 if (peer->getAddress(MTP_UDP, peer_address)) {
2500 // We have to create a packet again for buffering
2501 // This isn't actually too bad an idea.
2502 BufferedPacket packet = makePacket(
2505 m_connection->GetProtocolID(),
2509 // Buffer the packet
2510 SharedBuffer<u8> data =
2511 peer->addSpiltPacket(channelnum,packet,reliable);
2513 if (data.getSize() != 0)
2515 LOG(dout_con<<m_connection->getDesc()
2516 <<"RETURNING TYPE_SPLIT: Constructed full data, "
2517 <<"size="<<data.getSize()<<std::endl);
2520 LOG(dout_con<<m_connection->getDesc()<<"BUFFERED TYPE_SPLIT"<<std::endl);
2521 throw ProcessedSilentlyException("Buffered a split packet chunk");
2524 //TODO throw some error
2527 else if (type == TYPE_RELIABLE)
2529 assert(channel != NULL);
2531 // Recursive reliable packets not allowed
2533 throw InvalidIncomingDataException("Found nested reliable packets");
2535 if (packetdata.getSize() < RELIABLE_HEADER_SIZE)
2536 throw InvalidIncomingDataException
2537 ("packetdata.getSize() < RELIABLE_HEADER_SIZE");
2539 u16 seqnum = readU16(&packetdata[1]);
2540 bool is_future_packet = false;
2541 bool is_old_packet = false;
2543 /* packet is within our receive window send ack */
2544 if (seqnum_in_window(seqnum, channel->readNextIncomingSeqNum(),MAX_RELIABLE_WINDOW_SIZE))
2546 m_connection->sendAck(peer_id,channelnum,seqnum);
2549 is_future_packet = seqnum_higher(seqnum, channel->readNextIncomingSeqNum());
2550 is_old_packet = seqnum_higher(channel->readNextIncomingSeqNum(), seqnum);
2553 /* packet is not within receive window, don't send ack. *
2554 * if this was a valid packet it's gonna be retransmitted */
2555 if (is_future_packet)
2557 throw ProcessedSilentlyException("Received packet newer then expected, not sending ack");
2560 /* seems like our ack was lost, send another one for a old packet */
2563 LOG(dout_con<<m_connection->getDesc()
2564 << "RE-SENDING ACK: peer_id: " << peer_id
2565 << ", channel: " << (channelnum&0xFF)
2566 << ", seqnum: " << seqnum << std::endl;)
2567 m_connection->sendAck(peer_id,channelnum,seqnum);
2569 // we already have this packet so this one was on wire at least
2570 // the current timeout
2571 // we don't know how long this packet was on wire don't do silly guessing
2572 // dynamic_cast<UDPPeer*>(&peer)->reportRTT(dynamic_cast<UDPPeer*>(&peer)->getResendTimeout());
2574 throw ProcessedSilentlyException("Retransmitting ack for old packet");
2578 if (seqnum != channel->readNextIncomingSeqNum())
2580 Address peer_address;
2582 // this is a reliable packet so we have a udp address for sure
2583 peer->getAddress(MTP_MINETEST_RELIABLE_UDP, peer_address);
2584 // This one comes later, buffer it.
2585 // Actually we have to make a packet to buffer one.
2586 // Well, we have all the ingredients, so just do it.
2587 BufferedPacket packet = con::makePacket(
2590 m_connection->GetProtocolID(),
2594 channel->incoming_reliables.insert(packet,channel->readNextIncomingSeqNum());
2596 LOG(dout_con<<m_connection->getDesc()
2597 << "BUFFERING, TYPE_RELIABLE peer_id: " << peer_id
2598 << ", channel: " << (channelnum&0xFF)
2599 << ", seqnum: " << seqnum << std::endl;)
2601 throw ProcessedQueued("Buffered future reliable packet");
2603 catch(AlreadyExistsException &e)
2606 catch(IncomingDataCorruption &e)
2608 ConnectionCommand discon;
2609 discon.disconnect_peer(peer_id);
2610 m_connection->putCommand(discon);
2612 LOG(derr_con<<m_connection->getDesc()
2613 << "INVALID, TYPE_RELIABLE peer_id: " << peer_id
2614 << ", channel: " << (channelnum&0xFF)
2615 << ", seqnum: " << seqnum
2616 << "DROPPING CLIENT!" << std::endl;)
2620 /* we got a packet to process right now */
2621 LOG(dout_con<<m_connection->getDesc()
2622 << "RECURSIVE, TYPE_RELIABLE peer_id: " << peer_id
2623 << ", channel: " << (channelnum&0xFF)
2624 << ", seqnum: " << seqnum << std::endl;)
2627 /* check for resend case */
2628 u16 queued_seqnum = 0;
2629 if (channel->incoming_reliables.getFirstSeqnum(queued_seqnum))
2631 if (queued_seqnum == seqnum)
2633 BufferedPacket queued_packet = channel->incoming_reliables.popFirst();
2634 /** TODO find a way to verify the new against the old packet */
2638 channel->incNextIncomingSeqNum();
2640 // Get out the inside packet and re-process it
2641 SharedBuffer<u8> payload(packetdata.getSize() - RELIABLE_HEADER_SIZE);
2642 memcpy(*payload, &packetdata[RELIABLE_HEADER_SIZE], payload.getSize());
2644 return processPacket(channel, payload, peer_id, channelnum, true);
2648 derr_con<<m_connection->getDesc()
2649 <<"Got invalid type="<<((int)type&0xff)<<std::endl;
2650 throw InvalidIncomingDataException("Invalid packet type");
2653 // We should never get here.
2654 FATAL_ERROR("Invalid execution point");
2661 Connection::Connection(u32 protocol_id, u32 max_packet_size, float timeout,
2662 bool ipv6, PeerHandler *peerhandler) :
2667 m_protocol_id(protocol_id),
2668 m_sendThread(max_packet_size, timeout),
2669 m_receiveThread(max_packet_size),
2671 m_bc_peerhandler(peerhandler),
2672 m_bc_receive_timeout(0),
2673 m_shutting_down(false),
2674 m_next_remote_peer_id(2)
2677 m_udpSocket.setTimeoutMs(5);
2679 m_sendThread.setParent(this);
2680 m_receiveThread.setParent(this);
2682 m_sendThread.start();
2683 m_receiveThread.start();
2688 Connection::~Connection()
2690 m_shutting_down = true;
2691 // request threads to stop
2692 m_sendThread.stop();
2693 m_receiveThread.stop();
2695 //TODO for some unkonwn reason send/receive threads do not exit as they're
2696 // supposed to be but wait on peer timeout. To speed up shutdown we reduce
2697 // timeout to half a second.
2698 m_sendThread.setPeerTimeout(0.5);
2700 // wait for threads to finish
2701 m_sendThread.wait();
2702 m_receiveThread.wait();
2705 for(std::map<u16, Peer*>::iterator
2706 j = m_peers.begin();
2707 j != m_peers.end(); ++j)
2713 /* Internal stuff */
2714 void Connection::putEvent(ConnectionEvent &e)
2716 assert(e.type != CONNEVENT_NONE); // Pre-condition
2717 m_event_queue.push_back(e);
2720 PeerHelper Connection::getPeer(u16 peer_id)
2722 MutexAutoLock peerlock(m_peers_mutex);
2723 std::map<u16, Peer*>::iterator node = m_peers.find(peer_id);
2725 if (node == m_peers.end()) {
2726 throw PeerNotFoundException("GetPeer: Peer not found (possible timeout)");
2730 FATAL_ERROR_IF(node->second->id != peer_id, "Invalid peer id");
2732 return PeerHelper(node->second);
2735 PeerHelper Connection::getPeerNoEx(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 return PeerHelper(NULL);
2745 FATAL_ERROR_IF(node->second->id != peer_id, "Invalid peer id");
2747 return PeerHelper(node->second);
2750 /* find peer_id for address */
2751 u16 Connection::lookupPeer(Address& sender)
2753 MutexAutoLock peerlock(m_peers_mutex);
2754 std::map<u16, Peer*>::iterator j;
2755 j = m_peers.begin();
2756 for(; j != m_peers.end(); ++j)
2758 Peer *peer = j->second;
2759 if (peer->isActive())
2764 if ((peer->getAddress(MTP_MINETEST_RELIABLE_UDP, tocheck)) && (tocheck == sender))
2767 if ((peer->getAddress(MTP_UDP, tocheck)) && (tocheck == sender))
2771 return PEER_ID_INEXISTENT;
2774 std::list<Peer*> Connection::getPeers()
2776 std::list<Peer*> list;
2777 for(std::map<u16, Peer*>::iterator j = m_peers.begin();
2778 j != m_peers.end(); ++j)
2780 Peer *peer = j->second;
2781 list.push_back(peer);
2786 bool Connection::deletePeer(u16 peer_id, bool timeout)
2790 /* lock list as short as possible */
2792 MutexAutoLock peerlock(m_peers_mutex);
2793 if (m_peers.find(peer_id) == m_peers.end())
2795 peer = m_peers[peer_id];
2796 m_peers.erase(peer_id);
2797 m_peer_ids.remove(peer_id);
2800 Address peer_address;
2801 //any peer has a primary address this never fails!
2802 peer->getAddress(MTP_PRIMARY, peer_address);
2805 e.peerRemoved(peer_id, timeout, peer_address);
2815 ConnectionEvent Connection::waitEvent(u32 timeout_ms)
2818 return m_event_queue.pop_front(timeout_ms);
2819 } catch(ItemNotFoundException &ex) {
2821 e.type = CONNEVENT_NONE;
2826 void Connection::putCommand(ConnectionCommand &c)
2828 if (!m_shutting_down) {
2829 m_command_queue.push_back(c);
2830 m_sendThread.Trigger();
2834 void Connection::Serve(Address bind_addr)
2836 ConnectionCommand c;
2841 void Connection::Connect(Address address)
2843 ConnectionCommand c;
2848 bool Connection::Connected()
2850 MutexAutoLock peerlock(m_peers_mutex);
2852 if (m_peers.size() != 1)
2855 std::map<u16, Peer*>::iterator node = m_peers.find(PEER_ID_SERVER);
2856 if (node == m_peers.end())
2859 if (m_peer_id == PEER_ID_INEXISTENT)
2865 void Connection::Disconnect()
2867 ConnectionCommand c;
2872 void Connection::Receive(NetworkPacket* pkt)
2875 ConnectionEvent e = waitEvent(m_bc_receive_timeout);
2876 if (e.type != CONNEVENT_NONE)
2877 LOG(dout_con << getDesc() << ": Receive: got event: "
2878 << e.describe() << std::endl);
2880 case CONNEVENT_NONE:
2881 throw NoIncomingDataException("No incoming data");
2882 case CONNEVENT_DATA_RECEIVED:
2883 // Data size is lesser than command size, ignoring packet
2884 if (e.data.getSize() < 2) {
2888 pkt->putRawPacket(*e.data, e.data.getSize(), e.peer_id);
2890 case CONNEVENT_PEER_ADDED: {
2891 UDPPeer tmp(e.peer_id, e.address, this);
2892 if (m_bc_peerhandler)
2893 m_bc_peerhandler->peerAdded(&tmp);
2896 case CONNEVENT_PEER_REMOVED: {
2897 UDPPeer tmp(e.peer_id, e.address, this);
2898 if (m_bc_peerhandler)
2899 m_bc_peerhandler->deletingPeer(&tmp, e.timeout);
2902 case CONNEVENT_BIND_FAILED:
2903 throw ConnectionBindFailed("Failed to bind socket "
2904 "(port already in use?)");
2907 throw NoIncomingDataException("No incoming data");
2910 void Connection::Send(u16 peer_id, u8 channelnum,
2911 NetworkPacket* pkt, bool reliable)
2913 assert(channelnum < CHANNEL_COUNT); // Pre-condition
2915 ConnectionCommand c;
2917 c.send(peer_id, channelnum, pkt, reliable);
2921 Address Connection::GetPeerAddress(u16 peer_id)
2923 PeerHelper peer = getPeerNoEx(peer_id);
2926 throw PeerNotFoundException("No address for peer found!");
2927 Address peer_address;
2928 peer->getAddress(MTP_PRIMARY, peer_address);
2929 return peer_address;
2932 float Connection::getPeerStat(u16 peer_id, rtt_stat_type type)
2934 PeerHelper peer = getPeerNoEx(peer_id);
2935 if (!peer) return -1;
2936 return peer->getStat(type);
2939 float Connection::getLocalStat(rate_stat_type type)
2941 PeerHelper peer = getPeerNoEx(PEER_ID_SERVER);
2943 FATAL_ERROR_IF(!peer, "Connection::getLocalStat we couldn't get our own peer? are you serious???");
2947 for (u16 j=0; j<CHANNEL_COUNT; j++) {
2950 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getCurrentDownloadRateKB();
2953 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getAvgDownloadRateKB();
2956 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getCurrentIncomingRateKB();
2959 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getAvgIncomingRateKB();
2962 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getAvgLossRateKB();
2965 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getCurrentLossRateKB();
2968 FATAL_ERROR("Connection::getLocalStat Invalid stat type");
2974 u16 Connection::createPeer(Address& sender, MTProtocols protocol, int fd)
2976 // Somebody wants to make a new connection
2978 // Get a unique peer id (2 or higher)
2979 u16 peer_id_new = m_next_remote_peer_id;
2980 u16 overflow = MAX_UDP_PEERS;
2983 Find an unused peer id
2985 MutexAutoLock lock(m_peers_mutex);
2986 bool out_of_ids = false;
2989 if (m_peers.find(peer_id_new) == m_peers.end())
2992 // Check for overflow
2993 if (peer_id_new == overflow) {
3001 errorstream << getDesc() << " ran out of peer ids" << std::endl;
3002 return PEER_ID_INEXISTENT;
3007 peer = new UDPPeer(peer_id_new, sender, this);
3009 m_peers[peer->id] = peer;
3010 m_peer_ids.push_back(peer->id);
3012 m_next_remote_peer_id = (peer_id_new +1 ) % MAX_UDP_PEERS;
3014 LOG(dout_con << getDesc()
3015 << "createPeer(): giving peer_id=" << peer_id_new << std::endl);
3017 ConnectionCommand cmd;
3018 SharedBuffer<u8> reply(4);
3019 writeU8(&reply[0], TYPE_CONTROL);
3020 writeU8(&reply[1], CONTROLTYPE_SET_PEER_ID);
3021 writeU16(&reply[2], peer_id_new);
3022 cmd.createPeer(peer_id_new,reply);
3025 // Create peer addition event
3027 e.peerAdded(peer_id_new, sender);
3030 // We're now talking to a valid peer_id
3034 void Connection::PrintInfo(std::ostream &out)
3036 m_info_mutex.lock();
3037 out<<getDesc()<<": ";
3038 m_info_mutex.unlock();
3041 void Connection::PrintInfo()
3043 PrintInfo(dout_con);
3046 const std::string Connection::getDesc()
3048 return std::string("con(")+
3049 itos(m_udpSocket.GetHandle())+"/"+itos(m_peer_id)+")";
3052 void Connection::DisconnectPeer(u16 peer_id)
3054 ConnectionCommand discon;
3055 discon.disconnect_peer(peer_id);
3059 void Connection::sendAck(u16 peer_id, u8 channelnum, u16 seqnum)
3061 assert(channelnum < CHANNEL_COUNT); // Pre-condition
3063 LOG(dout_con<<getDesc()
3064 <<" Queuing ACK command to peer_id: " << peer_id <<
3065 " channel: " << (channelnum & 0xFF) <<
3066 " seqnum: " << seqnum << std::endl);
3068 ConnectionCommand c;
3069 SharedBuffer<u8> ack(4);
3070 writeU8(&ack[0], TYPE_CONTROL);
3071 writeU8(&ack[1], CONTROLTYPE_ACK);
3072 writeU16(&ack[2], seqnum);
3074 c.ack(peer_id, channelnum, ack);
3076 m_sendThread.Trigger();
3079 UDPPeer* Connection::createServerPeer(Address& address)
3081 if (getPeerNoEx(PEER_ID_SERVER) != 0)
3083 throw ConnectionException("Already connected to a server");
3086 UDPPeer *peer = new UDPPeer(PEER_ID_SERVER, address, this);
3089 MutexAutoLock lock(m_peers_mutex);
3090 m_peers[peer->id] = peer;
3091 m_peer_ids.push_back(peer->id);