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