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