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