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