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