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