]> git.lizzy.rs Git - dragonfireclient.git/blob - src/network/connection.cpp
Shave off buffer copies in networking code (#11607)
[dragonfireclient.git] / src / network / connection.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
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.
9
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.
14
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.
18 */
19
20 #include <iomanip>
21 #include <cerrno>
22 #include <algorithm>
23 #include <cmath>
24 #include "connection.h"
25 #include "serialization.h"
26 #include "log.h"
27 #include "porting.h"
28 #include "network/connectionthreads.h"
29 #include "network/networkpacket.h"
30 #include "network/peerhandler.h"
31 #include "util/serialize.h"
32 #include "util/numeric.h"
33 #include "util/string.h"
34 #include "settings.h"
35 #include "profiler.h"
36
37 namespace con
38 {
39
40 /******************************************************************************/
41 /* defines used for debugging and profiling                                   */
42 /******************************************************************************/
43 #ifdef NDEBUG
44         #define LOG(a) a
45         #define PROFILE(a)
46 #else
47         #if 0
48         /* this mutex is used to achieve log message consistency */
49         std::mutex log_message_mutex;
50         #define LOG(a)                                                                 \
51                 {                                                                          \
52                 MutexAutoLock loglock(log_message_mutex);                                 \
53                 a;                                                                         \
54                 }
55         #else
56         // Prevent deadlocks until a solution is found after 5.2.0 (TODO)
57         #define LOG(a) a
58         #endif
59
60         #define PROFILE(a) a
61 #endif
62
63 #define PING_TIMEOUT 5.0
64
65 BufferedPacket makePacket(Address &address, const SharedBuffer<u8> &data,
66                 u32 protocol_id, session_t sender_peer_id, u8 channel)
67 {
68         u32 packet_size = data.getSize() + BASE_HEADER_SIZE;
69         BufferedPacket p(packet_size);
70         p.address = address;
71
72         writeU32(&p.data[0], protocol_id);
73         writeU16(&p.data[4], sender_peer_id);
74         writeU8(&p.data[6], channel);
75
76         memcpy(&p.data[BASE_HEADER_SIZE], *data, data.getSize());
77
78         return p;
79 }
80
81 SharedBuffer<u8> makeOriginalPacket(const SharedBuffer<u8> &data)
82 {
83         u32 header_size = 1;
84         u32 packet_size = data.getSize() + header_size;
85         SharedBuffer<u8> b(packet_size);
86
87         writeU8(&(b[0]), PACKET_TYPE_ORIGINAL);
88         if (data.getSize() > 0) {
89                 memcpy(&(b[header_size]), *data, data.getSize());
90         }
91         return b;
92 }
93
94 // Split data in chunks and add TYPE_SPLIT headers to them
95 void makeSplitPacket(const SharedBuffer<u8> &data, u32 chunksize_max, u16 seqnum,
96                 std::list<SharedBuffer<u8>> *chunks)
97 {
98         // Chunk packets, containing the TYPE_SPLIT header
99         u32 chunk_header_size = 7;
100         u32 maximum_data_size = chunksize_max - chunk_header_size;
101         u32 start = 0;
102         u32 end = 0;
103         u32 chunk_num = 0;
104         u16 chunk_count = 0;
105         do {
106                 end = start + maximum_data_size - 1;
107                 if (end > data.getSize() - 1)
108                         end = data.getSize() - 1;
109
110                 u32 payload_size = end - start + 1;
111                 u32 packet_size = chunk_header_size + payload_size;
112
113                 SharedBuffer<u8> chunk(packet_size);
114
115                 writeU8(&chunk[0], PACKET_TYPE_SPLIT);
116                 writeU16(&chunk[1], seqnum);
117                 // [3] u16 chunk_count is written at next stage
118                 writeU16(&chunk[5], chunk_num);
119                 memcpy(&chunk[chunk_header_size], &data[start], payload_size);
120
121                 chunks->push_back(chunk);
122                 chunk_count++;
123
124                 start = end + 1;
125                 chunk_num++;
126         }
127         while (end != data.getSize() - 1);
128
129         for (SharedBuffer<u8> &chunk : *chunks) {
130                 // Write chunk_count
131                 writeU16(&(chunk[3]), chunk_count);
132         }
133 }
134
135 void makeAutoSplitPacket(const SharedBuffer<u8> &data, u32 chunksize_max,
136                 u16 &split_seqnum, std::list<SharedBuffer<u8>> *list)
137 {
138         u32 original_header_size = 1;
139
140         if (data.getSize() + original_header_size > chunksize_max) {
141                 makeSplitPacket(data, chunksize_max, split_seqnum, list);
142                 split_seqnum++;
143                 return;
144         }
145
146         list->push_back(makeOriginalPacket(data));
147 }
148
149 SharedBuffer<u8> makeReliablePacket(const SharedBuffer<u8> &data, u16 seqnum)
150 {
151         u32 header_size = 3;
152         u32 packet_size = data.getSize() + header_size;
153         SharedBuffer<u8> b(packet_size);
154
155         writeU8(&b[0], PACKET_TYPE_RELIABLE);
156         writeU16(&b[1], seqnum);
157
158         memcpy(&b[header_size], *data, data.getSize());
159
160         return b;
161 }
162
163 /*
164         ReliablePacketBuffer
165 */
166
167 void ReliablePacketBuffer::print()
168 {
169         MutexAutoLock listlock(m_list_mutex);
170         LOG(dout_con<<"Dump of ReliablePacketBuffer:" << std::endl);
171         unsigned int index = 0;
172         for (BufferedPacket &bufferedPacket : m_list) {
173                 u16 s = readU16(&(bufferedPacket.data[BASE_HEADER_SIZE+1]));
174                 LOG(dout_con<<index<< ":" << s << std::endl);
175                 index++;
176         }
177 }
178
179 bool ReliablePacketBuffer::empty()
180 {
181         MutexAutoLock listlock(m_list_mutex);
182         return m_list.empty();
183 }
184
185 u32 ReliablePacketBuffer::size()
186 {
187         MutexAutoLock listlock(m_list_mutex);
188         return m_list.size();
189 }
190
191 RPBSearchResult ReliablePacketBuffer::findPacket(u16 seqnum)
192 {
193         std::list<BufferedPacket>::iterator i = m_list.begin();
194         for(; i != m_list.end(); ++i)
195         {
196                 u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
197                 if (s == seqnum)
198                         break;
199         }
200         return i;
201 }
202
203 bool ReliablePacketBuffer::getFirstSeqnum(u16& result)
204 {
205         MutexAutoLock listlock(m_list_mutex);
206         if (m_list.empty())
207                 return false;
208         const BufferedPacket &p = m_list.front();
209         result = readU16(&p.data[BASE_HEADER_SIZE + 1]);
210         return true;
211 }
212
213 BufferedPacket ReliablePacketBuffer::popFirst()
214 {
215         MutexAutoLock listlock(m_list_mutex);
216         if (m_list.empty())
217                 throw NotFoundException("Buffer is empty");
218         BufferedPacket p = std::move(m_list.front());
219         m_list.pop_front();
220
221         if (m_list.empty()) {
222                 m_oldest_non_answered_ack = 0;
223         } else {
224                 m_oldest_non_answered_ack =
225                                 readU16(&m_list.front().data[BASE_HEADER_SIZE + 1]);
226         }
227         return p;
228 }
229
230 BufferedPacket ReliablePacketBuffer::popSeqnum(u16 seqnum)
231 {
232         MutexAutoLock listlock(m_list_mutex);
233         RPBSearchResult r = findPacket(seqnum);
234         if (r == notFound()) {
235                 LOG(dout_con<<"Sequence number: " << seqnum
236                                 << " not found in reliable buffer"<<std::endl);
237                 throw NotFoundException("seqnum not found in buffer");
238         }
239         BufferedPacket p = std::move(*r);
240
241         m_list.erase(r);
242
243         if (m_list.empty()) {
244                 m_oldest_non_answered_ack = 0;
245         } else {
246                 m_oldest_non_answered_ack =
247                                 readU16(&m_list.front().data[BASE_HEADER_SIZE + 1]);
248         }
249         return p;
250 }
251
252 void ReliablePacketBuffer::insert(const BufferedPacket &p, u16 next_expected)
253 {
254         MutexAutoLock listlock(m_list_mutex);
255         if (p.data.getSize() < BASE_HEADER_SIZE + 3) {
256                 errorstream << "ReliablePacketBuffer::insert(): Invalid data size for "
257                         "reliable packet" << std::endl;
258                 return;
259         }
260         u8 type = readU8(&p.data[BASE_HEADER_SIZE + 0]);
261         if (type != PACKET_TYPE_RELIABLE) {
262                 errorstream << "ReliablePacketBuffer::insert(): type is not reliable"
263                         << std::endl;
264                 return;
265         }
266         u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE + 1]);
267
268         if (!seqnum_in_window(seqnum, next_expected, MAX_RELIABLE_WINDOW_SIZE)) {
269                 errorstream << "ReliablePacketBuffer::insert(): seqnum is outside of "
270                         "expected window " << std::endl;
271                 return;
272         }
273         if (seqnum == next_expected) {
274                 errorstream << "ReliablePacketBuffer::insert(): seqnum is next expected"
275                         << std::endl;
276                 return;
277         }
278
279         sanity_check(m_list.size() <= SEQNUM_MAX); // FIXME: Handle the error?
280
281         // Find the right place for the packet and insert it there
282         // If list is empty, just add it
283         if (m_list.empty())
284         {
285                 m_list.push_back(p);
286                 m_oldest_non_answered_ack = seqnum;
287                 // Done.
288                 return;
289         }
290
291         // Otherwise find the right place
292         std::list<BufferedPacket>::iterator i = m_list.begin();
293         // Find the first packet in the list which has a higher seqnum
294         u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
295
296         /* case seqnum is smaller then next_expected seqnum */
297         /* this is true e.g. on wrap around */
298         if (seqnum < next_expected) {
299                 while(((s < seqnum) || (s >= next_expected)) && (i != m_list.end())) {
300                         ++i;
301                         if (i != m_list.end())
302                                 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
303                 }
304         }
305         /* non wrap around case (at least for incoming and next_expected */
306         else
307         {
308                 while(((s < seqnum) && (s >= next_expected)) && (i != m_list.end())) {
309                         ++i;
310                         if (i != m_list.end())
311                                 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
312                 }
313         }
314
315         if (s == seqnum) {
316                 /* nothing to do this seems to be a resent packet */
317                 /* for paranoia reason data should be compared */
318                 if (
319                         (readU16(&(i->data[BASE_HEADER_SIZE+1])) != seqnum) ||
320                         (i->data.getSize() != p.data.getSize()) ||
321                         (i->address != p.address)
322                         )
323                 {
324                         /* if this happens your maximum transfer window may be to big */
325                         fprintf(stderr,
326                                         "Duplicated seqnum %d non matching packet detected:\n",
327                                         seqnum);
328                         fprintf(stderr, "Old: seqnum: %05d size: %04d, address: %s\n",
329                                         readU16(&(i->data[BASE_HEADER_SIZE+1])),i->data.getSize(),
330                                         i->address.serializeString().c_str());
331                         fprintf(stderr, "New: seqnum: %05d size: %04u, address: %s\n",
332                                         readU16(&(p.data[BASE_HEADER_SIZE+1])),p.data.getSize(),
333                                         p.address.serializeString().c_str());
334                         throw IncomingDataCorruption("duplicated packet isn't same as original one");
335                 }
336         }
337         /* insert or push back */
338         else if (i != m_list.end()) {
339                 m_list.insert(i, p);
340         } else {
341                 m_list.push_back(p);
342         }
343
344         /* update last packet number */
345         m_oldest_non_answered_ack = readU16(&m_list.front().data[BASE_HEADER_SIZE+1]);
346 }
347
348 void ReliablePacketBuffer::incrementTimeouts(float dtime)
349 {
350         MutexAutoLock listlock(m_list_mutex);
351         for (BufferedPacket &bufferedPacket : m_list) {
352                 bufferedPacket.time += dtime;
353                 bufferedPacket.totaltime += dtime;
354         }
355 }
356
357 std::list<BufferedPacket>
358         ReliablePacketBuffer::getTimedOuts(float timeout, u32 max_packets)
359 {
360         MutexAutoLock listlock(m_list_mutex);
361         std::list<BufferedPacket> timed_outs;
362         for (BufferedPacket &bufferedPacket : m_list) {
363                 if (bufferedPacket.time >= timeout) {
364                         // caller will resend packet so reset time and increase counter
365                         bufferedPacket.time = 0.0f;
366                         bufferedPacket.resend_count++;
367
368                         timed_outs.push_back(bufferedPacket);
369
370                         if (timed_outs.size() >= max_packets)
371                                 break;
372                 }
373         }
374         return timed_outs;
375 }
376
377 /*
378         IncomingSplitPacket
379 */
380
381 bool IncomingSplitPacket::insert(u32 chunk_num, SharedBuffer<u8> &chunkdata)
382 {
383         sanity_check(chunk_num < chunk_count);
384
385         // If chunk already exists, ignore it.
386         // Sometimes two identical packets may arrive when there is network
387         // lag and the server re-sends stuff.
388         if (chunks.find(chunk_num) != chunks.end())
389                 return false;
390
391         // Set chunk data in buffer
392         chunks[chunk_num] = chunkdata;
393
394         return true;
395 }
396
397 SharedBuffer<u8> IncomingSplitPacket::reassemble()
398 {
399         sanity_check(allReceived());
400
401         // Calculate total size
402         u32 totalsize = 0;
403         for (const auto &chunk : chunks)
404                 totalsize += chunk.second.getSize();
405
406         SharedBuffer<u8> fulldata(totalsize);
407
408         // Copy chunks to data buffer
409         u32 start = 0;
410         for (u32 chunk_i = 0; chunk_i < chunk_count; chunk_i++) {
411                 const SharedBuffer<u8> &buf = chunks[chunk_i];
412                 memcpy(&fulldata[start], *buf, buf.getSize());
413                 start += buf.getSize();
414         }
415
416         return fulldata;
417 }
418
419 /*
420         IncomingSplitBuffer
421 */
422
423 IncomingSplitBuffer::~IncomingSplitBuffer()
424 {
425         MutexAutoLock listlock(m_map_mutex);
426         for (auto &i : m_buf) {
427                 delete i.second;
428         }
429 }
430
431 SharedBuffer<u8> IncomingSplitBuffer::insert(const BufferedPacket &p, bool reliable)
432 {
433         MutexAutoLock listlock(m_map_mutex);
434         u32 headersize = BASE_HEADER_SIZE + 7;
435         if (p.data.getSize() < headersize) {
436                 errorstream << "Invalid data size for split packet" << std::endl;
437                 return SharedBuffer<u8>();
438         }
439         u8 type = readU8(&p.data[BASE_HEADER_SIZE+0]);
440         u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]);
441         u16 chunk_count = readU16(&p.data[BASE_HEADER_SIZE+3]);
442         u16 chunk_num = readU16(&p.data[BASE_HEADER_SIZE+5]);
443
444         if (type != PACKET_TYPE_SPLIT) {
445                 errorstream << "IncomingSplitBuffer::insert(): type is not split"
446                         << std::endl;
447                 return SharedBuffer<u8>();
448         }
449         if (chunk_num >= chunk_count) {
450                 errorstream << "IncomingSplitBuffer::insert(): chunk_num=" << chunk_num
451                                 << " >= chunk_count=" << chunk_count << std::endl;
452                 return SharedBuffer<u8>();
453         }
454
455         // Add if doesn't exist
456         IncomingSplitPacket *sp;
457         if (m_buf.find(seqnum) == m_buf.end()) {
458                 sp = new IncomingSplitPacket(chunk_count, reliable);
459                 m_buf[seqnum] = sp;
460         } else {
461                 sp = m_buf[seqnum];
462         }
463
464         if (chunk_count != sp->chunk_count) {
465                 errorstream << "IncomingSplitBuffer::insert(): chunk_count="
466                                 << chunk_count << " != sp->chunk_count=" << sp->chunk_count
467                                 << std::endl;
468                 return SharedBuffer<u8>();
469         }
470         if (reliable != sp->reliable)
471                 LOG(derr_con<<"Connection: WARNING: reliable="<<reliable
472                                 <<" != sp->reliable="<<sp->reliable
473                                 <<std::endl);
474
475         // Cut chunk data out of packet
476         u32 chunkdatasize = p.data.getSize() - headersize;
477         SharedBuffer<u8> chunkdata(chunkdatasize);
478         memcpy(*chunkdata, &(p.data[headersize]), chunkdatasize);
479
480         if (!sp->insert(chunk_num, chunkdata))
481                 return SharedBuffer<u8>();
482
483         // If not all chunks are received, return empty buffer
484         if (!sp->allReceived())
485                 return SharedBuffer<u8>();
486
487         SharedBuffer<u8> fulldata = sp->reassemble();
488
489         // Remove sp from buffer
490         m_buf.erase(seqnum);
491         delete sp;
492
493         return fulldata;
494 }
495
496 void IncomingSplitBuffer::removeUnreliableTimedOuts(float dtime, float timeout)
497 {
498         std::deque<u16> remove_queue;
499         {
500                 MutexAutoLock listlock(m_map_mutex);
501                 for (auto &i : m_buf) {
502                         IncomingSplitPacket *p = i.second;
503                         // Reliable ones are not removed by timeout
504                         if (p->reliable)
505                                 continue;
506                         p->time += dtime;
507                         if (p->time >= timeout)
508                                 remove_queue.push_back(i.first);
509                 }
510         }
511         for (u16 j : remove_queue) {
512                 MutexAutoLock listlock(m_map_mutex);
513                 LOG(dout_con<<"NOTE: Removing timed out unreliable split packet"<<std::endl);
514                 delete m_buf[j];
515                 m_buf.erase(j);
516         }
517 }
518
519 /*
520         ConnectionCommand
521  */
522
523 void ConnectionCommand::send(session_t peer_id_, u8 channelnum_, NetworkPacket *pkt,
524         bool reliable_)
525 {
526         type = CONNCMD_SEND;
527         peer_id = peer_id_;
528         channelnum = channelnum_;
529         data = pkt->oldForgePacket();
530         reliable = reliable_;
531 }
532
533 /*
534         Channel
535 */
536
537 u16 Channel::readNextIncomingSeqNum()
538 {
539         MutexAutoLock internal(m_internal_mutex);
540         return next_incoming_seqnum;
541 }
542
543 u16 Channel::incNextIncomingSeqNum()
544 {
545         MutexAutoLock internal(m_internal_mutex);
546         u16 retval = next_incoming_seqnum;
547         next_incoming_seqnum++;
548         return retval;
549 }
550
551 u16 Channel::readNextSplitSeqNum()
552 {
553         MutexAutoLock internal(m_internal_mutex);
554         return next_outgoing_split_seqnum;
555 }
556 void Channel::setNextSplitSeqNum(u16 seqnum)
557 {
558         MutexAutoLock internal(m_internal_mutex);
559         next_outgoing_split_seqnum = seqnum;
560 }
561
562 u16 Channel::getOutgoingSequenceNumber(bool& successful)
563 {
564         MutexAutoLock internal(m_internal_mutex);
565         u16 retval = next_outgoing_seqnum;
566         u16 lowest_unacked_seqnumber;
567
568         /* shortcut if there ain't any packet in outgoing list */
569         if (outgoing_reliables_sent.empty())
570         {
571                 next_outgoing_seqnum++;
572                 return retval;
573         }
574
575         if (outgoing_reliables_sent.getFirstSeqnum(lowest_unacked_seqnumber))
576         {
577                 if (lowest_unacked_seqnumber < next_outgoing_seqnum) {
578                         // ugly cast but this one is required in order to tell compiler we
579                         // know about difference of two unsigned may be negative in general
580                         // but we already made sure it won't happen in this case
581                         if (((u16)(next_outgoing_seqnum - lowest_unacked_seqnumber)) > window_size) {
582                                 successful = false;
583                                 return 0;
584                         }
585                 }
586                 else {
587                         // ugly cast but this one is required in order to tell compiler we
588                         // know about difference of two unsigned may be negative in general
589                         // but we already made sure it won't happen in this case
590                         if ((next_outgoing_seqnum + (u16)(SEQNUM_MAX - lowest_unacked_seqnumber)) >
591                                 window_size) {
592                                 successful = false;
593                                 return 0;
594                         }
595                 }
596         }
597
598         next_outgoing_seqnum++;
599         return retval;
600 }
601
602 u16 Channel::readOutgoingSequenceNumber()
603 {
604         MutexAutoLock internal(m_internal_mutex);
605         return next_outgoing_seqnum;
606 }
607
608 bool Channel::putBackSequenceNumber(u16 seqnum)
609 {
610         if (((seqnum + 1) % (SEQNUM_MAX+1)) == next_outgoing_seqnum) {
611
612                 next_outgoing_seqnum = seqnum;
613                 return true;
614         }
615         return false;
616 }
617
618 void Channel::UpdateBytesSent(unsigned int bytes, unsigned int packets)
619 {
620         MutexAutoLock internal(m_internal_mutex);
621         current_bytes_transfered += bytes;
622         current_packet_successful += packets;
623 }
624
625 void Channel::UpdateBytesReceived(unsigned int bytes) {
626         MutexAutoLock internal(m_internal_mutex);
627         current_bytes_received += bytes;
628 }
629
630 void Channel::UpdateBytesLost(unsigned int bytes)
631 {
632         MutexAutoLock internal(m_internal_mutex);
633         current_bytes_lost += bytes;
634 }
635
636
637 void Channel::UpdatePacketLossCounter(unsigned int count)
638 {
639         MutexAutoLock internal(m_internal_mutex);
640         current_packet_loss += count;
641 }
642
643 void Channel::UpdatePacketTooLateCounter()
644 {
645         MutexAutoLock internal(m_internal_mutex);
646         current_packet_too_late++;
647 }
648
649 void Channel::UpdateTimers(float dtime)
650 {
651         bpm_counter += dtime;
652         packet_loss_counter += dtime;
653
654         if (packet_loss_counter > 1.0f) {
655                 packet_loss_counter -= 1.0f;
656
657                 unsigned int packet_loss = 11; /* use a neutral value for initialization */
658                 unsigned int packets_successful = 0;
659                 //unsigned int packet_too_late = 0;
660
661                 bool reasonable_amount_of_data_transmitted = false;
662
663                 {
664                         MutexAutoLock internal(m_internal_mutex);
665                         packet_loss = current_packet_loss;
666                         //packet_too_late = current_packet_too_late;
667                         packets_successful = current_packet_successful;
668
669                         if (current_bytes_transfered > (unsigned int) (window_size*512/2)) {
670                                 reasonable_amount_of_data_transmitted = true;
671                         }
672                         current_packet_loss = 0;
673                         current_packet_too_late = 0;
674                         current_packet_successful = 0;
675                 }
676
677                 /* dynamic window size */
678                 float successful_to_lost_ratio = 0.0f;
679                 bool done = false;
680
681                 if (packets_successful > 0) {
682                         successful_to_lost_ratio = packet_loss/packets_successful;
683                 } else if (packet_loss > 0) {
684                         window_size = std::max(
685                                         (window_size - 10),
686                                         MIN_RELIABLE_WINDOW_SIZE);
687                         done = true;
688                 }
689
690                 if (!done) {
691                         if ((successful_to_lost_ratio < 0.01f) &&
692                                 (window_size < MAX_RELIABLE_WINDOW_SIZE)) {
693                                 /* don't even think about increasing if we didn't even
694                                  * use major parts of our window */
695                                 if (reasonable_amount_of_data_transmitted)
696                                         window_size = std::min(
697                                                         (window_size + 100),
698                                                         MAX_RELIABLE_WINDOW_SIZE);
699                         } else if ((successful_to_lost_ratio < 0.05f) &&
700                                         (window_size < MAX_RELIABLE_WINDOW_SIZE)) {
701                                 /* don't even think about increasing if we didn't even
702                                  * use major parts of our window */
703                                 if (reasonable_amount_of_data_transmitted)
704                                         window_size = std::min(
705                                                         (window_size + 50),
706                                                         MAX_RELIABLE_WINDOW_SIZE);
707                         } else if (successful_to_lost_ratio > 0.15f) {
708                                 window_size = std::max(
709                                                 (window_size - 100),
710                                                 MIN_RELIABLE_WINDOW_SIZE);
711                         } else if (successful_to_lost_ratio > 0.1f) {
712                                 window_size = std::max(
713                                                 (window_size - 50),
714                                                 MIN_RELIABLE_WINDOW_SIZE);
715                         }
716                 }
717         }
718
719         if (bpm_counter > 10.0f) {
720                 {
721                         MutexAutoLock internal(m_internal_mutex);
722                         cur_kbps                 =
723                                         (((float) current_bytes_transfered)/bpm_counter)/1024.0f;
724                         current_bytes_transfered = 0;
725                         cur_kbps_lost            =
726                                         (((float) current_bytes_lost)/bpm_counter)/1024.0f;
727                         current_bytes_lost       = 0;
728                         cur_incoming_kbps        =
729                                         (((float) current_bytes_received)/bpm_counter)/1024.0f;
730                         current_bytes_received   = 0;
731                         bpm_counter              = 0.0f;
732                 }
733
734                 if (cur_kbps > max_kbps) {
735                         max_kbps = cur_kbps;
736                 }
737
738                 if (cur_kbps_lost > max_kbps_lost) {
739                         max_kbps_lost = cur_kbps_lost;
740                 }
741
742                 if (cur_incoming_kbps > max_incoming_kbps) {
743                         max_incoming_kbps = cur_incoming_kbps;
744                 }
745
746                 rate_samples       = MYMIN(rate_samples+1,10);
747                 float old_fraction = ((float) (rate_samples-1) )/( (float) rate_samples);
748                 avg_kbps           = avg_kbps * old_fraction +
749                                 cur_kbps * (1.0 - old_fraction);
750                 avg_kbps_lost      = avg_kbps_lost * old_fraction +
751                                 cur_kbps_lost * (1.0 - old_fraction);
752                 avg_incoming_kbps  = avg_incoming_kbps * old_fraction +
753                                 cur_incoming_kbps * (1.0 - old_fraction);
754         }
755 }
756
757
758 /*
759         Peer
760 */
761
762 PeerHelper::PeerHelper(Peer* peer) :
763         m_peer(peer)
764 {
765         if (peer && !peer->IncUseCount())
766                 m_peer = nullptr;
767 }
768
769 PeerHelper::~PeerHelper()
770 {
771         if (m_peer)
772                 m_peer->DecUseCount();
773
774         m_peer = nullptr;
775 }
776
777 PeerHelper& PeerHelper::operator=(Peer* peer)
778 {
779         m_peer = peer;
780         if (peer && !peer->IncUseCount())
781                 m_peer = nullptr;
782         return *this;
783 }
784
785 Peer* PeerHelper::operator->() const
786 {
787         return m_peer;
788 }
789
790 Peer* PeerHelper::operator&() const
791 {
792         return m_peer;
793 }
794
795 bool PeerHelper::operator!()
796 {
797         return ! m_peer;
798 }
799
800 bool PeerHelper::operator!=(void* ptr)
801 {
802         return ((void*) m_peer != ptr);
803 }
804
805 bool Peer::IncUseCount()
806 {
807         MutexAutoLock lock(m_exclusive_access_mutex);
808
809         if (!m_pending_deletion) {
810                 this->m_usage++;
811                 return true;
812         }
813
814         return false;
815 }
816
817 void Peer::DecUseCount()
818 {
819         {
820                 MutexAutoLock lock(m_exclusive_access_mutex);
821                 sanity_check(m_usage > 0);
822                 m_usage--;
823
824                 if (!((m_pending_deletion) && (m_usage == 0)))
825                         return;
826         }
827         delete this;
828 }
829
830 void Peer::RTTStatistics(float rtt, const std::string &profiler_id,
831                 unsigned int num_samples) {
832
833         if (m_last_rtt > 0) {
834                 /* set min max values */
835                 if (rtt < m_rtt.min_rtt)
836                         m_rtt.min_rtt = rtt;
837                 if (rtt >= m_rtt.max_rtt)
838                         m_rtt.max_rtt = rtt;
839
840                 /* do average calculation */
841                 if (m_rtt.avg_rtt < 0.0)
842                         m_rtt.avg_rtt  = rtt;
843                 else
844                         m_rtt.avg_rtt  = m_rtt.avg_rtt * (num_samples/(num_samples-1)) +
845                                                                 rtt * (1/num_samples);
846
847                 /* do jitter calculation */
848
849                 //just use some neutral value at beginning
850                 float jitter = m_rtt.jitter_min;
851
852                 if (rtt > m_last_rtt)
853                         jitter = rtt-m_last_rtt;
854
855                 if (rtt <= m_last_rtt)
856                         jitter = m_last_rtt - rtt;
857
858                 if (jitter < m_rtt.jitter_min)
859                         m_rtt.jitter_min = jitter;
860                 if (jitter >= m_rtt.jitter_max)
861                         m_rtt.jitter_max = jitter;
862
863                 if (m_rtt.jitter_avg < 0.0)
864                         m_rtt.jitter_avg  = jitter;
865                 else
866                         m_rtt.jitter_avg  = m_rtt.jitter_avg * (num_samples/(num_samples-1)) +
867                                                                 jitter * (1/num_samples);
868
869                 if (!profiler_id.empty()) {
870                         g_profiler->graphAdd(profiler_id + " RTT [ms]", rtt * 1000.f);
871                         g_profiler->graphAdd(profiler_id + " jitter [ms]", jitter * 1000.f);
872                 }
873         }
874         /* save values required for next loop */
875         m_last_rtt = rtt;
876 }
877
878 bool Peer::isTimedOut(float timeout)
879 {
880         MutexAutoLock lock(m_exclusive_access_mutex);
881         u64 current_time = porting::getTimeMs();
882
883         float dtime = CALC_DTIME(m_last_timeout_check,current_time);
884         m_last_timeout_check = current_time;
885
886         m_timeout_counter += dtime;
887
888         return m_timeout_counter > timeout;
889 }
890
891 void Peer::Drop()
892 {
893         {
894                 MutexAutoLock usage_lock(m_exclusive_access_mutex);
895                 m_pending_deletion = true;
896                 if (m_usage != 0)
897                         return;
898         }
899
900         PROFILE(std::stringstream peerIdentifier1);
901         PROFILE(peerIdentifier1 << "runTimeouts[" << m_connection->getDesc()
902                         << ";" << id << ";RELIABLE]");
903         PROFILE(g_profiler->remove(peerIdentifier1.str()));
904         PROFILE(std::stringstream peerIdentifier2);
905         PROFILE(peerIdentifier2 << "sendPackets[" << m_connection->getDesc()
906                         << ";" << id << ";RELIABLE]");
907         PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier2.str(), SPT_AVG));
908
909         delete this;
910 }
911
912 UDPPeer::UDPPeer(u16 a_id, Address a_address, Connection* connection) :
913         Peer(a_address,a_id,connection)
914 {
915         for (Channel &channel : channels)
916                 channel.setWindowSize(START_RELIABLE_WINDOW_SIZE);
917 }
918
919 bool UDPPeer::getAddress(MTProtocols type,Address& toset)
920 {
921         if ((type == MTP_UDP) || (type == MTP_MINETEST_RELIABLE_UDP) || (type == MTP_PRIMARY))
922         {
923                 toset = address;
924                 return true;
925         }
926
927         return false;
928 }
929
930 void UDPPeer::reportRTT(float rtt)
931 {
932         if (rtt < 0.0) {
933                 return;
934         }
935         RTTStatistics(rtt,"rudp",MAX_RELIABLE_WINDOW_SIZE*10);
936
937         float timeout = getStat(AVG_RTT) * RESEND_TIMEOUT_FACTOR;
938         if (timeout < RESEND_TIMEOUT_MIN)
939                 timeout = RESEND_TIMEOUT_MIN;
940         if (timeout > RESEND_TIMEOUT_MAX)
941                 timeout = RESEND_TIMEOUT_MAX;
942
943         MutexAutoLock usage_lock(m_exclusive_access_mutex);
944         resend_timeout = timeout;
945 }
946
947 bool UDPPeer::Ping(float dtime,SharedBuffer<u8>& data)
948 {
949         m_ping_timer += dtime;
950         if (m_ping_timer >= PING_TIMEOUT)
951         {
952                 // Create and send PING packet
953                 writeU8(&data[0], PACKET_TYPE_CONTROL);
954                 writeU8(&data[1], CONTROLTYPE_PING);
955                 m_ping_timer = 0.0;
956                 return true;
957         }
958         return false;
959 }
960
961 void UDPPeer::PutReliableSendCommand(ConnectionCommand &c,
962                 unsigned int max_packet_size)
963 {
964         if (m_pending_disconnect)
965                 return;
966
967         Channel &chan = channels[c.channelnum];
968
969         if (chan.queued_commands.empty() &&
970                         /* don't queue more packets then window size */
971                         (chan.queued_reliables.size() < chan.getWindowSize() / 2)) {
972                 LOG(dout_con<<m_connection->getDesc()
973                                 <<" processing reliable command for peer id: " << c.peer_id
974                                 <<" data size: " << c.data.getSize() << std::endl);
975                 if (!processReliableSendCommand(c,max_packet_size)) {
976                         chan.queued_commands.push_back(c);
977                 }
978         }
979         else {
980                 LOG(dout_con<<m_connection->getDesc()
981                                 <<" Queueing reliable command for peer id: " << c.peer_id
982                                 <<" data size: " << c.data.getSize() <<std::endl);
983                 chan.queued_commands.push_back(c);
984                 if (chan.queued_commands.size() >= chan.getWindowSize() / 2) {
985                         LOG(derr_con << m_connection->getDesc()
986                                         << "Possible packet stall to peer id: " << c.peer_id
987                                         << " queued_commands=" << chan.queued_commands.size()
988                                         << std::endl);
989                 }
990         }
991 }
992
993 bool UDPPeer::processReliableSendCommand(
994                                 ConnectionCommand &c,
995                                 unsigned int max_packet_size)
996 {
997         if (m_pending_disconnect)
998                 return true;
999
1000         Channel &chan = channels[c.channelnum];
1001
1002         u32 chunksize_max = max_packet_size
1003                                                         - BASE_HEADER_SIZE
1004                                                         - RELIABLE_HEADER_SIZE;
1005
1006         sanity_check(c.data.getSize() < MAX_RELIABLE_WINDOW_SIZE*512);
1007
1008         std::list<SharedBuffer<u8>> originals;
1009         u16 split_sequence_number = chan.readNextSplitSeqNum();
1010
1011         if (c.raw) {
1012                 originals.emplace_back(c.data);
1013         } else {
1014                 makeAutoSplitPacket(c.data, chunksize_max,split_sequence_number, &originals);
1015                 chan.setNextSplitSeqNum(split_sequence_number);
1016         }
1017
1018         bool have_sequence_number = true;
1019         bool have_initial_sequence_number = false;
1020         std::queue<BufferedPacket> toadd;
1021         volatile u16 initial_sequence_number = 0;
1022
1023         for (SharedBuffer<u8> &original : originals) {
1024                 u16 seqnum = chan.getOutgoingSequenceNumber(have_sequence_number);
1025
1026                 /* oops, we don't have enough sequence numbers to send this packet */
1027                 if (!have_sequence_number)
1028                         break;
1029
1030                 if (!have_initial_sequence_number)
1031                 {
1032                         initial_sequence_number = seqnum;
1033                         have_initial_sequence_number = true;
1034                 }
1035
1036                 SharedBuffer<u8> reliable = makeReliablePacket(original, seqnum);
1037
1038                 // Add base headers and make a packet
1039                 BufferedPacket p = con::makePacket(address, reliable,
1040                                 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1041                                 c.channelnum);
1042
1043                 toadd.push(std::move(p));
1044         }
1045
1046         if (have_sequence_number) {
1047                 volatile u16 pcount = 0;
1048                 while (!toadd.empty()) {
1049                         BufferedPacket p = std::move(toadd.front());
1050                         toadd.pop();
1051 //                      LOG(dout_con<<connection->getDesc()
1052 //                                      << " queuing reliable packet for peer_id: " << c.peer_id
1053 //                                      << " channel: " << (c.channelnum&0xFF)
1054 //                                      << " seqnum: " << readU16(&p.data[BASE_HEADER_SIZE+1])
1055 //                                      << std::endl)
1056                         chan.queued_reliables.push(std::move(p));
1057                         pcount++;
1058                 }
1059                 sanity_check(chan.queued_reliables.size() < 0xFFFF);
1060                 return true;
1061         }
1062
1063         volatile u16 packets_available = toadd.size();
1064         /* we didn't get a single sequence number no need to fill queue */
1065         if (!have_initial_sequence_number) {
1066                 return false;
1067         }
1068
1069         while (!toadd.empty()) {
1070                 /* remove packet */
1071                 toadd.pop();
1072
1073                 bool successfully_put_back_sequence_number
1074                         = chan.putBackSequenceNumber(
1075                                 (initial_sequence_number+toadd.size() % (SEQNUM_MAX+1)));
1076
1077                 FATAL_ERROR_IF(!successfully_put_back_sequence_number, "error");
1078         }
1079
1080         // DO NOT REMOVE n_queued! It avoids a deadlock of async locked
1081         // 'log_message_mutex' and 'm_list_mutex'.
1082         u32 n_queued = chan.outgoing_reliables_sent.size();
1083
1084         LOG(dout_con<<m_connection->getDesc()
1085                         << " Windowsize exceeded on reliable sending "
1086                         << c.data.getSize() << " bytes"
1087                         << std::endl << "\t\tinitial_sequence_number: "
1088                         << initial_sequence_number
1089                         << std::endl << "\t\tgot at most            : "
1090                         << packets_available << " packets"
1091                         << std::endl << "\t\tpackets queued         : "
1092                         << n_queued
1093                         << std::endl);
1094
1095         return false;
1096 }
1097
1098 void UDPPeer::RunCommandQueues(
1099                                                         unsigned int max_packet_size,
1100                                                         unsigned int maxcommands,
1101                                                         unsigned int maxtransfer)
1102 {
1103
1104         for (Channel &channel : channels) {
1105                 unsigned int commands_processed = 0;
1106
1107                 if ((!channel.queued_commands.empty()) &&
1108                                 (channel.queued_reliables.size() < maxtransfer) &&
1109                                 (commands_processed < maxcommands)) {
1110                         try {
1111                                 ConnectionCommand c = channel.queued_commands.front();
1112
1113                                 LOG(dout_con << m_connection->getDesc()
1114                                                 << " processing queued reliable command " << std::endl);
1115
1116                                 // Packet is processed, remove it from queue
1117                                 if (processReliableSendCommand(c,max_packet_size)) {
1118                                         channel.queued_commands.pop_front();
1119                                 } else {
1120                                         LOG(dout_con << m_connection->getDesc()
1121                                                         << " Failed to queue packets for peer_id: " << c.peer_id
1122                                                         << ", delaying sending of " << c.data.getSize()
1123                                                         << " bytes" << std::endl);
1124                                 }
1125                         }
1126                         catch (ItemNotFoundException &e) {
1127                                 // intentionally empty
1128                         }
1129                 }
1130         }
1131 }
1132
1133 u16 UDPPeer::getNextSplitSequenceNumber(u8 channel)
1134 {
1135         assert(channel < CHANNEL_COUNT); // Pre-condition
1136         return channels[channel].readNextSplitSeqNum();
1137 }
1138
1139 void UDPPeer::setNextSplitSequenceNumber(u8 channel, u16 seqnum)
1140 {
1141         assert(channel < CHANNEL_COUNT); // Pre-condition
1142         channels[channel].setNextSplitSeqNum(seqnum);
1143 }
1144
1145 SharedBuffer<u8> UDPPeer::addSplitPacket(u8 channel, const BufferedPacket &toadd,
1146         bool reliable)
1147 {
1148         assert(channel < CHANNEL_COUNT); // Pre-condition
1149         return channels[channel].incoming_splits.insert(toadd, reliable);
1150 }
1151
1152 /*
1153         Connection
1154 */
1155
1156 Connection::Connection(u32 protocol_id, u32 max_packet_size, float timeout,
1157                 bool ipv6, PeerHandler *peerhandler) :
1158         m_udpSocket(ipv6),
1159         m_protocol_id(protocol_id),
1160         m_sendThread(new ConnectionSendThread(max_packet_size, timeout)),
1161         m_receiveThread(new ConnectionReceiveThread(max_packet_size)),
1162         m_bc_peerhandler(peerhandler)
1163
1164 {
1165         /* Amount of time Receive() will wait for data, this is entirely different
1166          * from the connection timeout */
1167         m_udpSocket.setTimeoutMs(500);
1168
1169         m_sendThread->setParent(this);
1170         m_receiveThread->setParent(this);
1171
1172         m_sendThread->start();
1173         m_receiveThread->start();
1174 }
1175
1176
1177 Connection::~Connection()
1178 {
1179         m_shutting_down = true;
1180         // request threads to stop
1181         m_sendThread->stop();
1182         m_receiveThread->stop();
1183
1184         //TODO for some unkonwn reason send/receive threads do not exit as they're
1185         // supposed to be but wait on peer timeout. To speed up shutdown we reduce
1186         // timeout to half a second.
1187         m_sendThread->setPeerTimeout(0.5);
1188
1189         // wait for threads to finish
1190         m_sendThread->wait();
1191         m_receiveThread->wait();
1192
1193         // Delete peers
1194         for (auto &peer : m_peers) {
1195                 delete peer.second;
1196         }
1197 }
1198
1199 /* Internal stuff */
1200
1201 void Connection::putEvent(const ConnectionEvent &e)
1202 {
1203         assert(e.type != CONNEVENT_NONE); // Pre-condition
1204         m_event_queue.push_back(e);
1205 }
1206
1207 void Connection::putEvent(ConnectionEvent &&e)
1208 {
1209         assert(e.type != CONNEVENT_NONE); // Pre-condition
1210         m_event_queue.push_back(std::move(e));
1211 }
1212
1213 void Connection::TriggerSend()
1214 {
1215         m_sendThread->Trigger();
1216 }
1217
1218 PeerHelper Connection::getPeerNoEx(session_t peer_id)
1219 {
1220         MutexAutoLock peerlock(m_peers_mutex);
1221         std::map<session_t, Peer *>::iterator node = m_peers.find(peer_id);
1222
1223         if (node == m_peers.end()) {
1224                 return PeerHelper(NULL);
1225         }
1226
1227         // Error checking
1228         FATAL_ERROR_IF(node->second->id != peer_id, "Invalid peer id");
1229
1230         return PeerHelper(node->second);
1231 }
1232
1233 /* find peer_id for address */
1234 u16 Connection::lookupPeer(Address& sender)
1235 {
1236         MutexAutoLock peerlock(m_peers_mutex);
1237         std::map<u16, Peer*>::iterator j;
1238         j = m_peers.begin();
1239         for(; j != m_peers.end(); ++j)
1240         {
1241                 Peer *peer = j->second;
1242                 if (peer->isPendingDeletion())
1243                         continue;
1244
1245                 Address tocheck;
1246
1247                 if ((peer->getAddress(MTP_MINETEST_RELIABLE_UDP, tocheck)) && (tocheck == sender))
1248                         return peer->id;
1249
1250                 if ((peer->getAddress(MTP_UDP, tocheck)) && (tocheck == sender))
1251                         return peer->id;
1252         }
1253
1254         return PEER_ID_INEXISTENT;
1255 }
1256
1257 bool Connection::deletePeer(session_t peer_id, bool timeout)
1258 {
1259         Peer *peer = 0;
1260
1261         /* lock list as short as possible */
1262         {
1263                 MutexAutoLock peerlock(m_peers_mutex);
1264                 if (m_peers.find(peer_id) == m_peers.end())
1265                         return false;
1266                 peer = m_peers[peer_id];
1267                 m_peers.erase(peer_id);
1268                 auto it = std::find(m_peer_ids.begin(), m_peer_ids.end(), peer_id);
1269                 m_peer_ids.erase(it);
1270         }
1271
1272         Address peer_address;
1273         //any peer has a primary address this never fails!
1274         peer->getAddress(MTP_PRIMARY, peer_address);
1275         // Create event
1276         ConnectionEvent e;
1277         e.peerRemoved(peer_id, timeout, peer_address);
1278         putEvent(e);
1279
1280
1281         peer->Drop();
1282         return true;
1283 }
1284
1285 /* Interface */
1286
1287 ConnectionEvent Connection::waitEvent(u32 timeout_ms)
1288 {
1289         try {
1290                 return m_event_queue.pop_front(timeout_ms);
1291         } catch(ItemNotFoundException &ex) {
1292                 ConnectionEvent e;
1293                 e.type = CONNEVENT_NONE;
1294                 return e;
1295         }
1296 }
1297
1298 void Connection::putCommand(const ConnectionCommand &c)
1299 {
1300         if (!m_shutting_down) {
1301                 m_command_queue.push_back(c);
1302                 m_sendThread->Trigger();
1303         }
1304 }
1305
1306 void Connection::putCommand(ConnectionCommand &&c)
1307 {
1308         if (!m_shutting_down) {
1309                 m_command_queue.push_back(std::move(c));
1310                 m_sendThread->Trigger();
1311         }
1312 }
1313
1314 void Connection::Serve(Address bind_addr)
1315 {
1316         ConnectionCommand c;
1317         c.serve(bind_addr);
1318         putCommand(c);
1319 }
1320
1321 void Connection::Connect(Address address)
1322 {
1323         ConnectionCommand c;
1324         c.connect(address);
1325         putCommand(c);
1326 }
1327
1328 bool Connection::Connected()
1329 {
1330         MutexAutoLock peerlock(m_peers_mutex);
1331
1332         if (m_peers.size() != 1)
1333                 return false;
1334
1335         std::map<session_t, Peer *>::iterator node = m_peers.find(PEER_ID_SERVER);
1336         if (node == m_peers.end())
1337                 return false;
1338
1339         if (m_peer_id == PEER_ID_INEXISTENT)
1340                 return false;
1341
1342         return true;
1343 }
1344
1345 void Connection::Disconnect()
1346 {
1347         ConnectionCommand c;
1348         c.disconnect();
1349         putCommand(c);
1350 }
1351
1352 bool Connection::Receive(NetworkPacket *pkt, u32 timeout)
1353 {
1354         /*
1355                 Note that this function can potentially wait infinitely if non-data
1356                 events keep happening before the timeout expires.
1357                 This is not considered to be a problem (is it?)
1358         */
1359         for(;;) {
1360                 ConnectionEvent e = waitEvent(timeout);
1361                 if (e.type != CONNEVENT_NONE)
1362                         LOG(dout_con << getDesc() << ": Receive: got event: "
1363                                         << e.describe() << std::endl);
1364                 switch(e.type) {
1365                 case CONNEVENT_NONE:
1366                         return false;
1367                 case CONNEVENT_DATA_RECEIVED:
1368                         // Data size is lesser than command size, ignoring packet
1369                         if (e.data.getSize() < 2) {
1370                                 continue;
1371                         }
1372
1373                         pkt->putRawPacket(*e.data, e.data.getSize(), e.peer_id);
1374                         return true;
1375                 case CONNEVENT_PEER_ADDED: {
1376                         UDPPeer tmp(e.peer_id, e.address, this);
1377                         if (m_bc_peerhandler)
1378                                 m_bc_peerhandler->peerAdded(&tmp);
1379                         continue;
1380                 }
1381                 case CONNEVENT_PEER_REMOVED: {
1382                         UDPPeer tmp(e.peer_id, e.address, this);
1383                         if (m_bc_peerhandler)
1384                                 m_bc_peerhandler->deletingPeer(&tmp, e.timeout);
1385                         continue;
1386                 }
1387                 case CONNEVENT_BIND_FAILED:
1388                         throw ConnectionBindFailed("Failed to bind socket "
1389                                         "(port already in use?)");
1390                 }
1391         }
1392         return false;
1393 }
1394
1395 void Connection::Receive(NetworkPacket *pkt)
1396 {
1397         bool any = Receive(pkt, m_bc_receive_timeout);
1398         if (!any)
1399                 throw NoIncomingDataException("No incoming data");
1400 }
1401
1402 bool Connection::TryReceive(NetworkPacket *pkt)
1403 {
1404         return Receive(pkt, 0);
1405 }
1406
1407 void Connection::Send(session_t peer_id, u8 channelnum,
1408                 NetworkPacket *pkt, bool reliable)
1409 {
1410         assert(channelnum < CHANNEL_COUNT); // Pre-condition
1411
1412         ConnectionCommand c;
1413
1414         c.send(peer_id, channelnum, pkt, reliable);
1415         putCommand(std::move(c));
1416 }
1417
1418 Address Connection::GetPeerAddress(session_t peer_id)
1419 {
1420         PeerHelper peer = getPeerNoEx(peer_id);
1421
1422         if (!peer)
1423                 throw PeerNotFoundException("No address for peer found!");
1424         Address peer_address;
1425         peer->getAddress(MTP_PRIMARY, peer_address);
1426         return peer_address;
1427 }
1428
1429 float Connection::getPeerStat(session_t peer_id, rtt_stat_type type)
1430 {
1431         PeerHelper peer = getPeerNoEx(peer_id);
1432         if (!peer) return -1;
1433         return peer->getStat(type);
1434 }
1435
1436 float Connection::getLocalStat(rate_stat_type type)
1437 {
1438         PeerHelper peer = getPeerNoEx(PEER_ID_SERVER);
1439
1440         FATAL_ERROR_IF(!peer, "Connection::getLocalStat we couldn't get our own peer? are you serious???");
1441
1442         float retval = 0.0;
1443
1444         for (Channel &channel : dynamic_cast<UDPPeer *>(&peer)->channels) {
1445                 switch(type) {
1446                         case CUR_DL_RATE:
1447                                 retval += channel.getCurrentDownloadRateKB();
1448                                 break;
1449                         case AVG_DL_RATE:
1450                                 retval += channel.getAvgDownloadRateKB();
1451                                 break;
1452                         case CUR_INC_RATE:
1453                                 retval += channel.getCurrentIncomingRateKB();
1454                                 break;
1455                         case AVG_INC_RATE:
1456                                 retval += channel.getAvgIncomingRateKB();
1457                                 break;
1458                         case AVG_LOSS_RATE:
1459                                 retval += channel.getAvgLossRateKB();
1460                                 break;
1461                         case CUR_LOSS_RATE:
1462                                 retval += channel.getCurrentLossRateKB();
1463                                 break;
1464                 default:
1465                         FATAL_ERROR("Connection::getLocalStat Invalid stat type");
1466                 }
1467         }
1468         return retval;
1469 }
1470
1471 u16 Connection::createPeer(Address& sender, MTProtocols protocol, int fd)
1472 {
1473         // Somebody wants to make a new connection
1474
1475         // Get a unique peer id (2 or higher)
1476         session_t peer_id_new = m_next_remote_peer_id;
1477         u16 overflow =  MAX_UDP_PEERS;
1478
1479         /*
1480                 Find an unused peer id
1481         */
1482         MutexAutoLock lock(m_peers_mutex);
1483         bool out_of_ids = false;
1484         for(;;) {
1485                 // Check if exists
1486                 if (m_peers.find(peer_id_new) == m_peers.end())
1487
1488                         break;
1489                 // Check for overflow
1490                 if (peer_id_new == overflow) {
1491                         out_of_ids = true;
1492                         break;
1493                 }
1494                 peer_id_new++;
1495         }
1496
1497         if (out_of_ids) {
1498                 errorstream << getDesc() << " ran out of peer ids" << std::endl;
1499                 return PEER_ID_INEXISTENT;
1500         }
1501
1502         // Create a peer
1503         Peer *peer = 0;
1504         peer = new UDPPeer(peer_id_new, sender, this);
1505
1506         m_peers[peer->id] = peer;
1507         m_peer_ids.push_back(peer->id);
1508
1509         m_next_remote_peer_id = (peer_id_new +1 ) % MAX_UDP_PEERS;
1510
1511         LOG(dout_con << getDesc()
1512                         << "createPeer(): giving peer_id=" << peer_id_new << std::endl);
1513
1514         ConnectionCommand cmd;
1515         Buffer<u8> reply(4);
1516         writeU8(&reply[0], PACKET_TYPE_CONTROL);
1517         writeU8(&reply[1], CONTROLTYPE_SET_PEER_ID);
1518         writeU16(&reply[2], peer_id_new);
1519         cmd.createPeer(peer_id_new,reply);
1520         putCommand(std::move(cmd));
1521
1522         // Create peer addition event
1523         ConnectionEvent e;
1524         e.peerAdded(peer_id_new, sender);
1525         putEvent(e);
1526
1527         // We're now talking to a valid peer_id
1528         return peer_id_new;
1529 }
1530
1531 void Connection::PrintInfo(std::ostream &out)
1532 {
1533         m_info_mutex.lock();
1534         out<<getDesc()<<": ";
1535         m_info_mutex.unlock();
1536 }
1537
1538 const std::string Connection::getDesc()
1539 {
1540         return std::string("con(")+
1541                         itos(m_udpSocket.GetHandle())+"/"+itos(m_peer_id)+")";
1542 }
1543
1544 void Connection::DisconnectPeer(session_t peer_id)
1545 {
1546         ConnectionCommand discon;
1547         discon.disconnect_peer(peer_id);
1548         putCommand(discon);
1549 }
1550
1551 void Connection::sendAck(session_t peer_id, u8 channelnum, u16 seqnum)
1552 {
1553         assert(channelnum < CHANNEL_COUNT); // Pre-condition
1554
1555         LOG(dout_con<<getDesc()
1556                         <<" Queuing ACK command to peer_id: " << peer_id <<
1557                         " channel: " << (channelnum & 0xFF) <<
1558                         " seqnum: " << seqnum << std::endl);
1559
1560         ConnectionCommand c;
1561         SharedBuffer<u8> ack(4);
1562         writeU8(&ack[0], PACKET_TYPE_CONTROL);
1563         writeU8(&ack[1], CONTROLTYPE_ACK);
1564         writeU16(&ack[2], seqnum);
1565
1566         c.ack(peer_id, channelnum, ack);
1567         putCommand(std::move(c));
1568         m_sendThread->Trigger();
1569 }
1570
1571 UDPPeer* Connection::createServerPeer(Address& address)
1572 {
1573         if (ConnectedToServer())
1574         {
1575                 throw ConnectionException("Already connected to a server");
1576         }
1577
1578         UDPPeer *peer = new UDPPeer(PEER_ID_SERVER, address, this);
1579
1580         {
1581                 MutexAutoLock lock(m_peers_mutex);
1582                 m_peers[peer->id] = peer;
1583                 m_peer_ids.push_back(peer->id);
1584         }
1585
1586         return peer;
1587 }
1588
1589 } // namespace