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