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