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