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