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