]> git.lizzy.rs Git - dragonfireclient.git/blob - src/network/connection.cpp
Code modernization: subfolders (#6283)
[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 "connection.h"
23 #include "serialization.h"
24 #include "log.h"
25 #include "porting.h"
26 #include "network/networkpacket.h"
27 #include "util/serialize.h"
28 #include "util/numeric.h"
29 #include "util/string.h"
30 #include "settings.h"
31 #include "profiler.h"
32
33 namespace con
34 {
35
36 /******************************************************************************/
37 /* defines used for debugging and profiling                                   */
38 /******************************************************************************/
39 #ifdef NDEBUG
40 #define LOG(a) a
41 #define PROFILE(a)
42 #undef DEBUG_CONNECTION_KBPS
43 #else
44 /* this mutex is used to achieve log message consistency */
45 std::mutex log_message_mutex;
46 #define LOG(a)                                                                 \
47         {                                                                          \
48         MutexAutoLock loglock(log_message_mutex);                                 \
49         a;                                                                         \
50         }
51 #define PROFILE(a) a
52 //#define DEBUG_CONNECTION_KBPS
53 #undef DEBUG_CONNECTION_KBPS
54 #endif
55
56
57 static inline float CALC_DTIME(u64 lasttime, u64 curtime)
58 {
59         float value = ( curtime - lasttime) / 1000.0;
60         return MYMAX(MYMIN(value,0.1),0.0);
61 }
62
63 #define MAX_UDP_PEERS 65535
64
65 #define PING_TIMEOUT 5.0
66
67 /* maximum number of retries for reliable packets */
68 #define MAX_RELIABLE_RETRY 5
69
70 static u16 readPeerId(u8 *packetdata)
71 {
72         return readU16(&packetdata[4]);
73 }
74 static u8 readChannel(u8 *packetdata)
75 {
76         return readU8(&packetdata[6]);
77 }
78
79 BufferedPacket makePacket(Address &address, u8 *data, u32 datasize,
80                 u32 protocol_id, u16 sender_peer_id, u8 channel)
81 {
82         u32 packet_size = datasize + BASE_HEADER_SIZE;
83         BufferedPacket p(packet_size);
84         p.address = address;
85
86         writeU32(&p.data[0], protocol_id);
87         writeU16(&p.data[4], sender_peer_id);
88         writeU8(&p.data[6], channel);
89
90         memcpy(&p.data[BASE_HEADER_SIZE], data, datasize);
91
92         return p;
93 }
94
95 BufferedPacket makePacket(Address &address, SharedBuffer<u8> &data,
96                 u32 protocol_id, u16 sender_peer_id, u8 channel)
97 {
98         return makePacket(address, *data, data.getSize(),
99                         protocol_id, sender_peer_id, channel);
100 }
101
102 SharedBuffer<u8> makeOriginalPacket(
103                 SharedBuffer<u8> data)
104 {
105         u32 header_size = 1;
106         u32 packet_size = data.getSize() + header_size;
107         SharedBuffer<u8> b(packet_size);
108
109         writeU8(&(b[0]), TYPE_ORIGINAL);
110         if (data.getSize() > 0) {
111                 memcpy(&(b[header_size]), *data, data.getSize());
112         }
113         return b;
114 }
115
116 std::list<SharedBuffer<u8> > makeSplitPacket(
117                 SharedBuffer<u8> data,
118                 u32 chunksize_max,
119                 u16 seqnum)
120 {
121         // Chunk packets, containing the TYPE_SPLIT header
122         std::list<SharedBuffer<u8> > chunks;
123
124         u32 chunk_header_size = 7;
125         u32 maximum_data_size = chunksize_max - chunk_header_size;
126         u32 start = 0;
127         u32 end = 0;
128         u32 chunk_num = 0;
129         u16 chunk_count = 0;
130         do{
131                 end = start + maximum_data_size - 1;
132                 if (end > data.getSize() - 1)
133                         end = data.getSize() - 1;
134
135                 u32 payload_size = end - start + 1;
136                 u32 packet_size = chunk_header_size + payload_size;
137
138                 SharedBuffer<u8> chunk(packet_size);
139
140                 writeU8(&chunk[0], TYPE_SPLIT);
141                 writeU16(&chunk[1], seqnum);
142                 // [3] u16 chunk_count is written at next stage
143                 writeU16(&chunk[5], chunk_num);
144                 memcpy(&chunk[chunk_header_size], &data[start], payload_size);
145
146                 chunks.push_back(chunk);
147                 chunk_count++;
148
149                 start = end + 1;
150                 chunk_num++;
151         }
152         while(end != data.getSize() - 1);
153
154         for (SharedBuffer<u8> &chunk : chunks) {
155                 // Write chunk_count
156                 writeU16(&(chunk[3]), chunk_count);
157         }
158
159         return chunks;
160 }
161
162 std::list<SharedBuffer<u8> > makeAutoSplitPacket(
163                 SharedBuffer<u8> data,
164                 u32 chunksize_max,
165                 u16 &split_seqnum)
166 {
167         u32 original_header_size = 1;
168         std::list<SharedBuffer<u8> > list;
169         if (data.getSize() + original_header_size > chunksize_max)
170         {
171                 list = makeSplitPacket(data, chunksize_max, split_seqnum);
172                 split_seqnum++;
173                 return list;
174         }
175
176         list.push_back(makeOriginalPacket(data));
177         return list;
178 }
179
180 SharedBuffer<u8> makeReliablePacket(
181                 const SharedBuffer<u8> &data,
182                 u16 seqnum)
183 {
184         u32 header_size = 3;
185         u32 packet_size = data.getSize() + header_size;
186         SharedBuffer<u8> b(packet_size);
187
188         writeU8(&b[0], TYPE_RELIABLE);
189         writeU16(&b[1], seqnum);
190
191         memcpy(&b[header_size], *data, data.getSize());
192
193         return b;
194 }
195
196 /*
197         ReliablePacketBuffer
198 */
199
200 void ReliablePacketBuffer::print()
201 {
202         MutexAutoLock listlock(m_list_mutex);
203         LOG(dout_con<<"Dump of ReliablePacketBuffer:" << std::endl);
204         unsigned int index = 0;
205         for (BufferedPacket &bufferedPacket : m_list) {
206                 u16 s = readU16(&(bufferedPacket.data[BASE_HEADER_SIZE+1]));
207                 LOG(dout_con<<index<< ":" << s << std::endl);
208                 index++;
209         }
210 }
211 bool ReliablePacketBuffer::empty()
212 {
213         MutexAutoLock listlock(m_list_mutex);
214         return m_list.empty();
215 }
216
217 u32 ReliablePacketBuffer::size()
218 {
219         return m_list_size;
220 }
221
222 bool ReliablePacketBuffer::containsPacket(u16 seqnum)
223 {
224         return !(findPacket(seqnum) == m_list.end());
225 }
226
227 RPBSearchResult ReliablePacketBuffer::findPacket(u16 seqnum)
228 {
229         std::list<BufferedPacket>::iterator i = m_list.begin();
230         for(; i != m_list.end(); ++i)
231         {
232                 u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
233                 /*dout_con<<"findPacket(): finding seqnum="<<seqnum
234                                 <<", comparing to s="<<s<<std::endl;*/
235                 if (s == seqnum)
236                         break;
237         }
238         return i;
239 }
240 RPBSearchResult ReliablePacketBuffer::notFound()
241 {
242         return m_list.end();
243 }
244 bool ReliablePacketBuffer::getFirstSeqnum(u16& result)
245 {
246         MutexAutoLock listlock(m_list_mutex);
247         if (m_list.empty())
248                 return false;
249         BufferedPacket p = *m_list.begin();
250         result = readU16(&p.data[BASE_HEADER_SIZE+1]);
251         return true;
252 }
253
254 BufferedPacket ReliablePacketBuffer::popFirst()
255 {
256         MutexAutoLock listlock(m_list_mutex);
257         if (m_list.empty())
258                 throw NotFoundException("Buffer is empty");
259         BufferedPacket p = *m_list.begin();
260         m_list.erase(m_list.begin());
261         --m_list_size;
262
263         if (m_list_size == 0) {
264                 m_oldest_non_answered_ack = 0;
265         } else {
266                 m_oldest_non_answered_ack =
267                                 readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]);
268         }
269         return p;
270 }
271 BufferedPacket ReliablePacketBuffer::popSeqnum(u16 seqnum)
272 {
273         MutexAutoLock listlock(m_list_mutex);
274         RPBSearchResult r = findPacket(seqnum);
275         if (r == notFound()) {
276                 LOG(dout_con<<"Sequence number: " << seqnum
277                                 << " not found in reliable buffer"<<std::endl);
278                 throw NotFoundException("seqnum not found in buffer");
279         }
280         BufferedPacket p = *r;
281
282
283         RPBSearchResult next = r;
284         ++next;
285         if (next != notFound()) {
286                 u16 s = readU16(&(next->data[BASE_HEADER_SIZE+1]));
287                 m_oldest_non_answered_ack = s;
288         }
289
290         m_list.erase(r);
291         --m_list_size;
292
293         if (m_list_size == 0)
294         { m_oldest_non_answered_ack = 0; }
295         else
296         { m_oldest_non_answered_ack = readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]);     }
297         return p;
298 }
299 void ReliablePacketBuffer::insert(BufferedPacket &p,u16 next_expected)
300 {
301         MutexAutoLock listlock(m_list_mutex);
302         if (p.data.getSize() < BASE_HEADER_SIZE + 3) {
303                 errorstream << "ReliablePacketBuffer::insert(): Invalid data size for "
304                         "reliable packet" << std::endl;
305                 return;
306         }
307         u8 type = readU8(&p.data[BASE_HEADER_SIZE + 0]);
308         if (type != TYPE_RELIABLE) {
309                 errorstream << "ReliablePacketBuffer::insert(): type is not reliable"
310                         << std::endl;
311                 return;
312         }
313         u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE + 1]);
314
315         if (!seqnum_in_window(seqnum, next_expected, MAX_RELIABLE_WINDOW_SIZE)) {
316                 errorstream << "ReliablePacketBuffer::insert(): seqnum is outside of "
317                         "expected window " << std::endl;
318                 return;
319         }
320         if (seqnum == next_expected) {
321                 errorstream << "ReliablePacketBuffer::insert(): seqnum is next expected"
322                         << std::endl;
323                 return;
324         }
325
326         ++m_list_size;
327         sanity_check(m_list_size <= SEQNUM_MAX+1);      // FIXME: Handle the error?
328
329         // Find the right place for the packet and insert it there
330         // If list is empty, just add it
331         if (m_list.empty())
332         {
333                 m_list.push_back(p);
334                 m_oldest_non_answered_ack = seqnum;
335                 // Done.
336                 return;
337         }
338
339         // Otherwise find the right place
340         std::list<BufferedPacket>::iterator i = m_list.begin();
341         // Find the first packet in the list which has a higher seqnum
342         u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
343
344         /* case seqnum is smaller then next_expected seqnum */
345         /* this is true e.g. on wrap around */
346         if (seqnum < next_expected) {
347                 while(((s < seqnum) || (s >= next_expected)) && (i != m_list.end())) {
348                         ++i;
349                         if (i != m_list.end())
350                                 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
351                 }
352         }
353         /* non wrap around case (at least for incoming and next_expected */
354         else
355         {
356                 while(((s < seqnum) && (s >= next_expected)) && (i != m_list.end())) {
357                         ++i;
358                         if (i != m_list.end())
359                                 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
360                 }
361         }
362
363         if (s == seqnum) {
364                 if (
365                         (readU16(&(i->data[BASE_HEADER_SIZE+1])) != seqnum) ||
366                         (i->data.getSize() != p.data.getSize()) ||
367                         (i->address != p.address)
368                         )
369                 {
370                         /* if this happens your maximum transfer window may be to big */
371                         fprintf(stderr,
372                                         "Duplicated seqnum %d non matching packet detected:\n",
373                                         seqnum);
374                         fprintf(stderr, "Old: seqnum: %05d size: %04d, address: %s\n",
375                                         readU16(&(i->data[BASE_HEADER_SIZE+1])),i->data.getSize(),
376                                         i->address.serializeString().c_str());
377                         fprintf(stderr, "New: seqnum: %05d size: %04u, address: %s\n",
378                                         readU16(&(p.data[BASE_HEADER_SIZE+1])),p.data.getSize(),
379                                         p.address.serializeString().c_str());
380                         throw IncomingDataCorruption("duplicated packet isn't same as original one");
381                 }
382
383                 /* nothing to do this seems to be a resent packet */
384                 /* for paranoia reason data should be compared */
385                 --m_list_size;
386         }
387         /* insert or push back */
388         else if (i != m_list.end()) {
389                 m_list.insert(i, p);
390         }
391         else {
392                 m_list.push_back(p);
393         }
394
395         /* update last packet number */
396         m_oldest_non_answered_ack = readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]);
397 }
398
399 void ReliablePacketBuffer::incrementTimeouts(float dtime)
400 {
401         MutexAutoLock listlock(m_list_mutex);
402         for (BufferedPacket &bufferedPacket : m_list) {
403                 bufferedPacket.time += dtime;
404                 bufferedPacket.totaltime += dtime;
405         }
406 }
407
408 std::list<BufferedPacket> ReliablePacketBuffer::getTimedOuts(float timeout,
409                                                                                                         unsigned int max_packets)
410 {
411         MutexAutoLock listlock(m_list_mutex);
412         std::list<BufferedPacket> timed_outs;
413         for (BufferedPacket &bufferedPacket : m_list) {
414                 if (bufferedPacket.time >= timeout) {
415                         timed_outs.push_back(bufferedPacket);
416
417                         //this packet will be sent right afterwards reset timeout here
418                         bufferedPacket.time = 0.0f;
419                         if (timed_outs.size() >= max_packets)
420                                 break;
421                 }
422         }
423         return timed_outs;
424 }
425
426 /*
427         IncomingSplitBuffer
428 */
429
430 IncomingSplitBuffer::~IncomingSplitBuffer()
431 {
432         MutexAutoLock listlock(m_map_mutex);
433         for (auto &i : m_buf) {
434                 delete i.second;
435         }
436 }
437 /*
438         This will throw a GotSplitPacketException when a full
439         split packet is constructed.
440 */
441 SharedBuffer<u8> IncomingSplitBuffer::insert(BufferedPacket &p, bool reliable)
442 {
443         MutexAutoLock listlock(m_map_mutex);
444         u32 headersize = BASE_HEADER_SIZE + 7;
445         if (p.data.getSize() < headersize) {
446                 errorstream << "Invalid data size for split packet" << std::endl;
447                 return SharedBuffer<u8>();
448         }
449         u8 type = readU8(&p.data[BASE_HEADER_SIZE+0]);
450         u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]);
451         u16 chunk_count = readU16(&p.data[BASE_HEADER_SIZE+3]);
452         u16 chunk_num = readU16(&p.data[BASE_HEADER_SIZE+5]);
453
454         if (type != TYPE_SPLIT) {
455                 errorstream << "IncomingSplitBuffer::insert(): type is not split"
456                         << std::endl;
457                 return SharedBuffer<u8>();
458         }
459
460         // Add if doesn't exist
461         if (m_buf.find(seqnum) == m_buf.end())
462         {
463                 IncomingSplitPacket *sp = new IncomingSplitPacket();
464                 sp->chunk_count = chunk_count;
465                 sp->reliable = reliable;
466                 m_buf[seqnum] = sp;
467         }
468
469         IncomingSplitPacket *sp = m_buf[seqnum];
470
471         // TODO: These errors should be thrown or something? Dunno.
472         if (chunk_count != sp->chunk_count)
473                 LOG(derr_con<<"Connection: WARNING: chunk_count="<<chunk_count
474                                 <<" != sp->chunk_count="<<sp->chunk_count
475                                 <<std::endl);
476         if (reliable != sp->reliable)
477                 LOG(derr_con<<"Connection: WARNING: reliable="<<reliable
478                                 <<" != sp->reliable="<<sp->reliable
479                                 <<std::endl);
480
481         // If chunk already exists, ignore it.
482         // Sometimes two identical packets may arrive when there is network
483         // lag and the server re-sends stuff.
484         if (sp->chunks.find(chunk_num) != sp->chunks.end())
485                 return SharedBuffer<u8>();
486
487         // Cut chunk data out of packet
488         u32 chunkdatasize = p.data.getSize() - headersize;
489         SharedBuffer<u8> chunkdata(chunkdatasize);
490         memcpy(*chunkdata, &(p.data[headersize]), chunkdatasize);
491
492         // Set chunk data in buffer
493         sp->chunks[chunk_num] = chunkdata;
494
495         // If not all chunks are received, return empty buffer
496         if (!sp->allReceived())
497                 return SharedBuffer<u8>();
498
499         // Calculate total size
500         u32 totalsize = 0;
501         for (const auto &chunk : sp->chunks) {
502                 totalsize += chunk.second.getSize();
503         }
504
505         SharedBuffer<u8> fulldata(totalsize);
506
507         // Copy chunks to data buffer
508         u32 start = 0;
509         for(u32 chunk_i=0; chunk_i<sp->chunk_count;
510                         chunk_i++)
511         {
512                 SharedBuffer<u8> buf = sp->chunks[chunk_i];
513                 u16 chunkdatasize = buf.getSize();
514                 memcpy(&fulldata[start], *buf, chunkdatasize);
515                 start += chunkdatasize;;
516         }
517
518         // Remove sp from buffer
519         m_buf.erase(seqnum);
520         delete sp;
521
522         return fulldata;
523 }
524 void IncomingSplitBuffer::removeUnreliableTimedOuts(float dtime, float timeout)
525 {
526         std::list<u16> remove_queue;
527         {
528                 MutexAutoLock listlock(m_map_mutex);
529                 for (auto &i : m_buf) {
530                         IncomingSplitPacket *p = i.second;
531                         // Reliable ones are not removed by timeout
532                         if (p->reliable)
533                                 continue;
534                         p->time += dtime;
535                         if (p->time >= timeout)
536                                 remove_queue.push_back(i.first);
537                 }
538         }
539         for (u16 j : remove_queue) {
540                 MutexAutoLock listlock(m_map_mutex);
541                 LOG(dout_con<<"NOTE: Removing timed out unreliable split packet"<<std::endl);
542                 delete m_buf[j];
543                 m_buf.erase(j);
544         }
545 }
546
547 /*
548         ConnectionCommand
549  */
550
551 void ConnectionCommand::send(u16 peer_id_, u8 channelnum_, NetworkPacket *pkt,
552         bool reliable_)
553 {
554         type = CONNCMD_SEND;
555         peer_id = peer_id_;
556         channelnum = channelnum_;
557         data = pkt->oldForgePacket();
558         reliable = reliable_;
559 }
560
561 /*
562         Channel
563 */
564
565 u16 Channel::readNextIncomingSeqNum()
566 {
567         MutexAutoLock internal(m_internal_mutex);
568         return next_incoming_seqnum;
569 }
570
571 u16 Channel::incNextIncomingSeqNum()
572 {
573         MutexAutoLock internal(m_internal_mutex);
574         u16 retval = next_incoming_seqnum;
575         next_incoming_seqnum++;
576         return retval;
577 }
578
579 u16 Channel::readNextSplitSeqNum()
580 {
581         MutexAutoLock internal(m_internal_mutex);
582         return next_outgoing_split_seqnum;
583 }
584 void Channel::setNextSplitSeqNum(u16 seqnum)
585 {
586         MutexAutoLock internal(m_internal_mutex);
587         next_outgoing_split_seqnum = seqnum;
588 }
589
590 u16 Channel::getOutgoingSequenceNumber(bool& successful)
591 {
592         MutexAutoLock internal(m_internal_mutex);
593         u16 retval = next_outgoing_seqnum;
594         u16 lowest_unacked_seqnumber;
595
596         /* shortcut if there ain't any packet in outgoing list */
597         if (outgoing_reliables_sent.empty())
598         {
599                 next_outgoing_seqnum++;
600                 return retval;
601         }
602
603         if (outgoing_reliables_sent.getFirstSeqnum(lowest_unacked_seqnumber))
604         {
605                 if (lowest_unacked_seqnumber < next_outgoing_seqnum) {
606                         // ugly cast but this one is required in order to tell compiler we
607                         // know about difference of two unsigned may be negative in general
608                         // but we already made sure it won't happen in this case
609                         if (((u16)(next_outgoing_seqnum - lowest_unacked_seqnumber)) > window_size) {
610                                 successful = false;
611                                 return 0;
612                         }
613                 }
614                 else {
615                         // ugly cast but this one is required in order to tell compiler we
616                         // know about difference of two unsigned may be negative in general
617                         // but we already made sure it won't happen in this case
618                         if ((next_outgoing_seqnum + (u16)(SEQNUM_MAX - lowest_unacked_seqnumber)) >
619                                 window_size) {
620                                 successful = false;
621                                 return 0;
622                         }
623                 }
624         }
625
626         next_outgoing_seqnum++;
627         return retval;
628 }
629
630 u16 Channel::readOutgoingSequenceNumber()
631 {
632         MutexAutoLock internal(m_internal_mutex);
633         return next_outgoing_seqnum;
634 }
635
636 bool Channel::putBackSequenceNumber(u16 seqnum)
637 {
638         if (((seqnum + 1) % (SEQNUM_MAX+1)) == next_outgoing_seqnum) {
639
640                 next_outgoing_seqnum = seqnum;
641                 return true;
642         }
643         return false;
644 }
645
646 void Channel::UpdateBytesSent(unsigned int bytes, unsigned int packets)
647 {
648         MutexAutoLock internal(m_internal_mutex);
649         current_bytes_transfered += bytes;
650         current_packet_successfull += packets;
651 }
652
653 void Channel::UpdateBytesReceived(unsigned int bytes) {
654         MutexAutoLock internal(m_internal_mutex);
655         current_bytes_received += bytes;
656 }
657
658 void Channel::UpdateBytesLost(unsigned int bytes)
659 {
660         MutexAutoLock internal(m_internal_mutex);
661         current_bytes_lost += bytes;
662 }
663
664
665 void Channel::UpdatePacketLossCounter(unsigned int count)
666 {
667         MutexAutoLock internal(m_internal_mutex);
668         current_packet_loss += count;
669 }
670
671 void Channel::UpdatePacketTooLateCounter()
672 {
673         MutexAutoLock internal(m_internal_mutex);
674         current_packet_too_late++;
675 }
676
677 void Channel::UpdateTimers(float dtime,bool legacy_peer)
678 {
679         bpm_counter += dtime;
680         packet_loss_counter += dtime;
681
682         if (packet_loss_counter > 1.0)
683         {
684                 packet_loss_counter -= 1.0;
685
686                 unsigned int packet_loss = 11; /* use a neutral value for initialization */
687                 unsigned int packets_successfull = 0;
688                 //unsigned int packet_too_late = 0;
689
690                 bool reasonable_amount_of_data_transmitted = false;
691
692                 {
693                         MutexAutoLock internal(m_internal_mutex);
694                         packet_loss = current_packet_loss;
695                         //packet_too_late = current_packet_too_late;
696                         packets_successfull = current_packet_successfull;
697
698                         if (current_bytes_transfered > (unsigned int) (window_size*512/2))
699                         {
700                                 reasonable_amount_of_data_transmitted = true;
701                         }
702                         current_packet_loss = 0;
703                         current_packet_too_late = 0;
704                         current_packet_successfull = 0;
705                 }
706
707                 /* dynamic window size is only available for non legacy peers */
708                 if (!legacy_peer) {
709                         float successfull_to_lost_ratio = 0.0;
710                         bool done = false;
711
712                         if (packets_successfull > 0) {
713                                 successfull_to_lost_ratio = packet_loss/packets_successfull;
714                         }
715                         else if (packet_loss > 0)
716                         {
717                                 window_size = MYMAX(
718                                                 (window_size - 10),
719                                                 MIN_RELIABLE_WINDOW_SIZE);
720                                 done = true;
721                         }
722
723                         if (!done)
724                         {
725                                 if ((successfull_to_lost_ratio < 0.01) &&
726                                         (window_size < MAX_RELIABLE_WINDOW_SIZE))
727                                 {
728                                         /* don't even think about increasing if we didn't even
729                                          * use major parts of our window */
730                                         if (reasonable_amount_of_data_transmitted)
731                                                 window_size = MYMIN(
732                                                                 (window_size + 100),
733                                                                 MAX_RELIABLE_WINDOW_SIZE);
734                                 }
735                                 else if ((successfull_to_lost_ratio < 0.05) &&
736                                                 (window_size < MAX_RELIABLE_WINDOW_SIZE))
737                                 {
738                                         /* don't even think about increasing if we didn't even
739                                          * use major parts of our window */
740                                         if (reasonable_amount_of_data_transmitted)
741                                                 window_size = MYMIN(
742                                                                 (window_size + 50),
743                                                                 MAX_RELIABLE_WINDOW_SIZE);
744                                 }
745                                 else if (successfull_to_lost_ratio > 0.15)
746                                 {
747                                         window_size = MYMAX(
748                                                         (window_size - 100),
749                                                         MIN_RELIABLE_WINDOW_SIZE);
750                                 }
751                                 else if (successfull_to_lost_ratio > 0.1)
752                                 {
753                                         window_size = MYMAX(
754                                                         (window_size - 50),
755                                                         MIN_RELIABLE_WINDOW_SIZE);
756                                 }
757                         }
758                 }
759         }
760
761         if (bpm_counter > 10.0)
762         {
763                 {
764                         MutexAutoLock internal(m_internal_mutex);
765                         cur_kbps                 =
766                                         (((float) current_bytes_transfered)/bpm_counter)/1024.0;
767                         current_bytes_transfered = 0;
768                         cur_kbps_lost            =
769                                         (((float) current_bytes_lost)/bpm_counter)/1024.0;
770                         current_bytes_lost       = 0;
771                         cur_incoming_kbps        =
772                                         (((float) current_bytes_received)/bpm_counter)/1024.0;
773                         current_bytes_received   = 0;
774                         bpm_counter              = 0;
775                 }
776
777                 if (cur_kbps > max_kbps)
778                 {
779                         max_kbps = cur_kbps;
780                 }
781
782                 if (cur_kbps_lost > max_kbps_lost)
783                 {
784                         max_kbps_lost = cur_kbps_lost;
785                 }
786
787                 if (cur_incoming_kbps > max_incoming_kbps) {
788                         max_incoming_kbps = cur_incoming_kbps;
789                 }
790
791                 rate_samples       = MYMIN(rate_samples+1,10);
792                 float old_fraction = ((float) (rate_samples-1) )/( (float) rate_samples);
793                 avg_kbps           = avg_kbps * old_fraction +
794                                 cur_kbps * (1.0 - old_fraction);
795                 avg_kbps_lost      = avg_kbps_lost * old_fraction +
796                                 cur_kbps_lost * (1.0 - old_fraction);
797                 avg_incoming_kbps  = avg_incoming_kbps * old_fraction +
798                                 cur_incoming_kbps * (1.0 - old_fraction);
799         }
800 }
801
802
803 /*
804         Peer
805 */
806
807 PeerHelper::PeerHelper(Peer* peer) :
808         m_peer(peer)
809 {
810         if (peer && !peer->IncUseCount())
811                 m_peer = nullptr;
812 }
813
814 PeerHelper::~PeerHelper()
815 {
816         if (m_peer)
817                 m_peer->DecUseCount();
818
819         m_peer = nullptr;
820 }
821
822 PeerHelper& PeerHelper::operator=(Peer* peer)
823 {
824         m_peer = peer;
825         if (peer && !peer->IncUseCount())
826                 m_peer = nullptr;
827         return *this;
828 }
829
830 Peer* PeerHelper::operator->() const
831 {
832         return m_peer;
833 }
834
835 Peer* PeerHelper::operator&() const
836 {
837         return m_peer;
838 }
839
840 bool PeerHelper::operator!() {
841         return ! m_peer;
842 }
843
844 bool PeerHelper::operator!=(void* ptr)
845 {
846         return ((void*) m_peer != ptr);
847 }
848
849 bool Peer::IncUseCount()
850 {
851         MutexAutoLock lock(m_exclusive_access_mutex);
852
853         if (!m_pending_deletion) {
854                 this->m_usage++;
855                 return true;
856         }
857
858         return false;
859 }
860
861 void Peer::DecUseCount()
862 {
863         {
864                 MutexAutoLock lock(m_exclusive_access_mutex);
865                 sanity_check(m_usage > 0);
866                 m_usage--;
867
868                 if (!((m_pending_deletion) && (m_usage == 0)))
869                         return;
870         }
871         delete this;
872 }
873
874 void Peer::RTTStatistics(float rtt, const std::string &profiler_id,
875                 unsigned int num_samples) {
876
877         if (m_last_rtt > 0) {
878                 /* set min max values */
879                 if (rtt < m_rtt.min_rtt)
880                         m_rtt.min_rtt = rtt;
881                 if (rtt >= m_rtt.max_rtt)
882                         m_rtt.max_rtt = rtt;
883
884                 /* do average calculation */
885                 if (m_rtt.avg_rtt < 0.0)
886                         m_rtt.avg_rtt  = rtt;
887                 else
888                         m_rtt.avg_rtt  = m_rtt.avg_rtt * (num_samples/(num_samples-1)) +
889                                                                 rtt * (1/num_samples);
890
891                 /* do jitter calculation */
892
893                 //just use some neutral value at beginning
894                 float jitter = m_rtt.jitter_min;
895
896                 if (rtt > m_last_rtt)
897                         jitter = rtt-m_last_rtt;
898
899                 if (rtt <= m_last_rtt)
900                         jitter = m_last_rtt - rtt;
901
902                 if (jitter < m_rtt.jitter_min)
903                         m_rtt.jitter_min = jitter;
904                 if (jitter >= m_rtt.jitter_max)
905                         m_rtt.jitter_max = jitter;
906
907                 if (m_rtt.jitter_avg < 0.0)
908                         m_rtt.jitter_avg  = jitter;
909                 else
910                         m_rtt.jitter_avg  = m_rtt.jitter_avg * (num_samples/(num_samples-1)) +
911                                                                 jitter * (1/num_samples);
912
913                 if (!profiler_id.empty()) {
914                         g_profiler->graphAdd(profiler_id + "_rtt", rtt);
915                         g_profiler->graphAdd(profiler_id + "_jitter", jitter);
916                 }
917         }
918         /* save values required for next loop */
919         m_last_rtt = rtt;
920 }
921
922 bool Peer::isTimedOut(float timeout)
923 {
924         MutexAutoLock lock(m_exclusive_access_mutex);
925         u64 current_time = porting::getTimeMs();
926
927         float dtime = CALC_DTIME(m_last_timeout_check,current_time);
928         m_last_timeout_check = current_time;
929
930         m_timeout_counter += dtime;
931
932         return m_timeout_counter > timeout;
933 }
934
935 void Peer::Drop()
936 {
937         {
938                 MutexAutoLock usage_lock(m_exclusive_access_mutex);
939                 m_pending_deletion = true;
940                 if (m_usage != 0)
941                         return;
942         }
943
944         PROFILE(std::stringstream peerIdentifier1);
945         PROFILE(peerIdentifier1 << "runTimeouts[" << m_connection->getDesc()
946                         << ";" << id << ";RELIABLE]");
947         PROFILE(g_profiler->remove(peerIdentifier1.str()));
948         PROFILE(std::stringstream peerIdentifier2);
949         PROFILE(peerIdentifier2 << "sendPackets[" << m_connection->getDesc()
950                         << ";" << id << ";RELIABLE]");
951         PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier2.str(), SPT_AVG));
952
953         delete this;
954 }
955
956 UDPPeer::UDPPeer(u16 a_id, Address a_address, Connection* connection) :
957         Peer(a_address,a_id,connection)
958 {
959 }
960
961 bool UDPPeer::getAddress(MTProtocols type,Address& toset)
962 {
963         if ((type == MTP_UDP) || (type == MTP_MINETEST_RELIABLE_UDP) || (type == MTP_PRIMARY))
964         {
965                 toset = address;
966                 return true;
967         }
968
969         return false;
970 }
971
972 void UDPPeer::setNonLegacyPeer()
973 {
974         m_legacy_peer = false;
975         for(unsigned int i=0; i< CHANNEL_COUNT; i++)
976         {
977                 channels->setWindowSize(g_settings->getU16("max_packets_per_iteration"));
978         }
979 }
980
981 void UDPPeer::reportRTT(float rtt)
982 {
983         if (rtt < 0.0) {
984                 return;
985         }
986         RTTStatistics(rtt,"rudp",MAX_RELIABLE_WINDOW_SIZE*10);
987
988         float timeout = getStat(AVG_RTT) * RESEND_TIMEOUT_FACTOR;
989         if (timeout < RESEND_TIMEOUT_MIN)
990                 timeout = RESEND_TIMEOUT_MIN;
991         if (timeout > RESEND_TIMEOUT_MAX)
992                 timeout = RESEND_TIMEOUT_MAX;
993
994         MutexAutoLock usage_lock(m_exclusive_access_mutex);
995         resend_timeout = timeout;
996 }
997
998 bool UDPPeer::Ping(float dtime,SharedBuffer<u8>& data)
999 {
1000         m_ping_timer += dtime;
1001         if (m_ping_timer >= PING_TIMEOUT)
1002         {
1003                 // Create and send PING packet
1004                 writeU8(&data[0], TYPE_CONTROL);
1005                 writeU8(&data[1], CONTROLTYPE_PING);
1006                 m_ping_timer = 0.0;
1007                 return true;
1008         }
1009         return false;
1010 }
1011
1012 void UDPPeer::PutReliableSendCommand(ConnectionCommand &c,
1013                 unsigned int max_packet_size)
1014 {
1015         if (m_pending_disconnect)
1016                 return;
1017
1018         if ( channels[c.channelnum].queued_commands.empty() &&
1019                         /* don't queue more packets then window size */
1020                         (channels[c.channelnum].queued_reliables.size()
1021                         < (channels[c.channelnum].getWindowSize()/2))) {
1022                 LOG(dout_con<<m_connection->getDesc()
1023                                 <<" processing reliable command for peer id: " << c.peer_id
1024                                 <<" data size: " << c.data.getSize() << std::endl);
1025                 if (!processReliableSendCommand(c,max_packet_size)) {
1026                         channels[c.channelnum].queued_commands.push_back(c);
1027                 }
1028         }
1029         else {
1030                 LOG(dout_con<<m_connection->getDesc()
1031                                 <<" Queueing reliable command for peer id: " << c.peer_id
1032                                 <<" data size: " << c.data.getSize() <<std::endl);
1033                 channels[c.channelnum].queued_commands.push_back(c);
1034         }
1035 }
1036
1037 bool UDPPeer::processReliableSendCommand(
1038                                 ConnectionCommand &c,
1039                                 unsigned int max_packet_size)
1040 {
1041         if (m_pending_disconnect)
1042                 return true;
1043
1044         u32 chunksize_max = max_packet_size
1045                                                         - BASE_HEADER_SIZE
1046                                                         - RELIABLE_HEADER_SIZE;
1047
1048         sanity_check(c.data.getSize() < MAX_RELIABLE_WINDOW_SIZE*512);
1049
1050         std::list<SharedBuffer<u8> > originals;
1051         u16 split_sequence_number = channels[c.channelnum].readNextSplitSeqNum();
1052
1053         if (c.raw)
1054         {
1055                 originals.emplace_back(c.data);
1056         }
1057         else {
1058                 originals = makeAutoSplitPacket(c.data, chunksize_max,split_sequence_number);
1059                 channels[c.channelnum].setNextSplitSeqNum(split_sequence_number);
1060         }
1061
1062         bool have_sequence_number = true;
1063         bool have_initial_sequence_number = false;
1064         std::queue<BufferedPacket> toadd;
1065         volatile u16 initial_sequence_number = 0;
1066
1067         for (SharedBuffer<u8> &original : originals) {
1068                 u16 seqnum = channels[c.channelnum].getOutgoingSequenceNumber(have_sequence_number);
1069
1070                 /* oops, we don't have enough sequence numbers to send this packet */
1071                 if (!have_sequence_number)
1072                         break;
1073
1074                 if (!have_initial_sequence_number)
1075                 {
1076                         initial_sequence_number = seqnum;
1077                         have_initial_sequence_number = true;
1078                 }
1079
1080                 SharedBuffer<u8> reliable = makeReliablePacket(original, seqnum);
1081
1082                 // Add base headers and make a packet
1083                 BufferedPacket p = con::makePacket(address, reliable,
1084                                 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1085                                 c.channelnum);
1086
1087                 toadd.push(p);
1088         }
1089
1090         if (have_sequence_number) {
1091                 volatile u16 pcount = 0;
1092                 while (!toadd.empty()) {
1093                         BufferedPacket p = toadd.front();
1094                         toadd.pop();
1095 //                      LOG(dout_con<<connection->getDesc()
1096 //                                      << " queuing reliable packet for peer_id: " << c.peer_id
1097 //                                      << " channel: " << (c.channelnum&0xFF)
1098 //                                      << " seqnum: " << readU16(&p.data[BASE_HEADER_SIZE+1])
1099 //                                      << std::endl)
1100                         channels[c.channelnum].queued_reliables.push(p);
1101                         pcount++;
1102                 }
1103                 sanity_check(channels[c.channelnum].queued_reliables.size() < 0xFFFF);
1104                 return true;
1105         }
1106
1107         volatile u16 packets_available = toadd.size();
1108         /* we didn't get a single sequence number no need to fill queue */
1109         if (!have_initial_sequence_number) {
1110                 return false;
1111         }
1112
1113         while (!toadd.empty()) {
1114                 /* remove packet */
1115                 toadd.pop();
1116
1117                 bool successfully_put_back_sequence_number
1118                         = channels[c.channelnum].putBackSequenceNumber(
1119                                 (initial_sequence_number+toadd.size() % (SEQNUM_MAX+1)));
1120
1121                 FATAL_ERROR_IF(!successfully_put_back_sequence_number, "error");
1122         }
1123
1124         LOG(dout_con<<m_connection->getDesc()
1125                         << " Windowsize exceeded on reliable sending "
1126                         << c.data.getSize() << " bytes"
1127                         << std::endl << "\t\tinitial_sequence_number: "
1128                         << initial_sequence_number
1129                         << std::endl << "\t\tgot at most            : "
1130                         << packets_available << " packets"
1131                         << std::endl << "\t\tpackets queued         : "
1132                         << channels[c.channelnum].outgoing_reliables_sent.size()
1133                         << std::endl);
1134
1135         return false;
1136 }
1137
1138 void UDPPeer::RunCommandQueues(
1139                                                         unsigned int max_packet_size,
1140                                                         unsigned int maxcommands,
1141                                                         unsigned int maxtransfer)
1142 {
1143
1144         for (Channel &channel : channels) {
1145                 unsigned int commands_processed = 0;
1146
1147                 if ((!channel.queued_commands.empty()) &&
1148                                 (channel.queued_reliables.size() < maxtransfer) &&
1149                                 (commands_processed < maxcommands)) {
1150                         try {
1151                                 ConnectionCommand c = channel.queued_commands.front();
1152
1153                                 LOG(dout_con << m_connection->getDesc()
1154                                                 << " processing queued reliable command " << std::endl);
1155
1156                                 // Packet is processed, remove it from queue
1157                                 if (processReliableSendCommand(c,max_packet_size)) {
1158                                         channel.queued_commands.pop_front();
1159                                 } else {
1160                                         LOG(dout_con << m_connection->getDesc()
1161                                                         << " Failed to queue packets for peer_id: " << c.peer_id
1162                                                         << ", delaying sending of " << c.data.getSize()
1163                                                         << " bytes" << std::endl);
1164                                 }
1165                         }
1166                         catch (ItemNotFoundException &e) {
1167                                 // intentionally empty
1168                         }
1169                 }
1170         }
1171 }
1172
1173 u16 UDPPeer::getNextSplitSequenceNumber(u8 channel)
1174 {
1175         assert(channel < CHANNEL_COUNT); // Pre-condition
1176         return channels[channel].readNextSplitSeqNum();
1177 }
1178
1179 void UDPPeer::setNextSplitSequenceNumber(u8 channel, u16 seqnum)
1180 {
1181         assert(channel < CHANNEL_COUNT); // Pre-condition
1182         channels[channel].setNextSplitSeqNum(seqnum);
1183 }
1184
1185 SharedBuffer<u8> UDPPeer::addSpiltPacket(u8 channel,
1186                                                                                         BufferedPacket toadd,
1187                                                                                         bool reliable)
1188 {
1189         assert(channel < CHANNEL_COUNT); // Pre-condition
1190         return channels[channel].incoming_splits.insert(toadd,reliable);
1191 }
1192
1193 /******************************************************************************/
1194 /* Connection Threads                                                         */
1195 /******************************************************************************/
1196
1197 ConnectionSendThread::ConnectionSendThread(unsigned int max_packet_size,
1198                 float timeout) :
1199         Thread("ConnectionSend"),
1200         m_max_packet_size(max_packet_size),
1201         m_timeout(timeout),
1202         m_max_data_packets_per_iteration(g_settings->getU16("max_packets_per_iteration"))
1203 {
1204 }
1205
1206 void * ConnectionSendThread::run()
1207 {
1208         assert(m_connection);
1209
1210         LOG(dout_con<<m_connection->getDesc()
1211                         <<"ConnectionSend thread started"<<std::endl);
1212
1213         u64 curtime = porting::getTimeMs();
1214         u64 lasttime = curtime;
1215
1216         PROFILE(std::stringstream ThreadIdentifier);
1217         PROFILE(ThreadIdentifier << "ConnectionSend: [" << m_connection->getDesc() << "]");
1218
1219         /* if stop is requested don't stop immediately but try to send all        */
1220         /* packets first */
1221         while(!stopRequested() || packetsQueued()) {
1222                 BEGIN_DEBUG_EXCEPTION_HANDLER
1223                 PROFILE(ScopeProfiler sp(g_profiler, ThreadIdentifier.str(), SPT_AVG));
1224
1225                 m_iteration_packets_avaialble = m_max_data_packets_per_iteration;
1226
1227                 /* wait for trigger or timeout */
1228                 m_send_sleep_semaphore.wait(50);
1229
1230                 /* remove all triggers */
1231                 while(m_send_sleep_semaphore.wait(0)) {}
1232
1233                 lasttime = curtime;
1234                 curtime = porting::getTimeMs();
1235                 float dtime = CALC_DTIME(lasttime,curtime);
1236
1237                 /* first do all the reliable stuff */
1238                 runTimeouts(dtime);
1239
1240                 /* translate commands to packets */
1241                 ConnectionCommand c = m_connection->m_command_queue.pop_frontNoEx(0);
1242                 while(c.type != CONNCMD_NONE)
1243                                 {
1244                         if (c.reliable)
1245                                 processReliableCommand(c);
1246                         else
1247                                 processNonReliableCommand(c);
1248
1249                         c = m_connection->m_command_queue.pop_frontNoEx(0);
1250                 }
1251
1252                 /* send non reliable packets */
1253                 sendPackets(dtime);
1254
1255                 END_DEBUG_EXCEPTION_HANDLER
1256         }
1257
1258         PROFILE(g_profiler->remove(ThreadIdentifier.str()));
1259         return NULL;
1260 }
1261
1262 void ConnectionSendThread::Trigger()
1263 {
1264         m_send_sleep_semaphore.post();
1265 }
1266
1267 bool ConnectionSendThread::packetsQueued()
1268 {
1269         std::list<u16> peerIds = m_connection->getPeerIDs();
1270
1271         if (!m_outgoing_queue.empty() && !peerIds.empty())
1272                 return true;
1273
1274         for (u16 peerId : peerIds) {
1275                 PeerHelper peer = m_connection->getPeerNoEx(peerId);
1276
1277                 if (!peer)
1278                         continue;
1279
1280                 if (dynamic_cast<UDPPeer*>(&peer) == 0)
1281                         continue;
1282
1283                 for (Channel &channel : (dynamic_cast<UDPPeer *>(&peer))->channels) {
1284                         if (channel.queued_commands.size() > 0) {
1285                                 return true;
1286                         }
1287                 }
1288         }
1289
1290
1291         return false;
1292 }
1293
1294 void ConnectionSendThread::runTimeouts(float dtime)
1295 {
1296         std::list<u16> timeouted_peers;
1297         std::list<u16> peerIds = m_connection->getPeerIDs();
1298
1299         for (u16 &peerId : peerIds) {
1300                 PeerHelper peer = m_connection->getPeerNoEx(peerId);
1301
1302                 if (!peer)
1303                         continue;
1304
1305                 if (dynamic_cast<UDPPeer*>(&peer) == 0)
1306                         continue;
1307
1308                 PROFILE(std::stringstream peerIdentifier);
1309                 PROFILE(peerIdentifier << "runTimeouts[" << m_connection->getDesc()
1310                                 << ";" << peerId << ";RELIABLE]");
1311                 PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier.str(), SPT_AVG));
1312
1313                 SharedBuffer<u8> data(2); // data for sending ping, required here because of goto
1314
1315                 /*
1316                         Check peer timeout
1317                 */
1318                 if (peer->isTimedOut(m_timeout))
1319                 {
1320                         infostream<<m_connection->getDesc()
1321                                         <<"RunTimeouts(): Peer "<<peer->id
1322                                         <<" has timed out."
1323                                         <<" (source=peer->timeout_counter)"
1324                                         <<std::endl;
1325                         // Add peer to the list
1326                         timeouted_peers.push_back(peer->id);
1327                         // Don't bother going through the buffers of this one
1328                         continue;
1329                 }
1330
1331                 float resend_timeout = dynamic_cast<UDPPeer*>(&peer)->getResendTimeout();
1332                 bool retry_count_exceeded = false;
1333                 for (Channel &channel : (dynamic_cast<UDPPeer *>(&peer))->channels) {
1334                         std::list<BufferedPacket> timed_outs;
1335
1336                         if (dynamic_cast<UDPPeer*>(&peer)->getLegacyPeer())
1337                                 channel.setWindowSize(g_settings->getU16("workaround_window_size"));
1338
1339                         // Remove timed out incomplete unreliable split packets
1340                         channel.incoming_splits.removeUnreliableTimedOuts(dtime, m_timeout);
1341
1342                         // Increment reliable packet times
1343                         channel.outgoing_reliables_sent.incrementTimeouts(dtime);
1344
1345                         unsigned int numpeers = m_connection->m_peers.size();
1346
1347                         if (numpeers == 0)
1348                                 return;
1349
1350                         // Re-send timed out outgoing reliables
1351                         timed_outs = channel.outgoing_reliables_sent.getTimedOuts(resend_timeout,
1352                                         (m_max_data_packets_per_iteration/numpeers));
1353
1354                         channel.UpdatePacketLossCounter(timed_outs.size());
1355                         g_profiler->graphAdd("packets_lost", timed_outs.size());
1356
1357                         m_iteration_packets_avaialble -= timed_outs.size();
1358
1359                         for(std::list<BufferedPacket>::iterator k = timed_outs.begin();
1360                                 k != timed_outs.end(); ++k)
1361                         {
1362                                 u16 peer_id = readPeerId(*(k->data));
1363                                 u8 channelnum  = readChannel(*(k->data));
1364                                 u16 seqnum  = readU16(&(k->data[BASE_HEADER_SIZE+1]));
1365
1366                                 channel.UpdateBytesLost(k->data.getSize());
1367                                 k->resend_count++;
1368
1369                                 if (k-> resend_count > MAX_RELIABLE_RETRY) {
1370                                         retry_count_exceeded = true;
1371                                         timeouted_peers.push_back(peer->id);
1372                                         /* no need to check additional packets if a single one did timeout*/
1373                                         break;
1374                                 }
1375
1376                                 LOG(derr_con<<m_connection->getDesc()
1377                                                 <<"RE-SENDING timed-out RELIABLE to "
1378                                                 << k->address.serializeString()
1379                                                 << "(t/o="<<resend_timeout<<"): "
1380                                                 <<"from_peer_id="<<peer_id
1381                                                 <<", channel="<<((int)channelnum&0xff)
1382                                                 <<", seqnum="<<seqnum
1383                                                 <<std::endl);
1384
1385                                 rawSend(*k);
1386
1387                                 // do not handle rtt here as we can't decide if this packet was
1388                                 // lost or really takes more time to transmit
1389                         }
1390
1391                         if (retry_count_exceeded) {
1392                                 break; /* no need to check other channels if we already did timeout */
1393                         }
1394
1395                         channel.UpdateTimers(dtime,dynamic_cast<UDPPeer*>(&peer)->getLegacyPeer());
1396                 }
1397
1398                 /* skip to next peer if we did timeout */
1399                 if (retry_count_exceeded)
1400                         continue;
1401
1402                 /* send ping if necessary */
1403                 if (dynamic_cast<UDPPeer*>(&peer)->Ping(dtime,data)) {
1404                         LOG(dout_con<<m_connection->getDesc()
1405                                         <<"Sending ping for peer_id: "
1406                                         << dynamic_cast<UDPPeer*>(&peer)->id <<std::endl);
1407                         /* this may fail if there ain't a sequence number left */
1408                         if (!rawSendAsPacket(dynamic_cast<UDPPeer*>(&peer)->id, 0, data, true))
1409                         {
1410                                 //retrigger with reduced ping interval
1411                                 dynamic_cast<UDPPeer*>(&peer)->Ping(4.0,data);
1412                         }
1413                 }
1414
1415                 dynamic_cast<UDPPeer*>(&peer)->RunCommandQueues(m_max_packet_size,
1416                                                                 m_max_commands_per_iteration,
1417                                                                 m_max_packets_requeued);
1418         }
1419
1420         // Remove timed out peers
1421         for (u16 timeouted_peer : timeouted_peers) {
1422                 LOG(derr_con << m_connection->getDesc()
1423                                 << "RunTimeouts(): Removing peer "<< timeouted_peer <<std::endl);
1424                 m_connection->deletePeer(timeouted_peer, true);
1425         }
1426 }
1427
1428 void ConnectionSendThread::rawSend(const BufferedPacket &packet)
1429 {
1430         try{
1431                 m_connection->m_udpSocket.Send(packet.address, *packet.data,
1432                                 packet.data.getSize());
1433                 LOG(dout_con <<m_connection->getDesc()
1434                                 << " rawSend: " << packet.data.getSize()
1435                                 << " bytes sent" << std::endl);
1436         } catch(SendFailedException &e) {
1437                 LOG(derr_con<<m_connection->getDesc()
1438                                 <<"Connection::rawSend(): SendFailedException: "
1439                                 <<packet.address.serializeString()<<std::endl);
1440         }
1441 }
1442
1443 void ConnectionSendThread::sendAsPacketReliable(BufferedPacket& p, Channel* channel)
1444 {
1445         try{
1446                 p.absolute_send_time = porting::getTimeMs();
1447                 // Buffer the packet
1448                 channel->outgoing_reliables_sent.insert(p,
1449                         (channel->readOutgoingSequenceNumber() - MAX_RELIABLE_WINDOW_SIZE)
1450                         % (MAX_RELIABLE_WINDOW_SIZE+1));
1451         }
1452         catch(AlreadyExistsException &e)
1453         {
1454                 LOG(derr_con<<m_connection->getDesc()
1455                                 <<"WARNING: Going to send a reliable packet"
1456                                 <<" in outgoing buffer" <<std::endl);
1457         }
1458
1459         // Send the packet
1460         rawSend(p);
1461 }
1462
1463 bool ConnectionSendThread::rawSendAsPacket(u16 peer_id, u8 channelnum,
1464                 SharedBuffer<u8> data, bool reliable)
1465 {
1466         PeerHelper peer = m_connection->getPeerNoEx(peer_id);
1467         if (!peer) {
1468                 LOG(dout_con<<m_connection->getDesc()
1469                                 <<" INFO: dropped packet for non existent peer_id: "
1470                                 << peer_id << std::endl);
1471                 FATAL_ERROR_IF(!reliable, "Trying to send raw packet reliable but no peer found!");
1472                 return false;
1473         }
1474         Channel *channel = &(dynamic_cast<UDPPeer*>(&peer)->channels[channelnum]);
1475
1476         if (reliable)
1477         {
1478                 bool have_sequence_number_for_raw_packet = true;
1479                 u16 seqnum =
1480                                 channel->getOutgoingSequenceNumber(have_sequence_number_for_raw_packet);
1481
1482                 if (!have_sequence_number_for_raw_packet)
1483                         return false;
1484
1485                 SharedBuffer<u8> reliable = makeReliablePacket(data, seqnum);
1486                 Address peer_address;
1487                 peer->getAddress(MTP_MINETEST_RELIABLE_UDP, peer_address);
1488
1489                 // Add base headers and make a packet
1490                 BufferedPacket p = con::makePacket(peer_address, reliable,
1491                                 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1492                                 channelnum);
1493
1494                 // first check if our send window is already maxed out
1495                 if (channel->outgoing_reliables_sent.size()
1496                                 < channel->getWindowSize()) {
1497                         LOG(dout_con<<m_connection->getDesc()
1498                                         <<" INFO: sending a reliable packet to peer_id " << peer_id
1499                                         <<" channel: " << channelnum
1500                                         <<" seqnum: " << seqnum << std::endl);
1501                         sendAsPacketReliable(p,channel);
1502                         return true;
1503                 }
1504
1505                 LOG(dout_con<<m_connection->getDesc()
1506                                 <<" INFO: queueing reliable packet for peer_id: " << peer_id
1507                                 <<" channel: " << channelnum
1508                                 <<" seqnum: " << seqnum << std::endl);
1509                 channel->queued_reliables.push(p);
1510                 return false;
1511         }
1512
1513         Address peer_address;
1514         if (peer->getAddress(MTP_UDP, peer_address)) {
1515                 // Add base headers and make a packet
1516                 BufferedPacket p = con::makePacket(peer_address, data,
1517                                 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1518                                 channelnum);
1519
1520                 // Send the packet
1521                 rawSend(p);
1522                 return true;
1523         }
1524
1525         LOG(dout_con << m_connection->getDesc()
1526                         << " INFO: dropped unreliable packet for peer_id: " << peer_id
1527                         << " because of (yet) missing udp address" << std::endl);
1528         return false;
1529 }
1530
1531 void ConnectionSendThread::processReliableCommand(ConnectionCommand &c)
1532 {
1533         assert(c.reliable);  // Pre-condition
1534
1535         switch(c.type) {
1536         case CONNCMD_NONE:
1537                 LOG(dout_con<<m_connection->getDesc()
1538                                 <<"UDP processing reliable CONNCMD_NONE"<<std::endl);
1539                 return;
1540
1541         case CONNCMD_SEND:
1542                 LOG(dout_con<<m_connection->getDesc()
1543                                 <<"UDP processing reliable CONNCMD_SEND"<<std::endl);
1544                 sendReliable(c);
1545                 return;
1546
1547         case CONNCMD_SEND_TO_ALL:
1548                 LOG(dout_con<<m_connection->getDesc()
1549                                 <<"UDP processing CONNCMD_SEND_TO_ALL"<<std::endl);
1550                 sendToAllReliable(c);
1551                 return;
1552
1553         case CONCMD_CREATE_PEER:
1554                 LOG(dout_con<<m_connection->getDesc()
1555                                 <<"UDP processing reliable CONCMD_CREATE_PEER"<<std::endl);
1556                 if (!rawSendAsPacket(c.peer_id,c.channelnum,c.data,c.reliable))
1557                 {
1558                         /* put to queue if we couldn't send it immediately */
1559                         sendReliable(c);
1560                 }
1561                 return;
1562
1563         case CONCMD_DISABLE_LEGACY:
1564                 LOG(dout_con<<m_connection->getDesc()
1565                                 <<"UDP processing reliable CONCMD_DISABLE_LEGACY"<<std::endl);
1566                 if (!rawSendAsPacket(c.peer_id,c.channelnum,c.data,c.reliable))
1567                 {
1568                         /* put to queue if we couldn't send it immediately */
1569                         sendReliable(c);
1570                 }
1571                 return;
1572
1573         case CONNCMD_SERVE:
1574         case CONNCMD_CONNECT:
1575         case CONNCMD_DISCONNECT:
1576         case CONCMD_ACK:
1577                 FATAL_ERROR("Got command that shouldn't be reliable as reliable command");
1578         default:
1579                 LOG(dout_con<<m_connection->getDesc()
1580                                 <<" Invalid reliable command type: " << c.type <<std::endl);
1581         }
1582 }
1583
1584
1585 void ConnectionSendThread::processNonReliableCommand(ConnectionCommand &c)
1586 {
1587         assert(!c.reliable); // Pre-condition
1588
1589         switch(c.type) {
1590         case CONNCMD_NONE:
1591                 LOG(dout_con<<m_connection->getDesc()
1592                                 <<" UDP processing CONNCMD_NONE"<<std::endl);
1593                 return;
1594         case CONNCMD_SERVE:
1595                 LOG(dout_con<<m_connection->getDesc()
1596                                 <<" UDP processing CONNCMD_SERVE port="
1597                                 <<c.address.serializeString()<<std::endl);
1598                 serve(c.address);
1599                 return;
1600         case CONNCMD_CONNECT:
1601                 LOG(dout_con<<m_connection->getDesc()
1602                                 <<" UDP processing CONNCMD_CONNECT"<<std::endl);
1603                 connect(c.address);
1604                 return;
1605         case CONNCMD_DISCONNECT:
1606                 LOG(dout_con<<m_connection->getDesc()
1607                                 <<" UDP processing CONNCMD_DISCONNECT"<<std::endl);
1608                 disconnect();
1609                 return;
1610         case CONNCMD_DISCONNECT_PEER:
1611                 LOG(dout_con<<m_connection->getDesc()
1612                                 <<" UDP processing CONNCMD_DISCONNECT_PEER"<<std::endl);
1613                 disconnect_peer(c.peer_id);
1614                 return;
1615         case CONNCMD_SEND:
1616                 LOG(dout_con<<m_connection->getDesc()
1617                                 <<" UDP processing CONNCMD_SEND"<<std::endl);
1618                 send(c.peer_id, c.channelnum, c.data);
1619                 return;
1620         case CONNCMD_SEND_TO_ALL:
1621                 LOG(dout_con<<m_connection->getDesc()
1622                                 <<" UDP processing CONNCMD_SEND_TO_ALL"<<std::endl);
1623                 sendToAll(c.channelnum, c.data);
1624                 return;
1625         case CONCMD_ACK:
1626                 LOG(dout_con<<m_connection->getDesc()
1627                                 <<" UDP processing CONCMD_ACK"<<std::endl);
1628                 sendAsPacket(c.peer_id,c.channelnum,c.data,true);
1629                 return;
1630         case CONCMD_CREATE_PEER:
1631                 FATAL_ERROR("Got command that should be reliable as unreliable command");
1632         default:
1633                 LOG(dout_con<<m_connection->getDesc()
1634                                 <<" Invalid command type: " << c.type <<std::endl);
1635         }
1636 }
1637
1638 void ConnectionSendThread::serve(Address bind_address)
1639 {
1640         LOG(dout_con<<m_connection->getDesc()
1641                         <<"UDP serving at port " << bind_address.serializeString() <<std::endl);
1642         try{
1643                 m_connection->m_udpSocket.Bind(bind_address);
1644                 m_connection->SetPeerID(PEER_ID_SERVER);
1645         }
1646         catch(SocketException &e) {
1647                 // Create event
1648                 ConnectionEvent ce;
1649                 ce.bindFailed();
1650                 m_connection->putEvent(ce);
1651         }
1652 }
1653
1654 void ConnectionSendThread::connect(Address address)
1655 {
1656         LOG(dout_con<<m_connection->getDesc()<<" connecting to "<<address.serializeString()
1657                         <<":"<<address.getPort()<<std::endl);
1658
1659         UDPPeer *peer = m_connection->createServerPeer(address);
1660
1661         // Create event
1662         ConnectionEvent e;
1663         e.peerAdded(peer->id, peer->address);
1664         m_connection->putEvent(e);
1665
1666         Address bind_addr;
1667
1668         if (address.isIPv6())
1669                 bind_addr.setAddress((IPv6AddressBytes*) NULL);
1670         else
1671                 bind_addr.setAddress(0,0,0,0);
1672
1673         m_connection->m_udpSocket.Bind(bind_addr);
1674
1675         // Send a dummy packet to server with peer_id = PEER_ID_INEXISTENT
1676         m_connection->SetPeerID(PEER_ID_INEXISTENT);
1677         NetworkPacket pkt(0,0);
1678         m_connection->Send(PEER_ID_SERVER, 0, &pkt, true);
1679 }
1680
1681 void ConnectionSendThread::disconnect()
1682 {
1683         LOG(dout_con<<m_connection->getDesc()<<" disconnecting"<<std::endl);
1684
1685         // Create and send DISCO packet
1686         SharedBuffer<u8> data(2);
1687         writeU8(&data[0], TYPE_CONTROL);
1688         writeU8(&data[1], CONTROLTYPE_DISCO);
1689
1690
1691         // Send to all
1692         std::list<u16> peerids = m_connection->getPeerIDs();
1693
1694         for (u16 peerid : peerids) {
1695                 sendAsPacket(peerid, 0,data,false);
1696         }
1697 }
1698
1699 void ConnectionSendThread::disconnect_peer(u16 peer_id)
1700 {
1701         LOG(dout_con<<m_connection->getDesc()<<" disconnecting peer"<<std::endl);
1702
1703         // Create and send DISCO packet
1704         SharedBuffer<u8> data(2);
1705         writeU8(&data[0], TYPE_CONTROL);
1706         writeU8(&data[1], CONTROLTYPE_DISCO);
1707         sendAsPacket(peer_id, 0,data,false);
1708
1709         PeerHelper peer = m_connection->getPeerNoEx(peer_id);
1710
1711         if (!peer)
1712                 return;
1713
1714         if (dynamic_cast<UDPPeer*>(&peer) == 0)
1715         {
1716                 return;
1717         }
1718
1719         dynamic_cast<UDPPeer*>(&peer)->m_pending_disconnect = true;
1720 }
1721
1722 void ConnectionSendThread::send(u16 peer_id, u8 channelnum,
1723                 SharedBuffer<u8> data)
1724 {
1725         assert(channelnum < CHANNEL_COUNT); // Pre-condition
1726
1727         PeerHelper peer = m_connection->getPeerNoEx(peer_id);
1728         if (!peer)
1729         {
1730                 LOG(dout_con<<m_connection->getDesc()<<" peer: peer_id="<<peer_id
1731                                 << ">>>NOT<<< found on sending packet"
1732                                 << ", channel " << (channelnum % 0xFF)
1733                                 << ", size: " << data.getSize() <<std::endl);
1734                 return;
1735         }
1736
1737         LOG(dout_con<<m_connection->getDesc()<<" sending to peer_id="<<peer_id
1738                         << ", channel " << (channelnum % 0xFF)
1739                         << ", size: " << data.getSize() <<std::endl);
1740
1741         u16 split_sequence_number = peer->getNextSplitSequenceNumber(channelnum);
1742
1743         u32 chunksize_max = m_max_packet_size - BASE_HEADER_SIZE;
1744         std::list<SharedBuffer<u8> > originals;
1745
1746         originals = makeAutoSplitPacket(data, chunksize_max,split_sequence_number);
1747
1748         peer->setNextSplitSequenceNumber(channelnum,split_sequence_number);
1749
1750         for (const SharedBuffer<u8> &original : originals) {
1751                 sendAsPacket(peer_id, channelnum, original);
1752         }
1753 }
1754
1755 void ConnectionSendThread::sendReliable(ConnectionCommand &c)
1756 {
1757         PeerHelper peer = m_connection->getPeerNoEx(c.peer_id);
1758         if (!peer)
1759                 return;
1760
1761         peer->PutReliableSendCommand(c,m_max_packet_size);
1762 }
1763
1764 void ConnectionSendThread::sendToAll(u8 channelnum, SharedBuffer<u8> data)
1765 {
1766         std::list<u16> peerids = m_connection->getPeerIDs();
1767
1768         for (u16 peerid : peerids) {
1769                 send(peerid, channelnum, data);
1770         }
1771 }
1772
1773 void ConnectionSendThread::sendToAllReliable(ConnectionCommand &c)
1774 {
1775         std::list<u16> peerids = m_connection->getPeerIDs();
1776
1777         for (u16 peerid : peerids) {
1778                 PeerHelper peer = m_connection->getPeerNoEx(peerid);
1779
1780                 if (!peer)
1781                         continue;
1782
1783                 peer->PutReliableSendCommand(c,m_max_packet_size);
1784         }
1785 }
1786
1787 void ConnectionSendThread::sendPackets(float dtime)
1788 {
1789         std::list<u16> peerIds = m_connection->getPeerIDs();
1790         std::list<u16> pendingDisconnect;
1791         std::map<u16,bool> pending_unreliable;
1792
1793         for (u16 peerId : peerIds) {
1794                 PeerHelper peer = m_connection->getPeerNoEx(peerId);
1795                 //peer may have been removed
1796                 if (!peer) {
1797                         LOG(dout_con<<m_connection->getDesc()<< " Peer not found: peer_id=" << peerId
1798                                 << std::endl);
1799                         continue;
1800                 }
1801                 peer->m_increment_packets_remaining = m_iteration_packets_avaialble/m_connection->m_peers.size();
1802
1803                 UDPPeer *udpPeer = dynamic_cast<UDPPeer*>(&peer);
1804
1805                 if (!udpPeer) {
1806                         continue;
1807                 }
1808
1809                 if (udpPeer->m_pending_disconnect) {
1810                         pendingDisconnect.push_back(peerId);
1811                 }
1812
1813                 PROFILE(std::stringstream peerIdentifier);
1814                 PROFILE(peerIdentifier << "sendPackets[" << m_connection->getDesc() << ";" << peerId
1815                         << ";RELIABLE]");
1816                 PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier.str(), SPT_AVG));
1817
1818                 LOG(dout_con<<m_connection->getDesc()
1819                                 << " Handle per peer queues: peer_id=" << peerId
1820                         << " packet quota: " << peer->m_increment_packets_remaining << std::endl);
1821
1822                 // first send queued reliable packets for all peers (if possible)
1823                 for (unsigned int i=0; i < CHANNEL_COUNT; i++) {
1824                         Channel &channel = udpPeer->channels[i];
1825                         u16 next_to_ack = 0;
1826
1827                         channel.outgoing_reliables_sent.getFirstSeqnum(next_to_ack);
1828                         u16 next_to_receive = 0;
1829                         channel.incoming_reliables.getFirstSeqnum(next_to_receive);
1830
1831                         LOG(dout_con<<m_connection->getDesc()<< "\t channel: "
1832                                                 << i << ", peer quota:"
1833                                                 << peer->m_increment_packets_remaining
1834                                                 << std::endl
1835                                         << "\t\t\treliables on wire: "
1836                                                 << channel.outgoing_reliables_sent.size()
1837                                                 << ", waiting for ack for " << next_to_ack
1838                                                 << std::endl
1839                                         << "\t\t\tincoming_reliables: "
1840                                                 << channel.incoming_reliables.size()
1841                                                 << ", next reliable packet: "
1842                                                 << channel.readNextIncomingSeqNum()
1843                                                 << ", next queued: " << next_to_receive
1844                                                 << std::endl
1845                                         << "\t\t\treliables queued : "
1846                                                 << channel.queued_reliables.size()
1847                                                 << std::endl
1848                                         << "\t\t\tqueued commands  : "
1849                                                 << channel.queued_commands.size()
1850                                                 << std::endl);
1851
1852                         while ((!channel.queued_reliables.empty()) &&
1853                                         (channel.outgoing_reliables_sent.size()
1854                                                         < channel.getWindowSize())&&
1855                                                         (peer->m_increment_packets_remaining > 0))
1856                         {
1857                                 BufferedPacket p = channel.queued_reliables.front();
1858                                 channel.queued_reliables.pop();
1859                                 LOG(dout_con<<m_connection->getDesc()
1860                                                 <<" INFO: sending a queued reliable packet "
1861                                                 <<" channel: " << i
1862                                                 <<", seqnum: " << readU16(&p.data[BASE_HEADER_SIZE+1])
1863                                                 << std::endl);
1864                                 sendAsPacketReliable(p, &channel);
1865                                 peer->m_increment_packets_remaining--;
1866                         }
1867                 }
1868         }
1869
1870         if (!m_outgoing_queue.empty()) {
1871                 LOG(dout_con<<m_connection->getDesc()
1872                                 << " Handle non reliable queue ("
1873                                 << m_outgoing_queue.size() << " pkts)" << std::endl);
1874         }
1875
1876         unsigned int initial_queuesize = m_outgoing_queue.size();
1877         /* send non reliable packets*/
1878         for(unsigned int i=0;i < initial_queuesize;i++) {
1879                 OutgoingPacket packet = m_outgoing_queue.front();
1880                 m_outgoing_queue.pop();
1881
1882                 if (packet.reliable)
1883                         continue;
1884
1885                 PeerHelper peer = m_connection->getPeerNoEx(packet.peer_id);
1886                 if (!peer) {
1887                         LOG(dout_con<<m_connection->getDesc()
1888                                                         <<" Outgoing queue: peer_id="<<packet.peer_id
1889                                                         << ">>>NOT<<< found on sending packet"
1890                                                         << ", channel " << (packet.channelnum % 0xFF)
1891                                                         << ", size: " << packet.data.getSize() <<std::endl);
1892                         continue;
1893                 }
1894
1895                 /* send acks immediately */
1896                 if (packet.ack) {
1897                         rawSendAsPacket(packet.peer_id, packet.channelnum,
1898                                                                 packet.data, packet.reliable);
1899                         peer->m_increment_packets_remaining =
1900                                         MYMIN(0,peer->m_increment_packets_remaining--);
1901                 }
1902                 else if (
1903                         ( peer->m_increment_packets_remaining > 0) ||
1904                         (stopRequested())) {
1905                         rawSendAsPacket(packet.peer_id, packet.channelnum,
1906                                         packet.data, packet.reliable);
1907                         peer->m_increment_packets_remaining--;
1908                 }
1909                 else {
1910                         m_outgoing_queue.push(packet);
1911                         pending_unreliable[packet.peer_id] = true;
1912                 }
1913         }
1914
1915         for (u16 peerId : pendingDisconnect) {
1916                 if (!pending_unreliable[peerId])
1917                 {
1918                         m_connection->deletePeer(peerId,false);
1919                 }
1920         }
1921 }
1922
1923 void ConnectionSendThread::sendAsPacket(u16 peer_id, u8 channelnum,
1924                 SharedBuffer<u8> data, bool ack)
1925 {
1926         OutgoingPacket packet(peer_id, channelnum, data, false, ack);
1927         m_outgoing_queue.push(packet);
1928 }
1929
1930 ConnectionReceiveThread::ConnectionReceiveThread(unsigned int max_packet_size) :
1931         Thread("ConnectionReceive")
1932 {
1933 }
1934
1935 void * ConnectionReceiveThread::run()
1936 {
1937         assert(m_connection);
1938
1939         LOG(dout_con<<m_connection->getDesc()
1940                         <<"ConnectionReceive thread started"<<std::endl);
1941
1942         PROFILE(std::stringstream ThreadIdentifier);
1943         PROFILE(ThreadIdentifier << "ConnectionReceive: [" << m_connection->getDesc() << "]");
1944
1945 #ifdef DEBUG_CONNECTION_KBPS
1946         u64 curtime = porting::getTimeMs();
1947         u64 lasttime = curtime;
1948         float debug_print_timer = 0.0;
1949 #endif
1950
1951         while(!stopRequested()) {
1952                 BEGIN_DEBUG_EXCEPTION_HANDLER
1953                 PROFILE(ScopeProfiler sp(g_profiler, ThreadIdentifier.str(), SPT_AVG));
1954
1955 #ifdef DEBUG_CONNECTION_KBPS
1956                 lasttime = curtime;
1957                 curtime = porting::getTimeMs();
1958                 float dtime = CALC_DTIME(lasttime,curtime);
1959 #endif
1960
1961                 /* receive packets */
1962                 receive();
1963
1964 #ifdef DEBUG_CONNECTION_KBPS
1965                 debug_print_timer += dtime;
1966                 if (debug_print_timer > 20.0) {
1967                         debug_print_timer -= 20.0;
1968
1969                         std::list<u16> peerids = m_connection->getPeerIDs();
1970
1971                         for (std::list<u16>::iterator i = peerids.begin();
1972                                         i != peerids.end();
1973                                         i++)
1974                         {
1975                                 PeerHelper peer = m_connection->getPeerNoEx(*i);
1976                                 if (!peer)
1977                                         continue;
1978
1979                                 float peer_current = 0.0;
1980                                 float peer_loss = 0.0;
1981                                 float avg_rate = 0.0;
1982                                 float avg_loss = 0.0;
1983
1984                                 for(u16 j=0; j<CHANNEL_COUNT; j++)
1985                                 {
1986                                         peer_current +=peer->channels[j].getCurrentDownloadRateKB();
1987                                         peer_loss += peer->channels[j].getCurrentLossRateKB();
1988                                         avg_rate += peer->channels[j].getAvgDownloadRateKB();
1989                                         avg_loss += peer->channels[j].getAvgLossRateKB();
1990                                 }
1991
1992                                 std::stringstream output;
1993                                 output << std::fixed << std::setprecision(1);
1994                                 output << "OUT to Peer " << *i << " RATES (good / loss) " << std::endl;
1995                                 output << "\tcurrent (sum): " << peer_current << "kb/s "<< peer_loss << "kb/s" << std::endl;
1996                                 output << "\taverage (sum): " << avg_rate << "kb/s "<< avg_loss << "kb/s" << std::endl;
1997                                 output << std::setfill(' ');
1998                                 for(u16 j=0; j<CHANNEL_COUNT; j++)
1999                                 {
2000                                         output << "\tcha " << j << ":"
2001                                                 << " CUR: " << std::setw(6) << peer->channels[j].getCurrentDownloadRateKB() <<"kb/s"
2002                                                 << " AVG: " << std::setw(6) << peer->channels[j].getAvgDownloadRateKB() <<"kb/s"
2003                                                 << " MAX: " << std::setw(6) << peer->channels[j].getMaxDownloadRateKB() <<"kb/s"
2004                                                 << " /"
2005                                                 << " CUR: " << std::setw(6) << peer->channels[j].getCurrentLossRateKB() <<"kb/s"
2006                                                 << " AVG: " << std::setw(6) << peer->channels[j].getAvgLossRateKB() <<"kb/s"
2007                                                 << " MAX: " << std::setw(6) << peer->channels[j].getMaxLossRateKB() <<"kb/s"
2008                                                 << " / WS: " << peer->channels[j].getWindowSize()
2009                                                 << std::endl;
2010                                 }
2011
2012                                 fprintf(stderr,"%s\n",output.str().c_str());
2013                         }
2014                 }
2015 #endif
2016                 END_DEBUG_EXCEPTION_HANDLER
2017         }
2018
2019         PROFILE(g_profiler->remove(ThreadIdentifier.str()));
2020         return NULL;
2021 }
2022
2023 // Receive packets from the network and buffers and create ConnectionEvents
2024 void ConnectionReceiveThread::receive()
2025 {
2026         // use IPv6 minimum allowed MTU as receive buffer size as this is
2027         // theoretical reliable upper boundary of a udp packet for all IPv6 enabled
2028         // infrastructure
2029         unsigned int packet_maxsize = 1500;
2030         SharedBuffer<u8> packetdata(packet_maxsize);
2031
2032         bool packet_queued = true;
2033
2034         unsigned int loop_count = 0;
2035
2036         /* first of all read packets from socket */
2037         /* check for incoming data available */
2038         while( (loop_count < 10) &&
2039                         (m_connection->m_udpSocket.WaitData(50))) {
2040                 loop_count++;
2041                 try {
2042                         if (packet_queued) {
2043                                 bool data_left = true;
2044                                 u16 peer_id;
2045                                 SharedBuffer<u8> resultdata;
2046                                 while(data_left) {
2047                                         try {
2048                                                 data_left = getFromBuffers(peer_id, resultdata);
2049                                                 if (data_left) {
2050                                                         ConnectionEvent e;
2051                                                         e.dataReceived(peer_id, resultdata);
2052                                                         m_connection->putEvent(e);
2053                                                 }
2054                                         }
2055                                         catch(ProcessedSilentlyException &e) {
2056                                                 /* try reading again */
2057                                         }
2058                                 }
2059                                 packet_queued = false;
2060                         }
2061
2062                         Address sender;
2063                         s32 received_size = m_connection->m_udpSocket.Receive(sender, *packetdata, packet_maxsize);
2064
2065                         if ((received_size < BASE_HEADER_SIZE) ||
2066                                 (readU32(&packetdata[0]) != m_connection->GetProtocolID()))
2067                         {
2068                                 LOG(derr_con<<m_connection->getDesc()
2069                                                 <<"Receive(): Invalid incoming packet, "
2070                                                 <<"size: " << received_size
2071                                                 <<", protocol: "
2072                                                 << ((received_size >= 4) ? readU32(&packetdata[0]) : -1)
2073                                                 << std::endl);
2074                                 continue;
2075                         }
2076
2077                         u16 peer_id          = readPeerId(*packetdata);
2078                         u8 channelnum        = readChannel(*packetdata);
2079
2080                         if (channelnum > CHANNEL_COUNT-1) {
2081                                 LOG(derr_con<<m_connection->getDesc()
2082                                                 <<"Receive(): Invalid channel "<<channelnum<<std::endl);
2083                                 throw InvalidIncomingDataException("Channel doesn't exist");
2084                         }
2085
2086                         /* Try to identify peer by sender address (may happen on join) */
2087                         if (peer_id == PEER_ID_INEXISTENT) {
2088                                 peer_id = m_connection->lookupPeer(sender);
2089                                 // We do not have to remind the peer of its
2090                                 // peer id as the CONTROLTYPE_SET_PEER_ID
2091                                 // command was sent reliably.
2092                         }
2093
2094                         /* The peer was not found in our lists. Add it. */
2095                         if (peer_id == PEER_ID_INEXISTENT) {
2096                                 peer_id = m_connection->createPeer(sender, MTP_MINETEST_RELIABLE_UDP, 0);
2097                         }
2098
2099                         PeerHelper peer = m_connection->getPeerNoEx(peer_id);
2100
2101                         if (!peer) {
2102                                 LOG(dout_con<<m_connection->getDesc()
2103                                                 <<" got packet from unknown peer_id: "
2104                                                 <<peer_id<<" Ignoring."<<std::endl);
2105                                 continue;
2106                         }
2107
2108                         // Validate peer address
2109
2110                         Address peer_address;
2111
2112                         if (peer->getAddress(MTP_UDP, peer_address)) {
2113                                 if (peer_address != sender) {
2114                                         LOG(derr_con<<m_connection->getDesc()
2115                                                         <<m_connection->getDesc()
2116                                                         <<" Peer "<<peer_id<<" sending from different address."
2117                                                         " Ignoring."<<std::endl);
2118                                         continue;
2119                                 }
2120                         }
2121                         else {
2122
2123                                 bool invalid_address = true;
2124                                 if (invalid_address) {
2125                                         LOG(derr_con<<m_connection->getDesc()
2126                                                         <<m_connection->getDesc()
2127                                                         <<" Peer "<<peer_id<<" unknown."
2128                                                         " Ignoring."<<std::endl);
2129                                         continue;
2130                                 }
2131                         }
2132
2133                         peer->ResetTimeout();
2134
2135                         Channel *channel = 0;
2136
2137                         if (dynamic_cast<UDPPeer*>(&peer) != 0)
2138                         {
2139                                 channel = &(dynamic_cast<UDPPeer*>(&peer)->channels[channelnum]);
2140                         }
2141
2142                         if (channel != 0) {
2143                                 channel->UpdateBytesReceived(received_size);
2144                         }
2145
2146                         // Throw the received packet to channel->processPacket()
2147
2148                         // Make a new SharedBuffer from the data without the base headers
2149                         SharedBuffer<u8> strippeddata(received_size - BASE_HEADER_SIZE);
2150                         memcpy(*strippeddata, &packetdata[BASE_HEADER_SIZE],
2151                                         strippeddata.getSize());
2152
2153                         try{
2154                                 // Process it (the result is some data with no headers made by us)
2155                                 SharedBuffer<u8> resultdata = processPacket
2156                                                 (channel, strippeddata, peer_id, channelnum, false);
2157
2158                                 LOG(dout_con<<m_connection->getDesc()
2159                                                 <<" ProcessPacket from peer_id: " << peer_id
2160                                                 << ",channel: " << (channelnum & 0xFF) << ", returned "
2161                                                 << resultdata.getSize() << " bytes" <<std::endl);
2162
2163                                 ConnectionEvent e;
2164                                 e.dataReceived(peer_id, resultdata);
2165                                 m_connection->putEvent(e);
2166                         }
2167                         catch(ProcessedSilentlyException &e) {
2168                         }
2169                         catch(ProcessedQueued &e) {
2170                                 packet_queued = true;
2171                         }
2172                 }
2173                 catch(InvalidIncomingDataException &e) {
2174                 }
2175                 catch(ProcessedSilentlyException &e) {
2176                 }
2177         }
2178 }
2179
2180 bool ConnectionReceiveThread::getFromBuffers(u16 &peer_id, SharedBuffer<u8> &dst)
2181 {
2182         std::list<u16> peerids = m_connection->getPeerIDs();
2183
2184         for (u16 peerid : peerids) {
2185                 PeerHelper peer = m_connection->getPeerNoEx(peerid);
2186                 if (!peer)
2187                         continue;
2188
2189                 if (dynamic_cast<UDPPeer*>(&peer) == 0)
2190                         continue;
2191
2192                 for (Channel &channel : (dynamic_cast<UDPPeer *>(&peer))->channels) {
2193                         if (checkIncomingBuffers(&channel, peer_id, dst)) {
2194                                 return true;
2195                         }
2196                 }
2197         }
2198         return false;
2199 }
2200
2201 bool ConnectionReceiveThread::checkIncomingBuffers(Channel *channel,
2202                 u16 &peer_id, SharedBuffer<u8> &dst)
2203 {
2204         u16 firstseqnum = 0;
2205         if (channel->incoming_reliables.getFirstSeqnum(firstseqnum))
2206         {
2207                 if (firstseqnum == channel->readNextIncomingSeqNum())
2208                 {
2209                         BufferedPacket p = channel->incoming_reliables.popFirst();
2210                         peer_id = readPeerId(*p.data);
2211                         u8 channelnum = readChannel(*p.data);
2212                         u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]);
2213
2214                         LOG(dout_con<<m_connection->getDesc()
2215                                         <<"UNBUFFERING TYPE_RELIABLE"
2216                                         <<" seqnum="<<seqnum
2217                                         <<" peer_id="<<peer_id
2218                                         <<" channel="<<((int)channelnum&0xff)
2219                                         <<std::endl);
2220
2221                         channel->incNextIncomingSeqNum();
2222
2223                         u32 headers_size = BASE_HEADER_SIZE + RELIABLE_HEADER_SIZE;
2224                         // Get out the inside packet and re-process it
2225                         SharedBuffer<u8> payload(p.data.getSize() - headers_size);
2226                         memcpy(*payload, &p.data[headers_size], payload.getSize());
2227
2228                         dst = processPacket(channel, payload, peer_id, channelnum, true);
2229                         return true;
2230                 }
2231         }
2232         return false;
2233 }
2234
2235 SharedBuffer<u8> ConnectionReceiveThread::processPacket(Channel *channel,
2236                 SharedBuffer<u8> packetdata, u16 peer_id, u8 channelnum, bool reliable)
2237 {
2238         PeerHelper peer = m_connection->getPeerNoEx(peer_id);
2239
2240         if (!peer) {
2241                 errorstream << "Peer not found (possible timeout)" << std::endl;
2242                 throw ProcessedSilentlyException("Peer not found (possible timeout)");
2243         }
2244
2245         if (packetdata.getSize() < 1)
2246                 throw InvalidIncomingDataException("packetdata.getSize() < 1");
2247
2248         u8 type = readU8(&(packetdata[0]));
2249
2250         if (MAX_UDP_PEERS <= 65535 && peer_id >= MAX_UDP_PEERS) {
2251                 std::string errmsg = "Invalid peer_id=" + itos(peer_id);
2252                 errorstream << errmsg << std::endl;
2253                 throw InvalidIncomingDataException(errmsg.c_str());
2254         }
2255
2256         if (type == TYPE_CONTROL)
2257         {
2258                 if (packetdata.getSize() < 2)
2259                         throw InvalidIncomingDataException("packetdata.getSize() < 2");
2260
2261                 u8 controltype = readU8(&(packetdata[1]));
2262
2263                 if (controltype == CONTROLTYPE_ACK)
2264                 {
2265                         assert(channel != NULL);
2266
2267                         if (packetdata.getSize() < 4) {
2268                                 throw InvalidIncomingDataException(
2269                                         "packetdata.getSize() < 4 (ACK header size)");
2270                         }
2271
2272                         u16 seqnum = readU16(&packetdata[2]);
2273                         LOG(dout_con<<m_connection->getDesc()
2274                                         <<" [ CONTROLTYPE_ACK: channelnum="
2275                                         <<((int)channelnum&0xff)<<", peer_id="<<peer_id
2276                                         <<", seqnum="<<seqnum<< " ]"<<std::endl);
2277
2278                         try{
2279                                 BufferedPacket p =
2280                                                 channel->outgoing_reliables_sent.popSeqnum(seqnum);
2281
2282                                 // only calculate rtt from straight sent packets
2283                                 if (p.resend_count == 0) {
2284                                         // Get round trip time
2285                                         u64 current_time = porting::getTimeMs();
2286
2287                                         // a overflow is quite unlikely but as it'd result in major
2288                                         // rtt miscalculation we handle it here
2289                                         if (current_time > p.absolute_send_time)
2290                                         {
2291                                                 float rtt = (current_time - p.absolute_send_time) / 1000.0;
2292
2293                                                 // Let peer calculate stuff according to it
2294                                                 // (avg_rtt and resend_timeout)
2295                                                 dynamic_cast<UDPPeer*>(&peer)->reportRTT(rtt);
2296                                         }
2297                                         else if (p.totaltime > 0)
2298                                         {
2299                                                 float rtt = p.totaltime;
2300
2301                                                 // Let peer calculate stuff according to it
2302                                                 // (avg_rtt and resend_timeout)
2303                                                 dynamic_cast<UDPPeer*>(&peer)->reportRTT(rtt);
2304                                         }
2305                                 }
2306                                 //put bytes for max bandwidth calculation
2307                                 channel->UpdateBytesSent(p.data.getSize(),1);
2308                                 if (channel->outgoing_reliables_sent.size() == 0)
2309                                 {
2310                                         m_connection->TriggerSend();
2311                                 }
2312                         }
2313                         catch(NotFoundException &e) {
2314                                 LOG(derr_con<<m_connection->getDesc()
2315                                                 <<"WARNING: ACKed packet not "
2316                                                 "in outgoing queue"
2317                                                 <<std::endl);
2318                                 channel->UpdatePacketTooLateCounter();
2319                         }
2320                         throw ProcessedSilentlyException("Got an ACK");
2321                 }
2322                 else if (controltype == CONTROLTYPE_SET_PEER_ID) {
2323                         // Got a packet to set our peer id
2324                         if (packetdata.getSize() < 4)
2325                                 throw InvalidIncomingDataException
2326                                                 ("packetdata.getSize() < 4 (SET_PEER_ID header size)");
2327                         u16 peer_id_new = readU16(&packetdata[2]);
2328                         LOG(dout_con<<m_connection->getDesc()
2329                                         <<"Got new peer id: "<<peer_id_new<<"... "<<std::endl);
2330
2331                         if (m_connection->GetPeerID() != PEER_ID_INEXISTENT)
2332                         {
2333                                 LOG(derr_con<<m_connection->getDesc()
2334                                                 <<"WARNING: Not changing"
2335                                                 " existing peer id."<<std::endl);
2336                         }
2337                         else
2338                         {
2339                                 LOG(dout_con<<m_connection->getDesc()<<"changing own peer id"<<std::endl);
2340                                 m_connection->SetPeerID(peer_id_new);
2341                         }
2342
2343                         ConnectionCommand cmd;
2344
2345                         SharedBuffer<u8> reply(2);
2346                         writeU8(&reply[0], TYPE_CONTROL);
2347                         writeU8(&reply[1], CONTROLTYPE_ENABLE_BIG_SEND_WINDOW);
2348                         cmd.disableLegacy(PEER_ID_SERVER,reply);
2349                         m_connection->putCommand(cmd);
2350
2351                         throw ProcessedSilentlyException("Got a SET_PEER_ID");
2352                 }
2353                 else if (controltype == CONTROLTYPE_PING)
2354                 {
2355                         // Just ignore it, the incoming data already reset
2356                         // the timeout counter
2357                         LOG(dout_con<<m_connection->getDesc()<<"PING"<<std::endl);
2358                         throw ProcessedSilentlyException("Got a PING");
2359                 }
2360                 else if (controltype == CONTROLTYPE_DISCO)
2361                 {
2362                         // Just ignore it, the incoming data already reset
2363                         // the timeout counter
2364                         LOG(dout_con<<m_connection->getDesc()
2365                                         <<"DISCO: Removing peer "<<(peer_id)<<std::endl);
2366
2367                         if (!m_connection->deletePeer(peer_id, false)) {
2368                                 derr_con<<m_connection->getDesc()
2369                                                 <<"DISCO: Peer not found"<<std::endl;
2370                         }
2371
2372                         throw ProcessedSilentlyException("Got a DISCO");
2373                 }
2374                 else if (controltype == CONTROLTYPE_ENABLE_BIG_SEND_WINDOW)
2375                 {
2376                         dynamic_cast<UDPPeer*>(&peer)->setNonLegacyPeer();
2377                         throw ProcessedSilentlyException("Got non legacy control");
2378                 }
2379                 else{
2380                         LOG(derr_con<<m_connection->getDesc()
2381                                         <<"INVALID TYPE_CONTROL: invalid controltype="
2382                                         <<((int)controltype&0xff)<<std::endl);
2383                         throw InvalidIncomingDataException("Invalid control type");
2384                 }
2385         }
2386         else if (type == TYPE_ORIGINAL)
2387         {
2388                 if (packetdata.getSize() <= ORIGINAL_HEADER_SIZE)
2389                         throw InvalidIncomingDataException
2390                                         ("packetdata.getSize() <= ORIGINAL_HEADER_SIZE");
2391                 LOG(dout_con<<m_connection->getDesc()
2392                                 <<"RETURNING TYPE_ORIGINAL to user"
2393                                 <<std::endl);
2394                 // Get the inside packet out and return it
2395                 SharedBuffer<u8> payload(packetdata.getSize() - ORIGINAL_HEADER_SIZE);
2396                 memcpy(*payload, &(packetdata[ORIGINAL_HEADER_SIZE]), payload.getSize());
2397                 return payload;
2398         }
2399         else if (type == TYPE_SPLIT)
2400         {
2401                 Address peer_address;
2402
2403                 if (peer->getAddress(MTP_UDP, peer_address)) {
2404
2405                         // We have to create a packet again for buffering
2406                         // This isn't actually too bad an idea.
2407                         BufferedPacket packet = makePacket(
2408                                         peer_address,
2409                                         packetdata,
2410                                         m_connection->GetProtocolID(),
2411                                         peer_id,
2412                                         channelnum);
2413
2414                         // Buffer the packet
2415                         SharedBuffer<u8> data =
2416                                         peer->addSpiltPacket(channelnum,packet,reliable);
2417
2418                         if (data.getSize() != 0)
2419                         {
2420                                 LOG(dout_con<<m_connection->getDesc()
2421                                                 <<"RETURNING TYPE_SPLIT: Constructed full data, "
2422                                                 <<"size="<<data.getSize()<<std::endl);
2423                                 return data;
2424                         }
2425                         LOG(dout_con<<m_connection->getDesc()<<"BUFFERED TYPE_SPLIT"<<std::endl);
2426                         throw ProcessedSilentlyException("Buffered a split packet chunk");
2427                 }
2428                 else {
2429                         //TODO throw some error
2430                 }
2431         }
2432         else if (type == TYPE_RELIABLE)
2433         {
2434                 assert(channel != NULL);
2435
2436                 // Recursive reliable packets not allowed
2437                 if (reliable)
2438                         throw InvalidIncomingDataException("Found nested reliable packets");
2439
2440                 if (packetdata.getSize() < RELIABLE_HEADER_SIZE)
2441                         throw InvalidIncomingDataException
2442                                         ("packetdata.getSize() < RELIABLE_HEADER_SIZE");
2443
2444                 u16 seqnum = readU16(&packetdata[1]);
2445                 bool is_future_packet = false;
2446                 bool is_old_packet = false;
2447
2448                 /* packet is within our receive window send ack */
2449                 if (seqnum_in_window(seqnum, channel->readNextIncomingSeqNum(),MAX_RELIABLE_WINDOW_SIZE))
2450                 {
2451                         m_connection->sendAck(peer_id,channelnum,seqnum);
2452                 }
2453                 else {
2454                         is_future_packet = seqnum_higher(seqnum, channel->readNextIncomingSeqNum());
2455                         is_old_packet    = seqnum_higher(channel->readNextIncomingSeqNum(), seqnum);
2456
2457
2458                         /* packet is not within receive window, don't send ack.           *
2459                          * if this was a valid packet it's gonna be retransmitted         */
2460                         if (is_future_packet)
2461                         {
2462                                 throw ProcessedSilentlyException("Received packet newer then expected, not sending ack");
2463                         }
2464
2465                         /* seems like our ack was lost, send another one for a old packet */
2466                         if (is_old_packet)
2467                         {
2468                                 LOG(dout_con<<m_connection->getDesc()
2469                                                 << "RE-SENDING ACK: peer_id: " << peer_id
2470                                                 << ", channel: " << (channelnum&0xFF)
2471                                                 << ", seqnum: " << seqnum << std::endl;)
2472                                 m_connection->sendAck(peer_id,channelnum,seqnum);
2473
2474                                 // we already have this packet so this one was on wire at least
2475                                 // the current timeout
2476                                 // we don't know how long this packet was on wire don't do silly guessing
2477                                 // dynamic_cast<UDPPeer*>(&peer)->reportRTT(dynamic_cast<UDPPeer*>(&peer)->getResendTimeout());
2478
2479                                 throw ProcessedSilentlyException("Retransmitting ack for old packet");
2480                         }
2481                 }
2482
2483                 if (seqnum != channel->readNextIncomingSeqNum())
2484                 {
2485                         Address peer_address;
2486
2487                         // this is a reliable packet so we have a udp address for sure
2488                         peer->getAddress(MTP_MINETEST_RELIABLE_UDP, peer_address);
2489                         // This one comes later, buffer it.
2490                         // Actually we have to make a packet to buffer one.
2491                         // Well, we have all the ingredients, so just do it.
2492                         BufferedPacket packet = con::makePacket(
2493                                         peer_address,
2494                                         packetdata,
2495                                         m_connection->GetProtocolID(),
2496                                         peer_id,
2497                                         channelnum);
2498                         try{
2499                                 channel->incoming_reliables.insert(packet,channel->readNextIncomingSeqNum());
2500
2501                                 LOG(dout_con<<m_connection->getDesc()
2502                                                 << "BUFFERING, TYPE_RELIABLE peer_id: " << peer_id
2503                                                 << ", channel: " << (channelnum&0xFF)
2504                                                 << ", seqnum: " << seqnum << std::endl;)
2505
2506                                 throw ProcessedQueued("Buffered future reliable packet");
2507                         }
2508                         catch(AlreadyExistsException &e)
2509                         {
2510                         }
2511                         catch(IncomingDataCorruption &e)
2512                         {
2513                                 ConnectionCommand discon;
2514                                 discon.disconnect_peer(peer_id);
2515                                 m_connection->putCommand(discon);
2516
2517                                 LOG(derr_con<<m_connection->getDesc()
2518                                                 << "INVALID, TYPE_RELIABLE peer_id: " << peer_id
2519                                                 << ", channel: " << (channelnum&0xFF)
2520                                                 << ", seqnum: " << seqnum
2521                                                 << "DROPPING CLIENT!" << std::endl;)
2522                         }
2523                 }
2524
2525                 /* we got a packet to process right now */
2526                 LOG(dout_con<<m_connection->getDesc()
2527                                 << "RECURSIVE, TYPE_RELIABLE peer_id: " << peer_id
2528                                 << ", channel: " << (channelnum&0xFF)
2529                                 << ", seqnum: " << seqnum << std::endl;)
2530
2531
2532                 /* check for resend case */
2533                 u16 queued_seqnum = 0;
2534                 if (channel->incoming_reliables.getFirstSeqnum(queued_seqnum))
2535                 {
2536                         if (queued_seqnum == seqnum)
2537                         {
2538                                 BufferedPacket queued_packet = channel->incoming_reliables.popFirst();
2539                                 /** TODO find a way to verify the new against the old packet */
2540                         }
2541                 }
2542
2543                 channel->incNextIncomingSeqNum();
2544
2545                 // Get out the inside packet and re-process it
2546                 SharedBuffer<u8> payload(packetdata.getSize() - RELIABLE_HEADER_SIZE);
2547                 memcpy(*payload, &packetdata[RELIABLE_HEADER_SIZE], payload.getSize());
2548
2549                 return processPacket(channel, payload, peer_id, channelnum, true);
2550         }
2551         else
2552         {
2553                 derr_con<<m_connection->getDesc()
2554                                 <<"Got invalid type="<<((int)type&0xff)<<std::endl;
2555                 throw InvalidIncomingDataException("Invalid packet type");
2556         }
2557
2558         // We should never get here.
2559         FATAL_ERROR("Invalid execution point");
2560 }
2561
2562 /*
2563         Connection
2564 */
2565
2566 Connection::Connection(u32 protocol_id, u32 max_packet_size, float timeout,
2567                 bool ipv6, PeerHandler *peerhandler) :
2568         m_udpSocket(ipv6),
2569         m_protocol_id(protocol_id),
2570         m_sendThread(max_packet_size, timeout),
2571         m_receiveThread(max_packet_size),
2572         m_bc_peerhandler(peerhandler)
2573
2574 {
2575         m_udpSocket.setTimeoutMs(5);
2576
2577         m_sendThread.setParent(this);
2578         m_receiveThread.setParent(this);
2579
2580         m_sendThread.start();
2581         m_receiveThread.start();
2582
2583 }
2584
2585
2586 Connection::~Connection()
2587 {
2588         m_shutting_down = true;
2589         // request threads to stop
2590         m_sendThread.stop();
2591         m_receiveThread.stop();
2592
2593         //TODO for some unkonwn reason send/receive threads do not exit as they're
2594         // supposed to be but wait on peer timeout. To speed up shutdown we reduce
2595         // timeout to half a second.
2596         m_sendThread.setPeerTimeout(0.5);
2597
2598         // wait for threads to finish
2599         m_sendThread.wait();
2600         m_receiveThread.wait();
2601
2602         // Delete peers
2603         for (auto &peer : m_peers) {
2604                 delete peer.second;
2605         }
2606 }
2607
2608 /* Internal stuff */
2609 void Connection::putEvent(ConnectionEvent &e)
2610 {
2611         assert(e.type != CONNEVENT_NONE); // Pre-condition
2612         m_event_queue.push_back(e);
2613 }
2614
2615 PeerHelper Connection::getPeer(u16 peer_id)
2616 {
2617         MutexAutoLock peerlock(m_peers_mutex);
2618         std::map<u16, Peer*>::iterator node = m_peers.find(peer_id);
2619
2620         if (node == m_peers.end()) {
2621                 throw PeerNotFoundException("GetPeer: Peer not found (possible timeout)");
2622         }
2623
2624         // Error checking
2625         FATAL_ERROR_IF(node->second->id != peer_id, "Invalid peer id");
2626
2627         return PeerHelper(node->second);
2628 }
2629
2630 PeerHelper Connection::getPeerNoEx(u16 peer_id)
2631 {
2632         MutexAutoLock peerlock(m_peers_mutex);
2633         std::map<u16, Peer*>::iterator node = m_peers.find(peer_id);
2634
2635         if (node == m_peers.end()) {
2636                 return PeerHelper(NULL);
2637         }
2638
2639         // Error checking
2640         FATAL_ERROR_IF(node->second->id != peer_id, "Invalid peer id");
2641
2642         return PeerHelper(node->second);
2643 }
2644
2645 /* find peer_id for address */
2646 u16 Connection::lookupPeer(Address& sender)
2647 {
2648         MutexAutoLock peerlock(m_peers_mutex);
2649         std::map<u16, Peer*>::iterator j;
2650         j = m_peers.begin();
2651         for(; j != m_peers.end(); ++j)
2652         {
2653                 Peer *peer = j->second;
2654                 if (peer->isPendingDeletion())
2655                         continue;
2656
2657                 Address tocheck;
2658
2659                 if ((peer->getAddress(MTP_MINETEST_RELIABLE_UDP, tocheck)) && (tocheck == sender))
2660                         return peer->id;
2661
2662                 if ((peer->getAddress(MTP_UDP, tocheck)) && (tocheck == sender))
2663                         return peer->id;
2664         }
2665
2666         return PEER_ID_INEXISTENT;
2667 }
2668
2669 std::list<Peer*> Connection::getPeers()
2670 {
2671         std::list<Peer*> list;
2672         for (auto &p : m_peers) {
2673                 Peer *peer = p.second;
2674                 list.push_back(peer);
2675         }
2676         return list;
2677 }
2678
2679 bool Connection::deletePeer(u16 peer_id, bool timeout)
2680 {
2681         Peer *peer = 0;
2682
2683         /* lock list as short as possible */
2684         {
2685                 MutexAutoLock peerlock(m_peers_mutex);
2686                 if (m_peers.find(peer_id) == m_peers.end())
2687                         return false;
2688                 peer = m_peers[peer_id];
2689                 m_peers.erase(peer_id);
2690                 m_peer_ids.remove(peer_id);
2691         }
2692
2693         Address peer_address;
2694         //any peer has a primary address this never fails!
2695         peer->getAddress(MTP_PRIMARY, peer_address);
2696         // Create event
2697         ConnectionEvent e;
2698         e.peerRemoved(peer_id, timeout, peer_address);
2699         putEvent(e);
2700
2701
2702         peer->Drop();
2703         return true;
2704 }
2705
2706 /* Interface */
2707
2708 ConnectionEvent Connection::waitEvent(u32 timeout_ms)
2709 {
2710         try {
2711                 return m_event_queue.pop_front(timeout_ms);
2712         } catch(ItemNotFoundException &ex) {
2713                 ConnectionEvent e;
2714                 e.type = CONNEVENT_NONE;
2715                 return e;
2716         }
2717 }
2718
2719 void Connection::putCommand(ConnectionCommand &c)
2720 {
2721         if (!m_shutting_down) {
2722                 m_command_queue.push_back(c);
2723                 m_sendThread.Trigger();
2724         }
2725 }
2726
2727 void Connection::Serve(Address bind_addr)
2728 {
2729         ConnectionCommand c;
2730         c.serve(bind_addr);
2731         putCommand(c);
2732 }
2733
2734 void Connection::Connect(Address address)
2735 {
2736         ConnectionCommand c;
2737         c.connect(address);
2738         putCommand(c);
2739 }
2740
2741 bool Connection::Connected()
2742 {
2743         MutexAutoLock peerlock(m_peers_mutex);
2744
2745         if (m_peers.size() != 1)
2746                 return false;
2747
2748         std::map<u16, Peer*>::iterator node = m_peers.find(PEER_ID_SERVER);
2749         if (node == m_peers.end())
2750                 return false;
2751
2752         if (m_peer_id == PEER_ID_INEXISTENT)
2753                 return false;
2754
2755         return true;
2756 }
2757
2758 void Connection::Disconnect()
2759 {
2760         ConnectionCommand c;
2761         c.disconnect();
2762         putCommand(c);
2763 }
2764
2765 void Connection::Receive(NetworkPacket* pkt)
2766 {
2767         for(;;) {
2768                 ConnectionEvent e = waitEvent(m_bc_receive_timeout);
2769                 if (e.type != CONNEVENT_NONE)
2770                         LOG(dout_con << getDesc() << ": Receive: got event: "
2771                                         << e.describe() << std::endl);
2772                 switch(e.type) {
2773                 case CONNEVENT_NONE:
2774                         throw NoIncomingDataException("No incoming data");
2775                 case CONNEVENT_DATA_RECEIVED:
2776                         // Data size is lesser than command size, ignoring packet
2777                         if (e.data.getSize() < 2) {
2778                                 continue;
2779                         }
2780
2781                         pkt->putRawPacket(*e.data, e.data.getSize(), e.peer_id);
2782                         return;
2783                 case CONNEVENT_PEER_ADDED: {
2784                         UDPPeer tmp(e.peer_id, e.address, this);
2785                         if (m_bc_peerhandler)
2786                                 m_bc_peerhandler->peerAdded(&tmp);
2787                         continue;
2788                 }
2789                 case CONNEVENT_PEER_REMOVED: {
2790                         UDPPeer tmp(e.peer_id, e.address, this);
2791                         if (m_bc_peerhandler)
2792                                 m_bc_peerhandler->deletingPeer(&tmp, e.timeout);
2793                         continue;
2794                 }
2795                 case CONNEVENT_BIND_FAILED:
2796                         throw ConnectionBindFailed("Failed to bind socket "
2797                                         "(port already in use?)");
2798                 }
2799         }
2800         throw NoIncomingDataException("No incoming data");
2801 }
2802
2803 void Connection::Send(u16 peer_id, u8 channelnum,
2804                 NetworkPacket* pkt, bool reliable)
2805 {
2806         assert(channelnum < CHANNEL_COUNT); // Pre-condition
2807
2808         ConnectionCommand c;
2809
2810         c.send(peer_id, channelnum, pkt, reliable);
2811         putCommand(c);
2812 }
2813
2814 Address Connection::GetPeerAddress(u16 peer_id)
2815 {
2816         PeerHelper peer = getPeerNoEx(peer_id);
2817
2818         if (!peer)
2819                 throw PeerNotFoundException("No address for peer found!");
2820         Address peer_address;
2821         peer->getAddress(MTP_PRIMARY, peer_address);
2822         return peer_address;
2823 }
2824
2825 float Connection::getPeerStat(u16 peer_id, rtt_stat_type type)
2826 {
2827         PeerHelper peer = getPeerNoEx(peer_id);
2828         if (!peer) return -1;
2829         return peer->getStat(type);
2830 }
2831
2832 float Connection::getLocalStat(rate_stat_type type)
2833 {
2834         PeerHelper peer = getPeerNoEx(PEER_ID_SERVER);
2835
2836         FATAL_ERROR_IF(!peer, "Connection::getLocalStat we couldn't get our own peer? are you serious???");
2837
2838         float retval = 0.0;
2839
2840         for (Channel &channel : dynamic_cast<UDPPeer *>(&peer)->channels) {
2841                 switch(type) {
2842                         case CUR_DL_RATE:
2843                                 retval += channel.getCurrentDownloadRateKB();
2844                                 break;
2845                         case AVG_DL_RATE:
2846                                 retval += channel.getAvgDownloadRateKB();
2847                                 break;
2848                         case CUR_INC_RATE:
2849                                 retval += channel.getCurrentIncomingRateKB();
2850                                 break;
2851                         case AVG_INC_RATE:
2852                                 retval += channel.getAvgIncomingRateKB();
2853                                 break;
2854                         case AVG_LOSS_RATE:
2855                                 retval += channel.getAvgLossRateKB();
2856                                 break;
2857                         case CUR_LOSS_RATE:
2858                                 retval += channel.getCurrentLossRateKB();
2859                                 break;
2860                 default:
2861                         FATAL_ERROR("Connection::getLocalStat Invalid stat type");
2862                 }
2863         }
2864         return retval;
2865 }
2866
2867 u16 Connection::createPeer(Address& sender, MTProtocols protocol, int fd)
2868 {
2869         // Somebody wants to make a new connection
2870
2871         // Get a unique peer id (2 or higher)
2872         u16 peer_id_new = m_next_remote_peer_id;
2873         u16 overflow =  MAX_UDP_PEERS;
2874
2875         /*
2876                 Find an unused peer id
2877         */
2878         MutexAutoLock lock(m_peers_mutex);
2879         bool out_of_ids = false;
2880         for(;;) {
2881                 // Check if exists
2882                 if (m_peers.find(peer_id_new) == m_peers.end())
2883
2884                         break;
2885                 // Check for overflow
2886                 if (peer_id_new == overflow) {
2887                         out_of_ids = true;
2888                         break;
2889                 }
2890                 peer_id_new++;
2891         }
2892
2893         if (out_of_ids) {
2894                 errorstream << getDesc() << " ran out of peer ids" << std::endl;
2895                 return PEER_ID_INEXISTENT;
2896         }
2897
2898         // Create a peer
2899         Peer *peer = 0;
2900         peer = new UDPPeer(peer_id_new, sender, this);
2901
2902         m_peers[peer->id] = peer;
2903         m_peer_ids.push_back(peer->id);
2904
2905         m_next_remote_peer_id = (peer_id_new +1 ) % MAX_UDP_PEERS;
2906
2907         LOG(dout_con << getDesc()
2908                         << "createPeer(): giving peer_id=" << peer_id_new << std::endl);
2909
2910         ConnectionCommand cmd;
2911         SharedBuffer<u8> reply(4);
2912         writeU8(&reply[0], TYPE_CONTROL);
2913         writeU8(&reply[1], CONTROLTYPE_SET_PEER_ID);
2914         writeU16(&reply[2], peer_id_new);
2915         cmd.createPeer(peer_id_new,reply);
2916         putCommand(cmd);
2917
2918         // Create peer addition event
2919         ConnectionEvent e;
2920         e.peerAdded(peer_id_new, sender);
2921         putEvent(e);
2922
2923         // We're now talking to a valid peer_id
2924         return peer_id_new;
2925 }
2926
2927 void Connection::PrintInfo(std::ostream &out)
2928 {
2929         m_info_mutex.lock();
2930         out<<getDesc()<<": ";
2931         m_info_mutex.unlock();
2932 }
2933
2934 void Connection::PrintInfo()
2935 {
2936         PrintInfo(dout_con);
2937 }
2938
2939 const std::string Connection::getDesc()
2940 {
2941         return std::string("con(")+
2942                         itos(m_udpSocket.GetHandle())+"/"+itos(m_peer_id)+")";
2943 }
2944
2945 void Connection::DisconnectPeer(u16 peer_id)
2946 {
2947         ConnectionCommand discon;
2948         discon.disconnect_peer(peer_id);
2949         putCommand(discon);
2950 }
2951
2952 void Connection::sendAck(u16 peer_id, u8 channelnum, u16 seqnum)
2953 {
2954         assert(channelnum < CHANNEL_COUNT); // Pre-condition
2955
2956         LOG(dout_con<<getDesc()
2957                         <<" Queuing ACK command to peer_id: " << peer_id <<
2958                         " channel: " << (channelnum & 0xFF) <<
2959                         " seqnum: " << seqnum << std::endl);
2960
2961         ConnectionCommand c;
2962         SharedBuffer<u8> ack(4);
2963         writeU8(&ack[0], TYPE_CONTROL);
2964         writeU8(&ack[1], CONTROLTYPE_ACK);
2965         writeU16(&ack[2], seqnum);
2966
2967         c.ack(peer_id, channelnum, ack);
2968         putCommand(c);
2969         m_sendThread.Trigger();
2970 }
2971
2972 UDPPeer* Connection::createServerPeer(Address& address)
2973 {
2974         if (getPeerNoEx(PEER_ID_SERVER) != 0)
2975         {
2976                 throw ConnectionException("Already connected to a server");
2977         }
2978
2979         UDPPeer *peer = new UDPPeer(PEER_ID_SERVER, address, this);
2980
2981         {
2982                 MutexAutoLock lock(m_peers_mutex);
2983                 m_peers[peer->id] = peer;
2984                 m_peer_ids.push_back(peer->id);
2985         }
2986
2987         return peer;
2988 }
2989
2990 } // namespace