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