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