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