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