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