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