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 std::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 #define MAX_UDP_PEERS 65535
65 #define PING_TIMEOUT 5.0
67 /* maximum number of retries for reliable packets */
68 #define MAX_RELIABLE_RETRY 5
70 static u16 readPeerId(u8 *packetdata)
72 return readU16(&packetdata[4]);
74 static u8 readChannel(u8 *packetdata)
76 return readU8(&packetdata[6]);
79 BufferedPacket makePacket(Address &address, u8 *data, u32 datasize,
80 u32 protocol_id, u16 sender_peer_id, u8 channel)
82 u32 packet_size = datasize + BASE_HEADER_SIZE;
83 BufferedPacket p(packet_size);
86 writeU32(&p.data[0], protocol_id);
87 writeU16(&p.data[4], sender_peer_id);
88 writeU8(&p.data[6], channel);
90 memcpy(&p.data[BASE_HEADER_SIZE], data, datasize);
95 BufferedPacket makePacket(Address &address, SharedBuffer<u8> &data,
96 u32 protocol_id, u16 sender_peer_id, u8 channel)
98 return makePacket(address, *data, data.getSize(),
99 protocol_id, sender_peer_id, channel);
102 SharedBuffer<u8> makeOriginalPacket(
103 SharedBuffer<u8> data)
106 u32 packet_size = data.getSize() + header_size;
107 SharedBuffer<u8> b(packet_size);
109 writeU8(&(b[0]), TYPE_ORIGINAL);
110 if (data.getSize() > 0) {
111 memcpy(&(b[header_size]), *data, data.getSize());
116 std::list<SharedBuffer<u8> > makeSplitPacket(
117 SharedBuffer<u8> data,
121 // Chunk packets, containing the TYPE_SPLIT header
122 std::list<SharedBuffer<u8> > chunks;
124 u32 chunk_header_size = 7;
125 u32 maximum_data_size = chunksize_max - chunk_header_size;
131 end = start + maximum_data_size - 1;
132 if (end > data.getSize() - 1)
133 end = data.getSize() - 1;
135 u32 payload_size = end - start + 1;
136 u32 packet_size = chunk_header_size + payload_size;
138 SharedBuffer<u8> chunk(packet_size);
140 writeU8(&chunk[0], TYPE_SPLIT);
141 writeU16(&chunk[1], seqnum);
142 // [3] u16 chunk_count is written at next stage
143 writeU16(&chunk[5], chunk_num);
144 memcpy(&chunk[chunk_header_size], &data[start], payload_size);
146 chunks.push_back(chunk);
152 while(end != data.getSize() - 1);
154 for(std::list<SharedBuffer<u8> >::iterator i = chunks.begin();
155 i != chunks.end(); ++i)
158 writeU16(&((*i)[3]), chunk_count);
164 std::list<SharedBuffer<u8> > makeAutoSplitPacket(
165 SharedBuffer<u8> data,
169 u32 original_header_size = 1;
170 std::list<SharedBuffer<u8> > list;
171 if (data.getSize() + original_header_size > chunksize_max)
173 list = makeSplitPacket(data, chunksize_max, split_seqnum);
179 list.push_back(makeOriginalPacket(data));
184 SharedBuffer<u8> makeReliablePacket(
185 SharedBuffer<u8> data,
189 u32 packet_size = data.getSize() + header_size;
190 SharedBuffer<u8> b(packet_size);
192 writeU8(&b[0], TYPE_RELIABLE);
193 writeU16(&b[1], seqnum);
195 memcpy(&b[header_size], *data, data.getSize());
204 void ReliablePacketBuffer::print()
206 MutexAutoLock listlock(m_list_mutex);
207 LOG(dout_con<<"Dump of ReliablePacketBuffer:" << std::endl);
208 unsigned int index = 0;
209 for(std::list<BufferedPacket>::iterator i = m_list.begin();
213 u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
214 LOG(dout_con<<index<< ":" << s << std::endl);
218 bool ReliablePacketBuffer::empty()
220 MutexAutoLock listlock(m_list_mutex);
221 return m_list.empty();
224 u32 ReliablePacketBuffer::size()
229 bool ReliablePacketBuffer::containsPacket(u16 seqnum)
231 return !(findPacket(seqnum) == m_list.end());
234 RPBSearchResult ReliablePacketBuffer::findPacket(u16 seqnum)
236 std::list<BufferedPacket>::iterator i = m_list.begin();
237 for(; i != m_list.end(); ++i)
239 u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
240 /*dout_con<<"findPacket(): finding seqnum="<<seqnum
241 <<", comparing to s="<<s<<std::endl;*/
247 RPBSearchResult ReliablePacketBuffer::notFound()
251 bool ReliablePacketBuffer::getFirstSeqnum(u16& result)
253 MutexAutoLock listlock(m_list_mutex);
256 BufferedPacket p = *m_list.begin();
257 result = readU16(&p.data[BASE_HEADER_SIZE+1]);
261 BufferedPacket ReliablePacketBuffer::popFirst()
263 MutexAutoLock listlock(m_list_mutex);
265 throw NotFoundException("Buffer is empty");
266 BufferedPacket p = *m_list.begin();
267 m_list.erase(m_list.begin());
270 if (m_list_size == 0) {
271 m_oldest_non_answered_ack = 0;
273 m_oldest_non_answered_ack =
274 readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]);
278 BufferedPacket ReliablePacketBuffer::popSeqnum(u16 seqnum)
280 MutexAutoLock listlock(m_list_mutex);
281 RPBSearchResult r = findPacket(seqnum);
282 if (r == notFound()) {
283 LOG(dout_con<<"Sequence number: " << seqnum
284 << " not found in reliable buffer"<<std::endl);
285 throw NotFoundException("seqnum not found in buffer");
287 BufferedPacket p = *r;
290 RPBSearchResult next = r;
292 if (next != notFound()) {
293 u16 s = readU16(&(next->data[BASE_HEADER_SIZE+1]));
294 m_oldest_non_answered_ack = s;
300 if (m_list_size == 0)
301 { m_oldest_non_answered_ack = 0; }
303 { m_oldest_non_answered_ack = readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]); }
306 void ReliablePacketBuffer::insert(BufferedPacket &p,u16 next_expected)
308 MutexAutoLock listlock(m_list_mutex);
309 if (p.data.getSize() < BASE_HEADER_SIZE + 3) {
310 errorstream << "ReliablePacketBuffer::insert(): Invalid data size for "
311 "reliable packet" << std::endl;
314 u8 type = readU8(&p.data[BASE_HEADER_SIZE + 0]);
315 if (type != TYPE_RELIABLE) {
316 errorstream << "ReliablePacketBuffer::insert(): type is not reliable"
320 u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE + 1]);
322 if (!seqnum_in_window(seqnum, next_expected, MAX_RELIABLE_WINDOW_SIZE)) {
323 errorstream << "ReliablePacketBuffer::insert(): seqnum is outside of "
324 "expected window " << std::endl;
327 if (seqnum == next_expected) {
328 errorstream << "ReliablePacketBuffer::insert(): seqnum is next expected"
334 sanity_check(m_list_size <= SEQNUM_MAX+1); // FIXME: Handle the error?
336 // Find the right place for the packet and insert it there
337 // If list is empty, just add it
341 m_oldest_non_answered_ack = seqnum;
346 // Otherwise find the right place
347 std::list<BufferedPacket>::iterator i = m_list.begin();
348 // Find the first packet in the list which has a higher seqnum
349 u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
351 /* case seqnum is smaller then next_expected seqnum */
352 /* this is true e.g. on wrap around */
353 if (seqnum < next_expected) {
354 while(((s < seqnum) || (s >= next_expected)) && (i != m_list.end())) {
356 if (i != m_list.end())
357 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
360 /* non wrap around case (at least for incoming and next_expected */
363 while(((s < seqnum) && (s >= next_expected)) && (i != m_list.end())) {
365 if (i != m_list.end())
366 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
372 (readU16(&(i->data[BASE_HEADER_SIZE+1])) != seqnum) ||
373 (i->data.getSize() != p.data.getSize()) ||
374 (i->address != p.address)
377 /* if this happens your maximum transfer window may be to big */
379 "Duplicated seqnum %d non matching packet detected:\n",
381 fprintf(stderr, "Old: seqnum: %05d size: %04d, address: %s\n",
382 readU16(&(i->data[BASE_HEADER_SIZE+1])),i->data.getSize(),
383 i->address.serializeString().c_str());
384 fprintf(stderr, "New: seqnum: %05d size: %04u, address: %s\n",
385 readU16(&(p.data[BASE_HEADER_SIZE+1])),p.data.getSize(),
386 p.address.serializeString().c_str());
387 throw IncomingDataCorruption("duplicated packet isn't same as original one");
390 /* nothing to do this seems to be a resent packet */
391 /* for paranoia reason data should be compared */
394 /* insert or push back */
395 else if (i != m_list.end()) {
402 /* update last packet number */
403 m_oldest_non_answered_ack = readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]);
406 void ReliablePacketBuffer::incrementTimeouts(float dtime)
408 MutexAutoLock listlock(m_list_mutex);
409 for(std::list<BufferedPacket>::iterator i = m_list.begin();
410 i != m_list.end(); ++i)
413 i->totaltime += dtime;
417 std::list<BufferedPacket> ReliablePacketBuffer::getTimedOuts(float timeout,
418 unsigned int max_packets)
420 MutexAutoLock listlock(m_list_mutex);
421 std::list<BufferedPacket> timed_outs;
422 for(std::list<BufferedPacket>::iterator i = m_list.begin();
423 i != m_list.end(); ++i)
425 if (i->time >= timeout) {
426 timed_outs.push_back(*i);
428 //this packet will be sent right afterwards reset timeout here
430 if (timed_outs.size() >= max_packets)
441 IncomingSplitBuffer::~IncomingSplitBuffer()
443 MutexAutoLock listlock(m_map_mutex);
444 for(std::map<u16, IncomingSplitPacket*>::iterator i = m_buf.begin();
445 i != m_buf.end(); ++i)
451 This will throw a GotSplitPacketException when a full
452 split packet is constructed.
454 SharedBuffer<u8> IncomingSplitBuffer::insert(BufferedPacket &p, bool reliable)
456 MutexAutoLock listlock(m_map_mutex);
457 u32 headersize = BASE_HEADER_SIZE + 7;
458 if (p.data.getSize() < headersize) {
459 errorstream << "Invalid data size for split packet" << std::endl;
460 return SharedBuffer<u8>();
462 u8 type = readU8(&p.data[BASE_HEADER_SIZE+0]);
463 u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]);
464 u16 chunk_count = readU16(&p.data[BASE_HEADER_SIZE+3]);
465 u16 chunk_num = readU16(&p.data[BASE_HEADER_SIZE+5]);
467 if (type != TYPE_SPLIT) {
468 errorstream << "IncomingSplitBuffer::insert(): type is not split"
470 return SharedBuffer<u8>();
473 // Add if doesn't exist
474 if (m_buf.find(seqnum) == m_buf.end())
476 IncomingSplitPacket *sp = new IncomingSplitPacket();
477 sp->chunk_count = chunk_count;
478 sp->reliable = reliable;
482 IncomingSplitPacket *sp = m_buf[seqnum];
484 // TODO: These errors should be thrown or something? Dunno.
485 if (chunk_count != sp->chunk_count)
486 LOG(derr_con<<"Connection: WARNING: chunk_count="<<chunk_count
487 <<" != sp->chunk_count="<<sp->chunk_count
489 if (reliable != sp->reliable)
490 LOG(derr_con<<"Connection: WARNING: reliable="<<reliable
491 <<" != sp->reliable="<<sp->reliable
494 // If chunk already exists, ignore it.
495 // Sometimes two identical packets may arrive when there is network
496 // lag and the server re-sends stuff.
497 if (sp->chunks.find(chunk_num) != sp->chunks.end())
498 return SharedBuffer<u8>();
500 // Cut chunk data out of packet
501 u32 chunkdatasize = p.data.getSize() - headersize;
502 SharedBuffer<u8> chunkdata(chunkdatasize);
503 memcpy(*chunkdata, &(p.data[headersize]), chunkdatasize);
505 // Set chunk data in buffer
506 sp->chunks[chunk_num] = chunkdata;
508 // If not all chunks are received, return empty buffer
509 if (sp->allReceived() == false)
510 return SharedBuffer<u8>();
512 // Calculate total size
514 for(std::map<u16, SharedBuffer<u8> >::iterator i = sp->chunks.begin();
515 i != sp->chunks.end(); ++i)
517 totalsize += i->second.getSize();
520 SharedBuffer<u8> fulldata(totalsize);
522 // Copy chunks to data buffer
524 for(u32 chunk_i=0; chunk_i<sp->chunk_count;
527 SharedBuffer<u8> buf = sp->chunks[chunk_i];
528 u16 chunkdatasize = buf.getSize();
529 memcpy(&fulldata[start], *buf, chunkdatasize);
530 start += chunkdatasize;;
533 // Remove sp from buffer
539 void IncomingSplitBuffer::removeUnreliableTimedOuts(float dtime, float timeout)
541 std::list<u16> remove_queue;
543 MutexAutoLock listlock(m_map_mutex);
544 for(std::map<u16, IncomingSplitPacket*>::iterator i = m_buf.begin();
545 i != m_buf.end(); ++i)
547 IncomingSplitPacket *p = i->second;
548 // Reliable ones are not removed by timeout
549 if (p->reliable == true)
552 if (p->time >= timeout)
553 remove_queue.push_back(i->first);
556 for(std::list<u16>::iterator j = remove_queue.begin();
557 j != remove_queue.end(); ++j)
559 MutexAutoLock listlock(m_map_mutex);
560 LOG(dout_con<<"NOTE: Removing timed out unreliable split packet"<<std::endl);
570 u16 Channel::readNextIncomingSeqNum()
572 MutexAutoLock internal(m_internal_mutex);
573 return next_incoming_seqnum;
576 u16 Channel::incNextIncomingSeqNum()
578 MutexAutoLock internal(m_internal_mutex);
579 u16 retval = next_incoming_seqnum;
580 next_incoming_seqnum++;
584 u16 Channel::readNextSplitSeqNum()
586 MutexAutoLock internal(m_internal_mutex);
587 return next_outgoing_split_seqnum;
589 void Channel::setNextSplitSeqNum(u16 seqnum)
591 MutexAutoLock internal(m_internal_mutex);
592 next_outgoing_split_seqnum = seqnum;
595 u16 Channel::getOutgoingSequenceNumber(bool& successful)
597 MutexAutoLock internal(m_internal_mutex);
598 u16 retval = next_outgoing_seqnum;
599 u16 lowest_unacked_seqnumber;
601 /* shortcut if there ain't any packet in outgoing list */
602 if (outgoing_reliables_sent.empty())
604 next_outgoing_seqnum++;
608 if (outgoing_reliables_sent.getFirstSeqnum(lowest_unacked_seqnumber))
610 if (lowest_unacked_seqnumber < next_outgoing_seqnum) {
611 // ugly cast but this one is required in order to tell compiler we
612 // know about difference of two unsigned may be negative in general
613 // but we already made sure it won't happen in this case
614 if (((u16)(next_outgoing_seqnum - lowest_unacked_seqnumber)) > window_size) {
620 // ugly cast but this one is required in order to tell compiler we
621 // know about difference of two unsigned may be negative in general
622 // but we already made sure it won't happen in this case
623 if ((next_outgoing_seqnum + (u16)(SEQNUM_MAX - lowest_unacked_seqnumber)) >
631 next_outgoing_seqnum++;
635 u16 Channel::readOutgoingSequenceNumber()
637 MutexAutoLock internal(m_internal_mutex);
638 return next_outgoing_seqnum;
641 bool Channel::putBackSequenceNumber(u16 seqnum)
643 if (((seqnum + 1) % (SEQNUM_MAX+1)) == next_outgoing_seqnum) {
645 next_outgoing_seqnum = seqnum;
651 void Channel::UpdateBytesSent(unsigned int bytes, unsigned int packets)
653 MutexAutoLock internal(m_internal_mutex);
654 current_bytes_transfered += bytes;
655 current_packet_successfull += packets;
658 void Channel::UpdateBytesReceived(unsigned int bytes) {
659 MutexAutoLock internal(m_internal_mutex);
660 current_bytes_received += bytes;
663 void Channel::UpdateBytesLost(unsigned int bytes)
665 MutexAutoLock internal(m_internal_mutex);
666 current_bytes_lost += bytes;
670 void Channel::UpdatePacketLossCounter(unsigned int count)
672 MutexAutoLock internal(m_internal_mutex);
673 current_packet_loss += count;
676 void Channel::UpdatePacketTooLateCounter()
678 MutexAutoLock internal(m_internal_mutex);
679 current_packet_too_late++;
682 void Channel::UpdateTimers(float dtime,bool legacy_peer)
684 bpm_counter += dtime;
685 packet_loss_counter += dtime;
687 if (packet_loss_counter > 1.0)
689 packet_loss_counter -= 1.0;
691 unsigned int packet_loss = 11; /* use a neutral value for initialization */
692 unsigned int packets_successfull = 0;
693 //unsigned int packet_too_late = 0;
695 bool reasonable_amount_of_data_transmitted = false;
698 MutexAutoLock internal(m_internal_mutex);
699 packet_loss = current_packet_loss;
700 //packet_too_late = current_packet_too_late;
701 packets_successfull = current_packet_successfull;
703 if (current_bytes_transfered > (unsigned int) (window_size*512/2))
705 reasonable_amount_of_data_transmitted = true;
707 current_packet_loss = 0;
708 current_packet_too_late = 0;
709 current_packet_successfull = 0;
712 /* dynamic window size is only available for non legacy peers */
714 float successfull_to_lost_ratio = 0.0;
717 if (packets_successfull > 0) {
718 successfull_to_lost_ratio = packet_loss/packets_successfull;
720 else if (packet_loss > 0)
724 MIN_RELIABLE_WINDOW_SIZE);
730 if ((successfull_to_lost_ratio < 0.01) &&
731 (window_size < MAX_RELIABLE_WINDOW_SIZE))
733 /* don't even think about increasing if we didn't even
734 * use major parts of our window */
735 if (reasonable_amount_of_data_transmitted)
738 MAX_RELIABLE_WINDOW_SIZE);
740 else if ((successfull_to_lost_ratio < 0.05) &&
741 (window_size < MAX_RELIABLE_WINDOW_SIZE))
743 /* don't even think about increasing if we didn't even
744 * use major parts of our window */
745 if (reasonable_amount_of_data_transmitted)
748 MAX_RELIABLE_WINDOW_SIZE);
750 else if (successfull_to_lost_ratio > 0.15)
754 MIN_RELIABLE_WINDOW_SIZE);
756 else if (successfull_to_lost_ratio > 0.1)
760 MIN_RELIABLE_WINDOW_SIZE);
766 if (bpm_counter > 10.0)
769 MutexAutoLock internal(m_internal_mutex);
771 (((float) current_bytes_transfered)/bpm_counter)/1024.0;
772 current_bytes_transfered = 0;
774 (((float) current_bytes_lost)/bpm_counter)/1024.0;
775 current_bytes_lost = 0;
777 (((float) current_bytes_received)/bpm_counter)/1024.0;
778 current_bytes_received = 0;
782 if (cur_kbps > max_kbps)
787 if (cur_kbps_lost > max_kbps_lost)
789 max_kbps_lost = cur_kbps_lost;
792 if (cur_incoming_kbps > max_incoming_kbps) {
793 max_incoming_kbps = cur_incoming_kbps;
796 rate_samples = MYMIN(rate_samples+1,10);
797 float old_fraction = ((float) (rate_samples-1) )/( (float) rate_samples);
798 avg_kbps = avg_kbps * old_fraction +
799 cur_kbps * (1.0 - old_fraction);
800 avg_kbps_lost = avg_kbps_lost * old_fraction +
801 cur_kbps_lost * (1.0 - old_fraction);
802 avg_incoming_kbps = avg_incoming_kbps * old_fraction +
803 cur_incoming_kbps * (1.0 - old_fraction);
812 PeerHelper::PeerHelper(Peer* peer) :
815 if (peer && !peer->IncUseCount())
819 PeerHelper::~PeerHelper()
822 m_peer->DecUseCount();
827 PeerHelper& PeerHelper::operator=(Peer* peer)
830 if (peer && !peer->IncUseCount())
835 Peer* PeerHelper::operator->() const
840 Peer* PeerHelper::operator&() const
845 bool PeerHelper::operator!() {
849 bool PeerHelper::operator!=(void* ptr)
851 return ((void*) m_peer != ptr);
854 bool Peer::IncUseCount()
856 MutexAutoLock lock(m_exclusive_access_mutex);
858 if (!m_pending_deletion) {
866 void Peer::DecUseCount()
869 MutexAutoLock lock(m_exclusive_access_mutex);
870 sanity_check(m_usage > 0);
873 if (!((m_pending_deletion) && (m_usage == 0)))
879 void Peer::RTTStatistics(float rtt, const std::string &profiler_id,
880 unsigned int num_samples) {
882 if (m_last_rtt > 0) {
883 /* set min max values */
884 if (rtt < m_rtt.min_rtt)
886 if (rtt >= m_rtt.max_rtt)
889 /* do average calculation */
890 if (m_rtt.avg_rtt < 0.0)
893 m_rtt.avg_rtt = m_rtt.avg_rtt * (num_samples/(num_samples-1)) +
894 rtt * (1/num_samples);
896 /* do jitter calculation */
898 //just use some neutral value at beginning
899 float jitter = m_rtt.jitter_min;
901 if (rtt > m_last_rtt)
902 jitter = rtt-m_last_rtt;
904 if (rtt <= m_last_rtt)
905 jitter = m_last_rtt - rtt;
907 if (jitter < m_rtt.jitter_min)
908 m_rtt.jitter_min = jitter;
909 if (jitter >= m_rtt.jitter_max)
910 m_rtt.jitter_max = jitter;
912 if (m_rtt.jitter_avg < 0.0)
913 m_rtt.jitter_avg = jitter;
915 m_rtt.jitter_avg = m_rtt.jitter_avg * (num_samples/(num_samples-1)) +
916 jitter * (1/num_samples);
918 if (profiler_id != "") {
919 g_profiler->graphAdd(profiler_id + "_rtt", rtt);
920 g_profiler->graphAdd(profiler_id + "_jitter", jitter);
923 /* save values required for next loop */
927 bool Peer::isTimedOut(float timeout)
929 MutexAutoLock lock(m_exclusive_access_mutex);
930 u64 current_time = porting::getTimeMs();
932 float dtime = CALC_DTIME(m_last_timeout_check,current_time);
933 m_last_timeout_check = current_time;
935 m_timeout_counter += dtime;
937 return m_timeout_counter > timeout;
943 MutexAutoLock usage_lock(m_exclusive_access_mutex);
944 m_pending_deletion = true;
949 PROFILE(std::stringstream peerIdentifier1);
950 PROFILE(peerIdentifier1 << "runTimeouts[" << m_connection->getDesc()
951 << ";" << id << ";RELIABLE]");
952 PROFILE(g_profiler->remove(peerIdentifier1.str()));
953 PROFILE(std::stringstream peerIdentifier2);
954 PROFILE(peerIdentifier2 << "sendPackets[" << m_connection->getDesc()
955 << ";" << id << ";RELIABLE]");
956 PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier2.str(), SPT_AVG));
961 UDPPeer::UDPPeer(u16 a_id, Address a_address, Connection* connection) :
962 Peer(a_address,a_id,connection)
966 bool UDPPeer::getAddress(MTProtocols type,Address& toset)
968 if ((type == MTP_UDP) || (type == MTP_MINETEST_RELIABLE_UDP) || (type == MTP_PRIMARY))
977 void UDPPeer::setNonLegacyPeer()
979 m_legacy_peer = false;
980 for(unsigned int i=0; i< CHANNEL_COUNT; i++)
982 channels->setWindowSize(g_settings->getU16("max_packets_per_iteration"));
986 void UDPPeer::reportRTT(float rtt)
991 RTTStatistics(rtt,"rudp",MAX_RELIABLE_WINDOW_SIZE*10);
993 float timeout = getStat(AVG_RTT) * RESEND_TIMEOUT_FACTOR;
994 if (timeout < RESEND_TIMEOUT_MIN)
995 timeout = RESEND_TIMEOUT_MIN;
996 if (timeout > RESEND_TIMEOUT_MAX)
997 timeout = RESEND_TIMEOUT_MAX;
999 MutexAutoLock usage_lock(m_exclusive_access_mutex);
1000 resend_timeout = timeout;
1003 bool UDPPeer::Ping(float dtime,SharedBuffer<u8>& data)
1005 m_ping_timer += dtime;
1006 if (m_ping_timer >= PING_TIMEOUT)
1008 // Create and send PING packet
1009 writeU8(&data[0], TYPE_CONTROL);
1010 writeU8(&data[1], CONTROLTYPE_PING);
1017 void UDPPeer::PutReliableSendCommand(ConnectionCommand &c,
1018 unsigned int max_packet_size)
1020 if (m_pending_disconnect)
1023 if ( channels[c.channelnum].queued_commands.empty() &&
1024 /* don't queue more packets then window size */
1025 (channels[c.channelnum].queued_reliables.size()
1026 < (channels[c.channelnum].getWindowSize()/2))) {
1027 LOG(dout_con<<m_connection->getDesc()
1028 <<" processing reliable command for peer id: " << c.peer_id
1029 <<" data size: " << c.data.getSize() << std::endl);
1030 if (!processReliableSendCommand(c,max_packet_size)) {
1031 channels[c.channelnum].queued_commands.push_back(c);
1035 LOG(dout_con<<m_connection->getDesc()
1036 <<" Queueing reliable command for peer id: " << c.peer_id
1037 <<" data size: " << c.data.getSize() <<std::endl);
1038 channels[c.channelnum].queued_commands.push_back(c);
1042 bool UDPPeer::processReliableSendCommand(
1043 ConnectionCommand &c,
1044 unsigned int max_packet_size)
1046 if (m_pending_disconnect)
1049 u32 chunksize_max = max_packet_size
1051 - RELIABLE_HEADER_SIZE;
1053 sanity_check(c.data.getSize() < MAX_RELIABLE_WINDOW_SIZE*512);
1055 std::list<SharedBuffer<u8> > originals;
1056 u16 split_sequence_number = channels[c.channelnum].readNextSplitSeqNum();
1060 originals.push_back(c.data);
1063 originals = makeAutoSplitPacket(c.data, chunksize_max,split_sequence_number);
1064 channels[c.channelnum].setNextSplitSeqNum(split_sequence_number);
1067 bool have_sequence_number = true;
1068 bool have_initial_sequence_number = false;
1069 std::queue<BufferedPacket> toadd;
1070 volatile u16 initial_sequence_number = 0;
1072 for(std::list<SharedBuffer<u8> >::iterator i = originals.begin();
1073 i != originals.end(); ++i)
1075 u16 seqnum = channels[c.channelnum].getOutgoingSequenceNumber(have_sequence_number);
1077 /* oops, we don't have enough sequence numbers to send this packet */
1078 if (!have_sequence_number)
1081 if (!have_initial_sequence_number)
1083 initial_sequence_number = seqnum;
1084 have_initial_sequence_number = true;
1087 SharedBuffer<u8> reliable = makeReliablePacket(*i, seqnum);
1089 // Add base headers and make a packet
1090 BufferedPacket p = con::makePacket(address, reliable,
1091 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1097 if (have_sequence_number) {
1098 volatile u16 pcount = 0;
1099 while(toadd.size() > 0) {
1100 BufferedPacket p = toadd.front();
1102 // LOG(dout_con<<connection->getDesc()
1103 // << " queuing reliable packet for peer_id: " << c.peer_id
1104 // << " channel: " << (c.channelnum&0xFF)
1105 // << " seqnum: " << readU16(&p.data[BASE_HEADER_SIZE+1])
1107 channels[c.channelnum].queued_reliables.push(p);
1110 sanity_check(channels[c.channelnum].queued_reliables.size() < 0xFFFF);
1114 volatile u16 packets_available = toadd.size();
1115 /* we didn't get a single sequence number no need to fill queue */
1116 if (!have_initial_sequence_number)
1120 while(toadd.size() > 0) {
1124 bool successfully_put_back_sequence_number
1125 = channels[c.channelnum].putBackSequenceNumber(
1126 (initial_sequence_number+toadd.size() % (SEQNUM_MAX+1)));
1128 FATAL_ERROR_IF(!successfully_put_back_sequence_number, "error");
1130 LOG(dout_con<<m_connection->getDesc()
1131 << " Windowsize exceeded on reliable sending "
1132 << c.data.getSize() << " bytes"
1133 << std::endl << "\t\tinitial_sequence_number: "
1134 << initial_sequence_number
1135 << std::endl << "\t\tgot at most : "
1136 << packets_available << " packets"
1137 << std::endl << "\t\tpackets queued : "
1138 << channels[c.channelnum].outgoing_reliables_sent.size()
1144 void UDPPeer::RunCommandQueues(
1145 unsigned int max_packet_size,
1146 unsigned int maxcommands,
1147 unsigned int maxtransfer)
1150 for (unsigned int i = 0; i < CHANNEL_COUNT; i++) {
1151 unsigned int commands_processed = 0;
1153 if ((channels[i].queued_commands.size() > 0) &&
1154 (channels[i].queued_reliables.size() < maxtransfer) &&
1155 (commands_processed < maxcommands)) {
1157 ConnectionCommand c = channels[i].queued_commands.front();
1159 LOG(dout_con << m_connection->getDesc()
1160 << " processing queued reliable command " << std::endl);
1162 // Packet is processed, remove it from queue
1163 if (processReliableSendCommand(c,max_packet_size)) {
1164 channels[i].queued_commands.pop_front();
1166 LOG(dout_con << m_connection->getDesc()
1167 << " Failed to queue packets for peer_id: " << c.peer_id
1168 << ", delaying sending of " << c.data.getSize()
1169 << " bytes" << std::endl);
1172 catch (ItemNotFoundException &e) {
1173 // intentionally empty
1179 u16 UDPPeer::getNextSplitSequenceNumber(u8 channel)
1181 assert(channel < CHANNEL_COUNT); // Pre-condition
1182 return channels[channel].readNextSplitSeqNum();
1185 void UDPPeer::setNextSplitSequenceNumber(u8 channel, u16 seqnum)
1187 assert(channel < CHANNEL_COUNT); // Pre-condition
1188 channels[channel].setNextSplitSeqNum(seqnum);
1191 SharedBuffer<u8> UDPPeer::addSpiltPacket(u8 channel,
1192 BufferedPacket toadd,
1195 assert(channel < CHANNEL_COUNT); // Pre-condition
1196 return channels[channel].incoming_splits.insert(toadd,reliable);
1199 /******************************************************************************/
1200 /* Connection Threads */
1201 /******************************************************************************/
1203 ConnectionSendThread::ConnectionSendThread(unsigned int max_packet_size,
1205 Thread("ConnectionSend"),
1206 m_max_packet_size(max_packet_size),
1208 m_max_data_packets_per_iteration(g_settings->getU16("max_packets_per_iteration"))
1212 void * ConnectionSendThread::run()
1214 assert(m_connection);
1216 LOG(dout_con<<m_connection->getDesc()
1217 <<"ConnectionSend thread started"<<std::endl);
1219 u64 curtime = porting::getTimeMs();
1220 u64 lasttime = curtime;
1222 PROFILE(std::stringstream ThreadIdentifier);
1223 PROFILE(ThreadIdentifier << "ConnectionSend: [" << m_connection->getDesc() << "]");
1225 /* if stop is requested don't stop immediately but try to send all */
1227 while(!stopRequested() || packetsQueued()) {
1228 BEGIN_DEBUG_EXCEPTION_HANDLER
1229 PROFILE(ScopeProfiler sp(g_profiler, ThreadIdentifier.str(), SPT_AVG));
1231 m_iteration_packets_avaialble = m_max_data_packets_per_iteration;
1233 /* wait for trigger or timeout */
1234 m_send_sleep_semaphore.wait(50);
1236 /* remove all triggers */
1237 while(m_send_sleep_semaphore.wait(0)) {}
1240 curtime = porting::getTimeMs();
1241 float dtime = CALC_DTIME(lasttime,curtime);
1243 /* first do all the reliable stuff */
1246 /* translate commands to packets */
1247 ConnectionCommand c = m_connection->m_command_queue.pop_frontNoEx(0);
1248 while(c.type != CONNCMD_NONE)
1251 processReliableCommand(c);
1253 processNonReliableCommand(c);
1255 c = m_connection->m_command_queue.pop_frontNoEx(0);
1258 /* send non reliable packets */
1261 END_DEBUG_EXCEPTION_HANDLER
1264 PROFILE(g_profiler->remove(ThreadIdentifier.str()));
1268 void ConnectionSendThread::Trigger()
1270 m_send_sleep_semaphore.post();
1273 bool ConnectionSendThread::packetsQueued()
1275 std::list<u16> peerIds = m_connection->getPeerIDs();
1277 if (!m_outgoing_queue.empty() && !peerIds.empty())
1280 for(std::list<u16>::iterator j = peerIds.begin();
1281 j != peerIds.end(); ++j)
1283 PeerHelper peer = m_connection->getPeerNoEx(*j);
1288 if (dynamic_cast<UDPPeer*>(&peer) == 0)
1291 for(u16 i=0; i < CHANNEL_COUNT; i++) {
1292 Channel *channel = &(dynamic_cast<UDPPeer*>(&peer))->channels[i];
1294 if (channel->queued_commands.size() > 0) {
1304 void ConnectionSendThread::runTimeouts(float dtime)
1306 std::list<u16> timeouted_peers;
1307 std::list<u16> peerIds = m_connection->getPeerIDs();
1309 for(std::list<u16>::iterator j = peerIds.begin();
1310 j != peerIds.end(); ++j)
1312 PeerHelper peer = m_connection->getPeerNoEx(*j);
1317 if (dynamic_cast<UDPPeer*>(&peer) == 0)
1320 PROFILE(std::stringstream peerIdentifier);
1321 PROFILE(peerIdentifier << "runTimeouts[" << m_connection->getDesc()
1322 << ";" << *j << ";RELIABLE]");
1323 PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier.str(), SPT_AVG));
1325 SharedBuffer<u8> data(2); // data for sending ping, required here because of goto
1330 if (peer->isTimedOut(m_timeout))
1332 infostream<<m_connection->getDesc()
1333 <<"RunTimeouts(): Peer "<<peer->id
1335 <<" (source=peer->timeout_counter)"
1337 // Add peer to the list
1338 timeouted_peers.push_back(peer->id);
1339 // Don't bother going through the buffers of this one
1343 float resend_timeout = dynamic_cast<UDPPeer*>(&peer)->getResendTimeout();
1344 bool retry_count_exceeded = false;
1345 for(u16 i=0; i<CHANNEL_COUNT; i++)
1347 std::list<BufferedPacket> timed_outs;
1348 Channel *channel = &(dynamic_cast<UDPPeer*>(&peer))->channels[i];
1350 if (dynamic_cast<UDPPeer*>(&peer)->getLegacyPeer())
1351 channel->setWindowSize(g_settings->getU16("workaround_window_size"));
1353 // Remove timed out incomplete unreliable split packets
1354 channel->incoming_splits.removeUnreliableTimedOuts(dtime, m_timeout);
1356 // Increment reliable packet times
1357 channel->outgoing_reliables_sent.incrementTimeouts(dtime);
1359 unsigned int numpeers = m_connection->m_peers.size();
1364 // Re-send timed out outgoing reliables
1365 timed_outs = channel->
1366 outgoing_reliables_sent.getTimedOuts(resend_timeout,
1367 (m_max_data_packets_per_iteration/numpeers));
1369 channel->UpdatePacketLossCounter(timed_outs.size());
1370 g_profiler->graphAdd("packets_lost", timed_outs.size());
1372 m_iteration_packets_avaialble -= timed_outs.size();
1374 for(std::list<BufferedPacket>::iterator k = timed_outs.begin();
1375 k != timed_outs.end(); ++k)
1377 u16 peer_id = readPeerId(*(k->data));
1378 u8 channelnum = readChannel(*(k->data));
1379 u16 seqnum = readU16(&(k->data[BASE_HEADER_SIZE+1]));
1381 channel->UpdateBytesLost(k->data.getSize());
1384 if (k-> resend_count > MAX_RELIABLE_RETRY) {
1385 retry_count_exceeded = true;
1386 timeouted_peers.push_back(peer->id);
1387 /* no need to check additional packets if a single one did timeout*/
1391 LOG(derr_con<<m_connection->getDesc()
1392 <<"RE-SENDING timed-out RELIABLE to "
1393 << k->address.serializeString()
1394 << "(t/o="<<resend_timeout<<"): "
1395 <<"from_peer_id="<<peer_id
1396 <<", channel="<<((int)channelnum&0xff)
1397 <<", seqnum="<<seqnum
1402 // do not handle rtt here as we can't decide if this packet was
1403 // lost or really takes more time to transmit
1406 if (retry_count_exceeded) {
1407 break; /* no need to check other channels if we already did timeout */
1410 channel->UpdateTimers(dtime,dynamic_cast<UDPPeer*>(&peer)->getLegacyPeer());
1413 /* skip to next peer if we did timeout */
1414 if (retry_count_exceeded)
1417 /* send ping if necessary */
1418 if (dynamic_cast<UDPPeer*>(&peer)->Ping(dtime,data)) {
1419 LOG(dout_con<<m_connection->getDesc()
1420 <<"Sending ping for peer_id: "
1421 << dynamic_cast<UDPPeer*>(&peer)->id <<std::endl);
1422 /* this may fail if there ain't a sequence number left */
1423 if (!rawSendAsPacket(dynamic_cast<UDPPeer*>(&peer)->id, 0, data, true))
1425 //retrigger with reduced ping interval
1426 dynamic_cast<UDPPeer*>(&peer)->Ping(4.0,data);
1430 dynamic_cast<UDPPeer*>(&peer)->RunCommandQueues(m_max_packet_size,
1431 m_max_commands_per_iteration,
1432 m_max_packets_requeued);
1435 // Remove timed out peers
1436 for(std::list<u16>::iterator i = timeouted_peers.begin();
1437 i != timeouted_peers.end(); ++i)
1439 LOG(derr_con<<m_connection->getDesc()
1440 <<"RunTimeouts(): Removing peer "<<(*i)<<std::endl);
1441 m_connection->deletePeer(*i, true);
1445 void ConnectionSendThread::rawSend(const BufferedPacket &packet)
1448 m_connection->m_udpSocket.Send(packet.address, *packet.data,
1449 packet.data.getSize());
1450 LOG(dout_con <<m_connection->getDesc()
1451 << " rawSend: " << packet.data.getSize()
1452 << " bytes sent" << std::endl);
1453 } catch(SendFailedException &e) {
1454 LOG(derr_con<<m_connection->getDesc()
1455 <<"Connection::rawSend(): SendFailedException: "
1456 <<packet.address.serializeString()<<std::endl);
1460 void ConnectionSendThread::sendAsPacketReliable(BufferedPacket& p, Channel* channel)
1463 p.absolute_send_time = porting::getTimeMs();
1464 // Buffer the packet
1465 channel->outgoing_reliables_sent.insert(p,
1466 (channel->readOutgoingSequenceNumber() - MAX_RELIABLE_WINDOW_SIZE)
1467 % (MAX_RELIABLE_WINDOW_SIZE+1));
1469 catch(AlreadyExistsException &e)
1471 LOG(derr_con<<m_connection->getDesc()
1472 <<"WARNING: Going to send a reliable packet"
1473 <<" in outgoing buffer" <<std::endl);
1480 bool ConnectionSendThread::rawSendAsPacket(u16 peer_id, u8 channelnum,
1481 SharedBuffer<u8> data, bool reliable)
1483 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
1485 LOG(dout_con<<m_connection->getDesc()
1486 <<" INFO: dropped packet for non existent peer_id: "
1487 << peer_id << std::endl);
1488 FATAL_ERROR_IF(!reliable, "Trying to send raw packet reliable but no peer found!");
1491 Channel *channel = &(dynamic_cast<UDPPeer*>(&peer)->channels[channelnum]);
1495 bool have_sequence_number_for_raw_packet = true;
1497 channel->getOutgoingSequenceNumber(have_sequence_number_for_raw_packet);
1499 if (!have_sequence_number_for_raw_packet)
1502 SharedBuffer<u8> reliable = makeReliablePacket(data, seqnum);
1503 Address peer_address;
1504 peer->getAddress(MTP_MINETEST_RELIABLE_UDP, peer_address);
1506 // Add base headers and make a packet
1507 BufferedPacket p = con::makePacket(peer_address, reliable,
1508 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1511 // first check if our send window is already maxed out
1512 if (channel->outgoing_reliables_sent.size()
1513 < channel->getWindowSize()) {
1514 LOG(dout_con<<m_connection->getDesc()
1515 <<" INFO: sending a reliable packet to peer_id " << peer_id
1516 <<" channel: " << channelnum
1517 <<" seqnum: " << seqnum << std::endl);
1518 sendAsPacketReliable(p,channel);
1522 LOG(dout_con<<m_connection->getDesc()
1523 <<" INFO: queueing reliable packet for peer_id: " << peer_id
1524 <<" channel: " << channelnum
1525 <<" seqnum: " << seqnum << std::endl);
1526 channel->queued_reliables.push(p);
1532 Address peer_address;
1534 if (peer->getAddress(MTP_UDP, peer_address))
1536 // Add base headers and make a packet
1537 BufferedPacket p = con::makePacket(peer_address, data,
1538 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1546 LOG(dout_con<<m_connection->getDesc()
1547 <<" INFO: dropped unreliable packet for peer_id: " << peer_id
1548 <<" because of (yet) missing udp address" << std::endl);
1557 void ConnectionSendThread::processReliableCommand(ConnectionCommand &c)
1559 assert(c.reliable); // Pre-condition
1563 LOG(dout_con<<m_connection->getDesc()
1564 <<"UDP processing reliable CONNCMD_NONE"<<std::endl);
1568 LOG(dout_con<<m_connection->getDesc()
1569 <<"UDP processing reliable CONNCMD_SEND"<<std::endl);
1573 case CONNCMD_SEND_TO_ALL:
1574 LOG(dout_con<<m_connection->getDesc()
1575 <<"UDP processing CONNCMD_SEND_TO_ALL"<<std::endl);
1576 sendToAllReliable(c);
1579 case CONCMD_CREATE_PEER:
1580 LOG(dout_con<<m_connection->getDesc()
1581 <<"UDP processing reliable CONCMD_CREATE_PEER"<<std::endl);
1582 if (!rawSendAsPacket(c.peer_id,c.channelnum,c.data,c.reliable))
1584 /* put to queue if we couldn't send it immediately */
1589 case CONCMD_DISABLE_LEGACY:
1590 LOG(dout_con<<m_connection->getDesc()
1591 <<"UDP processing reliable CONCMD_DISABLE_LEGACY"<<std::endl);
1592 if (!rawSendAsPacket(c.peer_id,c.channelnum,c.data,c.reliable))
1594 /* put to queue if we couldn't send it immediately */
1600 case CONNCMD_CONNECT:
1601 case CONNCMD_DISCONNECT:
1603 FATAL_ERROR("Got command that shouldn't be reliable as reliable command");
1605 LOG(dout_con<<m_connection->getDesc()
1606 <<" Invalid reliable command type: " << c.type <<std::endl);
1611 void ConnectionSendThread::processNonReliableCommand(ConnectionCommand &c)
1613 assert(!c.reliable); // Pre-condition
1617 LOG(dout_con<<m_connection->getDesc()
1618 <<" UDP processing CONNCMD_NONE"<<std::endl);
1621 LOG(dout_con<<m_connection->getDesc()
1622 <<" UDP processing CONNCMD_SERVE port="
1623 <<c.address.serializeString()<<std::endl);
1626 case CONNCMD_CONNECT:
1627 LOG(dout_con<<m_connection->getDesc()
1628 <<" UDP processing CONNCMD_CONNECT"<<std::endl);
1631 case CONNCMD_DISCONNECT:
1632 LOG(dout_con<<m_connection->getDesc()
1633 <<" UDP processing CONNCMD_DISCONNECT"<<std::endl);
1636 case CONNCMD_DISCONNECT_PEER:
1637 LOG(dout_con<<m_connection->getDesc()
1638 <<" UDP processing CONNCMD_DISCONNECT_PEER"<<std::endl);
1639 disconnect_peer(c.peer_id);
1642 LOG(dout_con<<m_connection->getDesc()
1643 <<" UDP processing CONNCMD_SEND"<<std::endl);
1644 send(c.peer_id, c.channelnum, c.data);
1646 case CONNCMD_SEND_TO_ALL:
1647 LOG(dout_con<<m_connection->getDesc()
1648 <<" UDP processing CONNCMD_SEND_TO_ALL"<<std::endl);
1649 sendToAll(c.channelnum, c.data);
1652 LOG(dout_con<<m_connection->getDesc()
1653 <<" UDP processing CONCMD_ACK"<<std::endl);
1654 sendAsPacket(c.peer_id,c.channelnum,c.data,true);
1656 case CONCMD_CREATE_PEER:
1657 FATAL_ERROR("Got command that should be reliable as unreliable command");
1659 LOG(dout_con<<m_connection->getDesc()
1660 <<" Invalid command type: " << c.type <<std::endl);
1664 void ConnectionSendThread::serve(Address bind_address)
1666 LOG(dout_con<<m_connection->getDesc()
1667 <<"UDP serving at port " << bind_address.serializeString() <<std::endl);
1669 m_connection->m_udpSocket.Bind(bind_address);
1670 m_connection->SetPeerID(PEER_ID_SERVER);
1672 catch(SocketException &e) {
1676 m_connection->putEvent(ce);
1680 void ConnectionSendThread::connect(Address address)
1682 LOG(dout_con<<m_connection->getDesc()<<" connecting to "<<address.serializeString()
1683 <<":"<<address.getPort()<<std::endl);
1685 UDPPeer *peer = m_connection->createServerPeer(address);
1689 e.peerAdded(peer->id, peer->address);
1690 m_connection->putEvent(e);
1694 if (address.isIPv6())
1695 bind_addr.setAddress((IPv6AddressBytes*) NULL);
1697 bind_addr.setAddress(0,0,0,0);
1699 m_connection->m_udpSocket.Bind(bind_addr);
1701 // Send a dummy packet to server with peer_id = PEER_ID_INEXISTENT
1702 m_connection->SetPeerID(PEER_ID_INEXISTENT);
1703 NetworkPacket pkt(0,0);
1704 m_connection->Send(PEER_ID_SERVER, 0, &pkt, true);
1707 void ConnectionSendThread::disconnect()
1709 LOG(dout_con<<m_connection->getDesc()<<" disconnecting"<<std::endl);
1711 // Create and send DISCO packet
1712 SharedBuffer<u8> data(2);
1713 writeU8(&data[0], TYPE_CONTROL);
1714 writeU8(&data[1], CONTROLTYPE_DISCO);
1718 std::list<u16> peerids = m_connection->getPeerIDs();
1720 for (std::list<u16>::iterator i = peerids.begin();
1724 sendAsPacket(*i, 0,data,false);
1728 void ConnectionSendThread::disconnect_peer(u16 peer_id)
1730 LOG(dout_con<<m_connection->getDesc()<<" disconnecting peer"<<std::endl);
1732 // Create and send DISCO packet
1733 SharedBuffer<u8> data(2);
1734 writeU8(&data[0], TYPE_CONTROL);
1735 writeU8(&data[1], CONTROLTYPE_DISCO);
1736 sendAsPacket(peer_id, 0,data,false);
1738 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
1743 if (dynamic_cast<UDPPeer*>(&peer) == 0)
1748 dynamic_cast<UDPPeer*>(&peer)->m_pending_disconnect = true;
1751 void ConnectionSendThread::send(u16 peer_id, u8 channelnum,
1752 SharedBuffer<u8> data)
1754 assert(channelnum < CHANNEL_COUNT); // Pre-condition
1756 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
1759 LOG(dout_con<<m_connection->getDesc()<<" peer: peer_id="<<peer_id
1760 << ">>>NOT<<< found on sending packet"
1761 << ", channel " << (channelnum % 0xFF)
1762 << ", size: " << data.getSize() <<std::endl);
1766 LOG(dout_con<<m_connection->getDesc()<<" sending to peer_id="<<peer_id
1767 << ", channel " << (channelnum % 0xFF)
1768 << ", size: " << data.getSize() <<std::endl);
1770 u16 split_sequence_number = peer->getNextSplitSequenceNumber(channelnum);
1772 u32 chunksize_max = m_max_packet_size - BASE_HEADER_SIZE;
1773 std::list<SharedBuffer<u8> > originals;
1775 originals = makeAutoSplitPacket(data, chunksize_max,split_sequence_number);
1777 peer->setNextSplitSequenceNumber(channelnum,split_sequence_number);
1779 for(std::list<SharedBuffer<u8> >::iterator i = originals.begin();
1780 i != originals.end(); ++i)
1782 SharedBuffer<u8> original = *i;
1783 sendAsPacket(peer_id, channelnum, original);
1787 void ConnectionSendThread::sendReliable(ConnectionCommand &c)
1789 PeerHelper peer = m_connection->getPeerNoEx(c.peer_id);
1793 peer->PutReliableSendCommand(c,m_max_packet_size);
1796 void ConnectionSendThread::sendToAll(u8 channelnum, SharedBuffer<u8> data)
1798 std::list<u16> peerids = m_connection->getPeerIDs();
1800 for (std::list<u16>::iterator i = peerids.begin();
1804 send(*i, channelnum, data);
1808 void ConnectionSendThread::sendToAllReliable(ConnectionCommand &c)
1810 std::list<u16> peerids = m_connection->getPeerIDs();
1812 for (std::list<u16>::iterator i = peerids.begin();
1816 PeerHelper peer = m_connection->getPeerNoEx(*i);
1821 peer->PutReliableSendCommand(c,m_max_packet_size);
1825 void ConnectionSendThread::sendPackets(float dtime)
1827 std::list<u16> peerIds = m_connection->getPeerIDs();
1828 std::list<u16> pendingDisconnect;
1829 std::map<u16,bool> pending_unreliable;
1831 for(std::list<u16>::iterator
1832 j = peerIds.begin();
1833 j != peerIds.end(); ++j)
1835 PeerHelper peer = m_connection->getPeerNoEx(*j);
1836 //peer may have been removed
1838 LOG(dout_con<<m_connection->getDesc()<< " Peer not found: peer_id=" << *j << std::endl);
1841 peer->m_increment_packets_remaining = m_iteration_packets_avaialble/m_connection->m_peers.size();
1843 if (dynamic_cast<UDPPeer*>(&peer) == 0)
1848 if (dynamic_cast<UDPPeer*>(&peer)->m_pending_disconnect)
1850 pendingDisconnect.push_back(*j);
1853 PROFILE(std::stringstream peerIdentifier);
1854 PROFILE(peerIdentifier << "sendPackets[" << m_connection->getDesc() << ";" << *j << ";RELIABLE]");
1855 PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier.str(), SPT_AVG));
1857 LOG(dout_con<<m_connection->getDesc()
1858 << " Handle per peer queues: peer_id=" << *j
1859 << " packet quota: " << peer->m_increment_packets_remaining << std::endl);
1860 // first send queued reliable packets for all peers (if possible)
1861 for (unsigned int i=0; i < CHANNEL_COUNT; i++)
1863 u16 next_to_ack = 0;
1864 dynamic_cast<UDPPeer*>(&peer)->channels[i].outgoing_reliables_sent.getFirstSeqnum(next_to_ack);
1865 u16 next_to_receive = 0;
1866 dynamic_cast<UDPPeer*>(&peer)->channels[i].incoming_reliables.getFirstSeqnum(next_to_receive);
1868 LOG(dout_con<<m_connection->getDesc()<< "\t channel: "
1869 << i << ", peer quota:"
1870 << peer->m_increment_packets_remaining
1872 << "\t\t\treliables on wire: "
1873 << dynamic_cast<UDPPeer*>(&peer)->channels[i].outgoing_reliables_sent.size()
1874 << ", waiting for ack for " << next_to_ack
1876 << "\t\t\tincoming_reliables: "
1877 << dynamic_cast<UDPPeer*>(&peer)->channels[i].incoming_reliables.size()
1878 << ", next reliable packet: "
1879 << dynamic_cast<UDPPeer*>(&peer)->channels[i].readNextIncomingSeqNum()
1880 << ", next queued: " << next_to_receive
1882 << "\t\t\treliables queued : "
1883 << dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.size()
1885 << "\t\t\tqueued commands : "
1886 << dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_commands.size()
1889 while ((dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.size() > 0) &&
1890 (dynamic_cast<UDPPeer*>(&peer)->channels[i].outgoing_reliables_sent.size()
1891 < dynamic_cast<UDPPeer*>(&peer)->channels[i].getWindowSize())&&
1892 (peer->m_increment_packets_remaining > 0))
1894 BufferedPacket p = dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.front();
1895 dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.pop();
1896 Channel* channel = &(dynamic_cast<UDPPeer*>(&peer)->channels[i]);
1897 LOG(dout_con<<m_connection->getDesc()
1898 <<" INFO: sending a queued reliable packet "
1900 <<", seqnum: " << readU16(&p.data[BASE_HEADER_SIZE+1])
1902 sendAsPacketReliable(p,channel);
1903 peer->m_increment_packets_remaining--;
1908 if (m_outgoing_queue.size())
1910 LOG(dout_con<<m_connection->getDesc()
1911 << " Handle non reliable queue ("
1912 << m_outgoing_queue.size() << " pkts)" << std::endl);
1915 unsigned int initial_queuesize = m_outgoing_queue.size();
1916 /* send non reliable packets*/
1917 for(unsigned int i=0;i < initial_queuesize;i++) {
1918 OutgoingPacket packet = m_outgoing_queue.front();
1919 m_outgoing_queue.pop();
1921 if (packet.reliable)
1924 PeerHelper peer = m_connection->getPeerNoEx(packet.peer_id);
1926 LOG(dout_con<<m_connection->getDesc()
1927 <<" Outgoing queue: peer_id="<<packet.peer_id
1928 << ">>>NOT<<< found on sending packet"
1929 << ", channel " << (packet.channelnum % 0xFF)
1930 << ", size: " << packet.data.getSize() <<std::endl);
1933 /* send acks immediately */
1934 else if (packet.ack)
1936 rawSendAsPacket(packet.peer_id, packet.channelnum,
1937 packet.data, packet.reliable);
1938 peer->m_increment_packets_remaining =
1939 MYMIN(0,peer->m_increment_packets_remaining--);
1942 ( peer->m_increment_packets_remaining > 0) ||
1943 (stopRequested())) {
1944 rawSendAsPacket(packet.peer_id, packet.channelnum,
1945 packet.data, packet.reliable);
1946 peer->m_increment_packets_remaining--;
1949 m_outgoing_queue.push(packet);
1950 pending_unreliable[packet.peer_id] = true;
1954 for(std::list<u16>::iterator
1955 k = pendingDisconnect.begin();
1956 k != pendingDisconnect.end(); ++k)
1958 if (!pending_unreliable[*k])
1960 m_connection->deletePeer(*k,false);
1965 void ConnectionSendThread::sendAsPacket(u16 peer_id, u8 channelnum,
1966 SharedBuffer<u8> data, bool ack)
1968 OutgoingPacket packet(peer_id, channelnum, data, false, ack);
1969 m_outgoing_queue.push(packet);
1972 ConnectionReceiveThread::ConnectionReceiveThread(unsigned int max_packet_size) :
1973 Thread("ConnectionReceive")
1977 void * ConnectionReceiveThread::run()
1979 assert(m_connection);
1981 LOG(dout_con<<m_connection->getDesc()
1982 <<"ConnectionReceive thread started"<<std::endl);
1984 PROFILE(std::stringstream ThreadIdentifier);
1985 PROFILE(ThreadIdentifier << "ConnectionReceive: [" << m_connection->getDesc() << "]");
1987 #ifdef DEBUG_CONNECTION_KBPS
1988 u64 curtime = porting::getTimeMs();
1989 u64 lasttime = curtime;
1990 float debug_print_timer = 0.0;
1993 while(!stopRequested()) {
1994 BEGIN_DEBUG_EXCEPTION_HANDLER
1995 PROFILE(ScopeProfiler sp(g_profiler, ThreadIdentifier.str(), SPT_AVG));
1997 #ifdef DEBUG_CONNECTION_KBPS
1999 curtime = porting::getTimeMs();
2000 float dtime = CALC_DTIME(lasttime,curtime);
2003 /* receive packets */
2006 #ifdef DEBUG_CONNECTION_KBPS
2007 debug_print_timer += dtime;
2008 if (debug_print_timer > 20.0) {
2009 debug_print_timer -= 20.0;
2011 std::list<u16> peerids = m_connection->getPeerIDs();
2013 for (std::list<u16>::iterator i = peerids.begin();
2017 PeerHelper peer = m_connection->getPeerNoEx(*i);
2021 float peer_current = 0.0;
2022 float peer_loss = 0.0;
2023 float avg_rate = 0.0;
2024 float avg_loss = 0.0;
2026 for(u16 j=0; j<CHANNEL_COUNT; j++)
2028 peer_current +=peer->channels[j].getCurrentDownloadRateKB();
2029 peer_loss += peer->channels[j].getCurrentLossRateKB();
2030 avg_rate += peer->channels[j].getAvgDownloadRateKB();
2031 avg_loss += peer->channels[j].getAvgLossRateKB();
2034 std::stringstream output;
2035 output << std::fixed << std::setprecision(1);
2036 output << "OUT to Peer " << *i << " RATES (good / loss) " << std::endl;
2037 output << "\tcurrent (sum): " << peer_current << "kb/s "<< peer_loss << "kb/s" << std::endl;
2038 output << "\taverage (sum): " << avg_rate << "kb/s "<< avg_loss << "kb/s" << std::endl;
2039 output << std::setfill(' ');
2040 for(u16 j=0; j<CHANNEL_COUNT; j++)
2042 output << "\tcha " << j << ":"
2043 << " CUR: " << std::setw(6) << peer->channels[j].getCurrentDownloadRateKB() <<"kb/s"
2044 << " AVG: " << std::setw(6) << peer->channels[j].getAvgDownloadRateKB() <<"kb/s"
2045 << " MAX: " << std::setw(6) << peer->channels[j].getMaxDownloadRateKB() <<"kb/s"
2047 << " CUR: " << std::setw(6) << peer->channels[j].getCurrentLossRateKB() <<"kb/s"
2048 << " AVG: " << std::setw(6) << peer->channels[j].getAvgLossRateKB() <<"kb/s"
2049 << " MAX: " << std::setw(6) << peer->channels[j].getMaxLossRateKB() <<"kb/s"
2050 << " / WS: " << peer->channels[j].getWindowSize()
2054 fprintf(stderr,"%s\n",output.str().c_str());
2058 END_DEBUG_EXCEPTION_HANDLER
2061 PROFILE(g_profiler->remove(ThreadIdentifier.str()));
2065 // Receive packets from the network and buffers and create ConnectionEvents
2066 void ConnectionReceiveThread::receive()
2068 // use IPv6 minimum allowed MTU as receive buffer size as this is
2069 // theoretical reliable upper boundary of a udp packet for all IPv6 enabled
2071 unsigned int packet_maxsize = 1500;
2072 SharedBuffer<u8> packetdata(packet_maxsize);
2074 bool packet_queued = true;
2076 unsigned int loop_count = 0;
2078 /* first of all read packets from socket */
2079 /* check for incoming data available */
2080 while( (loop_count < 10) &&
2081 (m_connection->m_udpSocket.WaitData(50))) {
2084 if (packet_queued) {
2085 bool data_left = true;
2087 SharedBuffer<u8> resultdata;
2090 data_left = getFromBuffers(peer_id, resultdata);
2093 e.dataReceived(peer_id, resultdata);
2094 m_connection->putEvent(e);
2097 catch(ProcessedSilentlyException &e) {
2098 /* try reading again */
2101 packet_queued = false;
2105 s32 received_size = m_connection->m_udpSocket.Receive(sender, *packetdata, packet_maxsize);
2107 if ((received_size < BASE_HEADER_SIZE) ||
2108 (readU32(&packetdata[0]) != m_connection->GetProtocolID()))
2110 LOG(derr_con<<m_connection->getDesc()
2111 <<"Receive(): Invalid incoming packet, "
2112 <<"size: " << received_size
2114 << ((received_size >= 4) ? readU32(&packetdata[0]) : -1)
2119 u16 peer_id = readPeerId(*packetdata);
2120 u8 channelnum = readChannel(*packetdata);
2122 if (channelnum > CHANNEL_COUNT-1) {
2123 LOG(derr_con<<m_connection->getDesc()
2124 <<"Receive(): Invalid channel "<<channelnum<<std::endl);
2125 throw InvalidIncomingDataException("Channel doesn't exist");
2128 /* Try to identify peer by sender address (may happen on join) */
2129 if (peer_id == PEER_ID_INEXISTENT) {
2130 peer_id = m_connection->lookupPeer(sender);
2131 // We do not have to remind the peer of its
2132 // peer id as the CONTROLTYPE_SET_PEER_ID
2133 // command was sent reliably.
2136 /* The peer was not found in our lists. Add it. */
2137 if (peer_id == PEER_ID_INEXISTENT) {
2138 peer_id = m_connection->createPeer(sender, MTP_MINETEST_RELIABLE_UDP, 0);
2141 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
2144 LOG(dout_con<<m_connection->getDesc()
2145 <<" got packet from unknown peer_id: "
2146 <<peer_id<<" Ignoring."<<std::endl);
2150 // Validate peer address
2152 Address peer_address;
2154 if (peer->getAddress(MTP_UDP, peer_address)) {
2155 if (peer_address != sender) {
2156 LOG(derr_con<<m_connection->getDesc()
2157 <<m_connection->getDesc()
2158 <<" Peer "<<peer_id<<" sending from different address."
2159 " Ignoring."<<std::endl);
2165 bool invalid_address = true;
2166 if (invalid_address) {
2167 LOG(derr_con<<m_connection->getDesc()
2168 <<m_connection->getDesc()
2169 <<" Peer "<<peer_id<<" unknown."
2170 " Ignoring."<<std::endl);
2175 peer->ResetTimeout();
2177 Channel *channel = 0;
2179 if (dynamic_cast<UDPPeer*>(&peer) != 0)
2181 channel = &(dynamic_cast<UDPPeer*>(&peer)->channels[channelnum]);
2185 channel->UpdateBytesReceived(received_size);
2188 // Throw the received packet to channel->processPacket()
2190 // Make a new SharedBuffer from the data without the base headers
2191 SharedBuffer<u8> strippeddata(received_size - BASE_HEADER_SIZE);
2192 memcpy(*strippeddata, &packetdata[BASE_HEADER_SIZE],
2193 strippeddata.getSize());
2196 // Process it (the result is some data with no headers made by us)
2197 SharedBuffer<u8> resultdata = processPacket
2198 (channel, strippeddata, peer_id, channelnum, false);
2200 LOG(dout_con<<m_connection->getDesc()
2201 <<" ProcessPacket from peer_id: " << peer_id
2202 << ",channel: " << (channelnum & 0xFF) << ", returned "
2203 << resultdata.getSize() << " bytes" <<std::endl);
2206 e.dataReceived(peer_id, resultdata);
2207 m_connection->putEvent(e);
2209 catch(ProcessedSilentlyException &e) {
2211 catch(ProcessedQueued &e) {
2212 packet_queued = true;
2215 catch(InvalidIncomingDataException &e) {
2217 catch(ProcessedSilentlyException &e) {
2222 bool ConnectionReceiveThread::getFromBuffers(u16 &peer_id, SharedBuffer<u8> &dst)
2224 std::list<u16> peerids = m_connection->getPeerIDs();
2226 for(std::list<u16>::iterator j = peerids.begin();
2227 j != peerids.end(); ++j)
2229 PeerHelper peer = m_connection->getPeerNoEx(*j);
2233 if (dynamic_cast<UDPPeer*>(&peer) == 0)
2236 for(u16 i=0; i<CHANNEL_COUNT; i++)
2238 Channel *channel = &(dynamic_cast<UDPPeer*>(&peer))->channels[i];
2240 if (checkIncomingBuffers(channel, peer_id, dst)) {
2248 bool ConnectionReceiveThread::checkIncomingBuffers(Channel *channel,
2249 u16 &peer_id, SharedBuffer<u8> &dst)
2251 u16 firstseqnum = 0;
2252 if (channel->incoming_reliables.getFirstSeqnum(firstseqnum))
2254 if (firstseqnum == channel->readNextIncomingSeqNum())
2256 BufferedPacket p = channel->incoming_reliables.popFirst();
2257 peer_id = readPeerId(*p.data);
2258 u8 channelnum = readChannel(*p.data);
2259 u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]);
2261 LOG(dout_con<<m_connection->getDesc()
2262 <<"UNBUFFERING TYPE_RELIABLE"
2263 <<" seqnum="<<seqnum
2264 <<" peer_id="<<peer_id
2265 <<" channel="<<((int)channelnum&0xff)
2268 channel->incNextIncomingSeqNum();
2270 u32 headers_size = BASE_HEADER_SIZE + RELIABLE_HEADER_SIZE;
2271 // Get out the inside packet and re-process it
2272 SharedBuffer<u8> payload(p.data.getSize() - headers_size);
2273 memcpy(*payload, &p.data[headers_size], payload.getSize());
2275 dst = processPacket(channel, payload, peer_id, channelnum, true);
2282 SharedBuffer<u8> ConnectionReceiveThread::processPacket(Channel *channel,
2283 SharedBuffer<u8> packetdata, u16 peer_id, u8 channelnum, bool reliable)
2285 PeerHelper peer = m_connection->getPeerNoEx(peer_id);
2288 errorstream << "Peer not found (possible timeout)" << std::endl;
2289 throw ProcessedSilentlyException("Peer not found (possible timeout)");
2292 if (packetdata.getSize() < 1)
2293 throw InvalidIncomingDataException("packetdata.getSize() < 1");
2295 u8 type = readU8(&(packetdata[0]));
2297 if (MAX_UDP_PEERS <= 65535 && peer_id >= MAX_UDP_PEERS) {
2298 std::string errmsg = "Invalid peer_id=" + itos(peer_id);
2299 errorstream << errmsg << std::endl;
2300 throw InvalidIncomingDataException(errmsg.c_str());
2303 if (type == TYPE_CONTROL)
2305 if (packetdata.getSize() < 2)
2306 throw InvalidIncomingDataException("packetdata.getSize() < 2");
2308 u8 controltype = readU8(&(packetdata[1]));
2310 if (controltype == CONTROLTYPE_ACK)
2312 assert(channel != NULL);
2314 if (packetdata.getSize() < 4) {
2315 throw InvalidIncomingDataException(
2316 "packetdata.getSize() < 4 (ACK header size)");
2319 u16 seqnum = readU16(&packetdata[2]);
2320 LOG(dout_con<<m_connection->getDesc()
2321 <<" [ CONTROLTYPE_ACK: channelnum="
2322 <<((int)channelnum&0xff)<<", peer_id="<<peer_id
2323 <<", seqnum="<<seqnum<< " ]"<<std::endl);
2327 channel->outgoing_reliables_sent.popSeqnum(seqnum);
2329 // only calculate rtt from straight sent packets
2330 if (p.resend_count == 0) {
2331 // Get round trip time
2332 u64 current_time = porting::getTimeMs();
2334 // a overflow is quite unlikely but as it'd result in major
2335 // rtt miscalculation we handle it here
2336 if (current_time > p.absolute_send_time)
2338 float rtt = (current_time - p.absolute_send_time) / 1000.0;
2340 // Let peer calculate stuff according to it
2341 // (avg_rtt and resend_timeout)
2342 dynamic_cast<UDPPeer*>(&peer)->reportRTT(rtt);
2344 else if (p.totaltime > 0)
2346 float rtt = p.totaltime;
2348 // Let peer calculate stuff according to it
2349 // (avg_rtt and resend_timeout)
2350 dynamic_cast<UDPPeer*>(&peer)->reportRTT(rtt);
2353 //put bytes for max bandwidth calculation
2354 channel->UpdateBytesSent(p.data.getSize(),1);
2355 if (channel->outgoing_reliables_sent.size() == 0)
2357 m_connection->TriggerSend();
2360 catch(NotFoundException &e) {
2361 LOG(derr_con<<m_connection->getDesc()
2362 <<"WARNING: ACKed packet not "
2365 channel->UpdatePacketTooLateCounter();
2367 throw ProcessedSilentlyException("Got an ACK");
2369 else if (controltype == CONTROLTYPE_SET_PEER_ID) {
2370 // Got a packet to set our peer id
2371 if (packetdata.getSize() < 4)
2372 throw InvalidIncomingDataException
2373 ("packetdata.getSize() < 4 (SET_PEER_ID header size)");
2374 u16 peer_id_new = readU16(&packetdata[2]);
2375 LOG(dout_con<<m_connection->getDesc()
2376 <<"Got new peer id: "<<peer_id_new<<"... "<<std::endl);
2378 if (m_connection->GetPeerID() != PEER_ID_INEXISTENT)
2380 LOG(derr_con<<m_connection->getDesc()
2381 <<"WARNING: Not changing"
2382 " existing peer id."<<std::endl);
2386 LOG(dout_con<<m_connection->getDesc()<<"changing own peer id"<<std::endl);
2387 m_connection->SetPeerID(peer_id_new);
2390 ConnectionCommand cmd;
2392 SharedBuffer<u8> reply(2);
2393 writeU8(&reply[0], TYPE_CONTROL);
2394 writeU8(&reply[1], CONTROLTYPE_ENABLE_BIG_SEND_WINDOW);
2395 cmd.disableLegacy(PEER_ID_SERVER,reply);
2396 m_connection->putCommand(cmd);
2398 throw ProcessedSilentlyException("Got a SET_PEER_ID");
2400 else if (controltype == CONTROLTYPE_PING)
2402 // Just ignore it, the incoming data already reset
2403 // the timeout counter
2404 LOG(dout_con<<m_connection->getDesc()<<"PING"<<std::endl);
2405 throw ProcessedSilentlyException("Got a PING");
2407 else if (controltype == CONTROLTYPE_DISCO)
2409 // Just ignore it, the incoming data already reset
2410 // the timeout counter
2411 LOG(dout_con<<m_connection->getDesc()
2412 <<"DISCO: Removing peer "<<(peer_id)<<std::endl);
2414 if (m_connection->deletePeer(peer_id, false) == false)
2416 derr_con<<m_connection->getDesc()
2417 <<"DISCO: Peer not found"<<std::endl;
2420 throw ProcessedSilentlyException("Got a DISCO");
2422 else if (controltype == CONTROLTYPE_ENABLE_BIG_SEND_WINDOW)
2424 dynamic_cast<UDPPeer*>(&peer)->setNonLegacyPeer();
2425 throw ProcessedSilentlyException("Got non legacy control");
2428 LOG(derr_con<<m_connection->getDesc()
2429 <<"INVALID TYPE_CONTROL: invalid controltype="
2430 <<((int)controltype&0xff)<<std::endl);
2431 throw InvalidIncomingDataException("Invalid control type");
2434 else if (type == TYPE_ORIGINAL)
2436 if (packetdata.getSize() <= ORIGINAL_HEADER_SIZE)
2437 throw InvalidIncomingDataException
2438 ("packetdata.getSize() <= ORIGINAL_HEADER_SIZE");
2439 LOG(dout_con<<m_connection->getDesc()
2440 <<"RETURNING TYPE_ORIGINAL to user"
2442 // Get the inside packet out and return it
2443 SharedBuffer<u8> payload(packetdata.getSize() - ORIGINAL_HEADER_SIZE);
2444 memcpy(*payload, &(packetdata[ORIGINAL_HEADER_SIZE]), payload.getSize());
2447 else if (type == TYPE_SPLIT)
2449 Address peer_address;
2451 if (peer->getAddress(MTP_UDP, peer_address)) {
2453 // We have to create a packet again for buffering
2454 // This isn't actually too bad an idea.
2455 BufferedPacket packet = makePacket(
2458 m_connection->GetProtocolID(),
2462 // Buffer the packet
2463 SharedBuffer<u8> data =
2464 peer->addSpiltPacket(channelnum,packet,reliable);
2466 if (data.getSize() != 0)
2468 LOG(dout_con<<m_connection->getDesc()
2469 <<"RETURNING TYPE_SPLIT: Constructed full data, "
2470 <<"size="<<data.getSize()<<std::endl);
2473 LOG(dout_con<<m_connection->getDesc()<<"BUFFERED TYPE_SPLIT"<<std::endl);
2474 throw ProcessedSilentlyException("Buffered a split packet chunk");
2477 //TODO throw some error
2480 else if (type == TYPE_RELIABLE)
2482 assert(channel != NULL);
2484 // Recursive reliable packets not allowed
2486 throw InvalidIncomingDataException("Found nested reliable packets");
2488 if (packetdata.getSize() < RELIABLE_HEADER_SIZE)
2489 throw InvalidIncomingDataException
2490 ("packetdata.getSize() < RELIABLE_HEADER_SIZE");
2492 u16 seqnum = readU16(&packetdata[1]);
2493 bool is_future_packet = false;
2494 bool is_old_packet = false;
2496 /* packet is within our receive window send ack */
2497 if (seqnum_in_window(seqnum, channel->readNextIncomingSeqNum(),MAX_RELIABLE_WINDOW_SIZE))
2499 m_connection->sendAck(peer_id,channelnum,seqnum);
2502 is_future_packet = seqnum_higher(seqnum, channel->readNextIncomingSeqNum());
2503 is_old_packet = seqnum_higher(channel->readNextIncomingSeqNum(), seqnum);
2506 /* packet is not within receive window, don't send ack. *
2507 * if this was a valid packet it's gonna be retransmitted */
2508 if (is_future_packet)
2510 throw ProcessedSilentlyException("Received packet newer then expected, not sending ack");
2513 /* seems like our ack was lost, send another one for a old packet */
2516 LOG(dout_con<<m_connection->getDesc()
2517 << "RE-SENDING ACK: peer_id: " << peer_id
2518 << ", channel: " << (channelnum&0xFF)
2519 << ", seqnum: " << seqnum << std::endl;)
2520 m_connection->sendAck(peer_id,channelnum,seqnum);
2522 // we already have this packet so this one was on wire at least
2523 // the current timeout
2524 // we don't know how long this packet was on wire don't do silly guessing
2525 // dynamic_cast<UDPPeer*>(&peer)->reportRTT(dynamic_cast<UDPPeer*>(&peer)->getResendTimeout());
2527 throw ProcessedSilentlyException("Retransmitting ack for old packet");
2531 if (seqnum != channel->readNextIncomingSeqNum())
2533 Address peer_address;
2535 // this is a reliable packet so we have a udp address for sure
2536 peer->getAddress(MTP_MINETEST_RELIABLE_UDP, peer_address);
2537 // This one comes later, buffer it.
2538 // Actually we have to make a packet to buffer one.
2539 // Well, we have all the ingredients, so just do it.
2540 BufferedPacket packet = con::makePacket(
2543 m_connection->GetProtocolID(),
2547 channel->incoming_reliables.insert(packet,channel->readNextIncomingSeqNum());
2549 LOG(dout_con<<m_connection->getDesc()
2550 << "BUFFERING, TYPE_RELIABLE peer_id: " << peer_id
2551 << ", channel: " << (channelnum&0xFF)
2552 << ", seqnum: " << seqnum << std::endl;)
2554 throw ProcessedQueued("Buffered future reliable packet");
2556 catch(AlreadyExistsException &e)
2559 catch(IncomingDataCorruption &e)
2561 ConnectionCommand discon;
2562 discon.disconnect_peer(peer_id);
2563 m_connection->putCommand(discon);
2565 LOG(derr_con<<m_connection->getDesc()
2566 << "INVALID, TYPE_RELIABLE peer_id: " << peer_id
2567 << ", channel: " << (channelnum&0xFF)
2568 << ", seqnum: " << seqnum
2569 << "DROPPING CLIENT!" << std::endl;)
2573 /* we got a packet to process right now */
2574 LOG(dout_con<<m_connection->getDesc()
2575 << "RECURSIVE, TYPE_RELIABLE peer_id: " << peer_id
2576 << ", channel: " << (channelnum&0xFF)
2577 << ", seqnum: " << seqnum << std::endl;)
2580 /* check for resend case */
2581 u16 queued_seqnum = 0;
2582 if (channel->incoming_reliables.getFirstSeqnum(queued_seqnum))
2584 if (queued_seqnum == seqnum)
2586 BufferedPacket queued_packet = channel->incoming_reliables.popFirst();
2587 /** TODO find a way to verify the new against the old packet */
2591 channel->incNextIncomingSeqNum();
2593 // Get out the inside packet and re-process it
2594 SharedBuffer<u8> payload(packetdata.getSize() - RELIABLE_HEADER_SIZE);
2595 memcpy(*payload, &packetdata[RELIABLE_HEADER_SIZE], payload.getSize());
2597 return processPacket(channel, payload, peer_id, channelnum, true);
2601 derr_con<<m_connection->getDesc()
2602 <<"Got invalid type="<<((int)type&0xff)<<std::endl;
2603 throw InvalidIncomingDataException("Invalid packet type");
2606 // We should never get here.
2607 FATAL_ERROR("Invalid execution point");
2614 Connection::Connection(u32 protocol_id, u32 max_packet_size, float timeout,
2615 bool ipv6, PeerHandler *peerhandler) :
2617 m_protocol_id(protocol_id),
2618 m_sendThread(max_packet_size, timeout),
2619 m_receiveThread(max_packet_size),
2620 m_bc_peerhandler(peerhandler)
2623 m_udpSocket.setTimeoutMs(5);
2625 m_sendThread.setParent(this);
2626 m_receiveThread.setParent(this);
2628 m_sendThread.start();
2629 m_receiveThread.start();
2634 Connection::~Connection()
2636 m_shutting_down = true;
2637 // request threads to stop
2638 m_sendThread.stop();
2639 m_receiveThread.stop();
2641 //TODO for some unkonwn reason send/receive threads do not exit as they're
2642 // supposed to be but wait on peer timeout. To speed up shutdown we reduce
2643 // timeout to half a second.
2644 m_sendThread.setPeerTimeout(0.5);
2646 // wait for threads to finish
2647 m_sendThread.wait();
2648 m_receiveThread.wait();
2651 for(std::map<u16, Peer*>::iterator
2652 j = m_peers.begin();
2653 j != m_peers.end(); ++j)
2659 /* Internal stuff */
2660 void Connection::putEvent(ConnectionEvent &e)
2662 assert(e.type != CONNEVENT_NONE); // Pre-condition
2663 m_event_queue.push_back(e);
2666 PeerHelper Connection::getPeer(u16 peer_id)
2668 MutexAutoLock peerlock(m_peers_mutex);
2669 std::map<u16, Peer*>::iterator node = m_peers.find(peer_id);
2671 if (node == m_peers.end()) {
2672 throw PeerNotFoundException("GetPeer: Peer not found (possible timeout)");
2676 FATAL_ERROR_IF(node->second->id != peer_id, "Invalid peer id");
2678 return PeerHelper(node->second);
2681 PeerHelper Connection::getPeerNoEx(u16 peer_id)
2683 MutexAutoLock peerlock(m_peers_mutex);
2684 std::map<u16, Peer*>::iterator node = m_peers.find(peer_id);
2686 if (node == m_peers.end()) {
2687 return PeerHelper(NULL);
2691 FATAL_ERROR_IF(node->second->id != peer_id, "Invalid peer id");
2693 return PeerHelper(node->second);
2696 /* find peer_id for address */
2697 u16 Connection::lookupPeer(Address& sender)
2699 MutexAutoLock peerlock(m_peers_mutex);
2700 std::map<u16, Peer*>::iterator j;
2701 j = m_peers.begin();
2702 for(; j != m_peers.end(); ++j)
2704 Peer *peer = j->second;
2705 if (peer->isPendingDeletion())
2710 if ((peer->getAddress(MTP_MINETEST_RELIABLE_UDP, tocheck)) && (tocheck == sender))
2713 if ((peer->getAddress(MTP_UDP, tocheck)) && (tocheck == sender))
2717 return PEER_ID_INEXISTENT;
2720 std::list<Peer*> Connection::getPeers()
2722 std::list<Peer*> list;
2723 for(std::map<u16, Peer*>::iterator j = m_peers.begin();
2724 j != m_peers.end(); ++j)
2726 Peer *peer = j->second;
2727 list.push_back(peer);
2732 bool Connection::deletePeer(u16 peer_id, bool timeout)
2736 /* lock list as short as possible */
2738 MutexAutoLock peerlock(m_peers_mutex);
2739 if (m_peers.find(peer_id) == m_peers.end())
2741 peer = m_peers[peer_id];
2742 m_peers.erase(peer_id);
2743 m_peer_ids.remove(peer_id);
2746 Address peer_address;
2747 //any peer has a primary address this never fails!
2748 peer->getAddress(MTP_PRIMARY, peer_address);
2751 e.peerRemoved(peer_id, timeout, peer_address);
2761 ConnectionEvent Connection::waitEvent(u32 timeout_ms)
2764 return m_event_queue.pop_front(timeout_ms);
2765 } catch(ItemNotFoundException &ex) {
2767 e.type = CONNEVENT_NONE;
2772 void Connection::putCommand(ConnectionCommand &c)
2774 if (!m_shutting_down) {
2775 m_command_queue.push_back(c);
2776 m_sendThread.Trigger();
2780 void Connection::Serve(Address bind_addr)
2782 ConnectionCommand c;
2787 void Connection::Connect(Address address)
2789 ConnectionCommand c;
2794 bool Connection::Connected()
2796 MutexAutoLock peerlock(m_peers_mutex);
2798 if (m_peers.size() != 1)
2801 std::map<u16, Peer*>::iterator node = m_peers.find(PEER_ID_SERVER);
2802 if (node == m_peers.end())
2805 if (m_peer_id == PEER_ID_INEXISTENT)
2811 void Connection::Disconnect()
2813 ConnectionCommand c;
2818 void Connection::Receive(NetworkPacket* pkt)
2821 ConnectionEvent e = waitEvent(m_bc_receive_timeout);
2822 if (e.type != CONNEVENT_NONE)
2823 LOG(dout_con << getDesc() << ": Receive: got event: "
2824 << e.describe() << std::endl);
2826 case CONNEVENT_NONE:
2827 throw NoIncomingDataException("No incoming data");
2828 case CONNEVENT_DATA_RECEIVED:
2829 // Data size is lesser than command size, ignoring packet
2830 if (e.data.getSize() < 2) {
2834 pkt->putRawPacket(*e.data, e.data.getSize(), e.peer_id);
2836 case CONNEVENT_PEER_ADDED: {
2837 UDPPeer tmp(e.peer_id, e.address, this);
2838 if (m_bc_peerhandler)
2839 m_bc_peerhandler->peerAdded(&tmp);
2842 case CONNEVENT_PEER_REMOVED: {
2843 UDPPeer tmp(e.peer_id, e.address, this);
2844 if (m_bc_peerhandler)
2845 m_bc_peerhandler->deletingPeer(&tmp, e.timeout);
2848 case CONNEVENT_BIND_FAILED:
2849 throw ConnectionBindFailed("Failed to bind socket "
2850 "(port already in use?)");
2853 throw NoIncomingDataException("No incoming data");
2856 void Connection::Send(u16 peer_id, u8 channelnum,
2857 NetworkPacket* pkt, bool reliable)
2859 assert(channelnum < CHANNEL_COUNT); // Pre-condition
2861 ConnectionCommand c;
2863 c.send(peer_id, channelnum, pkt, reliable);
2867 Address Connection::GetPeerAddress(u16 peer_id)
2869 PeerHelper peer = getPeerNoEx(peer_id);
2872 throw PeerNotFoundException("No address for peer found!");
2873 Address peer_address;
2874 peer->getAddress(MTP_PRIMARY, peer_address);
2875 return peer_address;
2878 float Connection::getPeerStat(u16 peer_id, rtt_stat_type type)
2880 PeerHelper peer = getPeerNoEx(peer_id);
2881 if (!peer) return -1;
2882 return peer->getStat(type);
2885 float Connection::getLocalStat(rate_stat_type type)
2887 PeerHelper peer = getPeerNoEx(PEER_ID_SERVER);
2889 FATAL_ERROR_IF(!peer, "Connection::getLocalStat we couldn't get our own peer? are you serious???");
2893 for (u16 j=0; j<CHANNEL_COUNT; j++) {
2896 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getCurrentDownloadRateKB();
2899 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getAvgDownloadRateKB();
2902 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getCurrentIncomingRateKB();
2905 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getAvgIncomingRateKB();
2908 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getAvgLossRateKB();
2911 retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getCurrentLossRateKB();
2914 FATAL_ERROR("Connection::getLocalStat Invalid stat type");
2920 u16 Connection::createPeer(Address& sender, MTProtocols protocol, int fd)
2922 // Somebody wants to make a new connection
2924 // Get a unique peer id (2 or higher)
2925 u16 peer_id_new = m_next_remote_peer_id;
2926 u16 overflow = MAX_UDP_PEERS;
2929 Find an unused peer id
2931 MutexAutoLock lock(m_peers_mutex);
2932 bool out_of_ids = false;
2935 if (m_peers.find(peer_id_new) == m_peers.end())
2938 // Check for overflow
2939 if (peer_id_new == overflow) {
2947 errorstream << getDesc() << " ran out of peer ids" << std::endl;
2948 return PEER_ID_INEXISTENT;
2953 peer = new UDPPeer(peer_id_new, sender, this);
2955 m_peers[peer->id] = peer;
2956 m_peer_ids.push_back(peer->id);
2958 m_next_remote_peer_id = (peer_id_new +1 ) % MAX_UDP_PEERS;
2960 LOG(dout_con << getDesc()
2961 << "createPeer(): giving peer_id=" << peer_id_new << std::endl);
2963 ConnectionCommand cmd;
2964 SharedBuffer<u8> reply(4);
2965 writeU8(&reply[0], TYPE_CONTROL);
2966 writeU8(&reply[1], CONTROLTYPE_SET_PEER_ID);
2967 writeU16(&reply[2], peer_id_new);
2968 cmd.createPeer(peer_id_new,reply);
2971 // Create peer addition event
2973 e.peerAdded(peer_id_new, sender);
2976 // We're now talking to a valid peer_id
2980 void Connection::PrintInfo(std::ostream &out)
2982 m_info_mutex.lock();
2983 out<<getDesc()<<": ";
2984 m_info_mutex.unlock();
2987 void Connection::PrintInfo()
2989 PrintInfo(dout_con);
2992 const std::string Connection::getDesc()
2994 return std::string("con(")+
2995 itos(m_udpSocket.GetHandle())+"/"+itos(m_peer_id)+")";
2998 void Connection::DisconnectPeer(u16 peer_id)
3000 ConnectionCommand discon;
3001 discon.disconnect_peer(peer_id);
3005 void Connection::sendAck(u16 peer_id, u8 channelnum, u16 seqnum)
3007 assert(channelnum < CHANNEL_COUNT); // Pre-condition
3009 LOG(dout_con<<getDesc()
3010 <<" Queuing ACK command to peer_id: " << peer_id <<
3011 " channel: " << (channelnum & 0xFF) <<
3012 " seqnum: " << seqnum << std::endl);
3014 ConnectionCommand c;
3015 SharedBuffer<u8> ack(4);
3016 writeU8(&ack[0], TYPE_CONTROL);
3017 writeU8(&ack[1], CONTROLTYPE_ACK);
3018 writeU16(&ack[2], seqnum);
3020 c.ack(peer_id, channelnum, ack);
3022 m_sendThread.Trigger();
3025 UDPPeer* Connection::createServerPeer(Address& address)
3027 if (getPeerNoEx(PEER_ID_SERVER) != 0)
3029 throw ConnectionException("Already connected to a server");
3032 UDPPeer *peer = new UDPPeer(PEER_ID_SERVER, address, this);
3035 MutexAutoLock lock(m_peers_mutex);
3036 m_peers[peer->id] = peer;
3037 m_peer_ids.push_back(peer->id);