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