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