]> git.lizzy.rs Git - minetest.git/blob - src/network/connection.cpp
495b15426b85491d769e792bf25d37399d9055dc
[minetest.git] / src / network / connection.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include <iomanip>
21 #include <cerrno>
22 #include <algorithm>
23 #include <cmath>
24 #include "connection.h"
25 #include "serialization.h"
26 #include "log.h"
27 #include "porting.h"
28 #include "network/connectionthreads.h"
29 #include "network/networkpacket.h"
30 #include "network/peerhandler.h"
31 #include "util/serialize.h"
32 #include "util/numeric.h"
33 #include "util/string.h"
34 #include "settings.h"
35 #include "profiler.h"
36
37 namespace con
38 {
39
40 /******************************************************************************/
41 /* defines used for debugging and profiling                                   */
42 /******************************************************************************/
43 #ifdef NDEBUG
44 #define LOG(a) a
45 #define PROFILE(a)
46 #else
47 /* this mutex is used to achieve log message consistency */
48 std::mutex log_message_mutex;
49 #define LOG(a)                                                                 \
50         {                                                                          \
51         MutexAutoLock loglock(log_message_mutex);                                 \
52         a;                                                                         \
53         }
54 #define PROFILE(a) a
55 #endif
56
57 #define PING_TIMEOUT 5.0
58
59 BufferedPacket makePacket(Address &address, SharedBuffer<u8> data,
60                 u32 protocol_id, session_t sender_peer_id, u8 channel)
61 {
62         u32 packet_size = data.getSize() + BASE_HEADER_SIZE;
63         BufferedPacket p(packet_size);
64         p.address = address;
65
66         writeU32(&p.data[0], protocol_id);
67         writeU16(&p.data[4], sender_peer_id);
68         writeU8(&p.data[6], channel);
69
70         memcpy(&p.data[BASE_HEADER_SIZE], *data, data.getSize());
71
72         return p;
73 }
74
75 SharedBuffer<u8> makeOriginalPacket(const SharedBuffer<u8> &data)
76 {
77         u32 header_size = 1;
78         u32 packet_size = data.getSize() + header_size;
79         SharedBuffer<u8> b(packet_size);
80
81         writeU8(&(b[0]), PACKET_TYPE_ORIGINAL);
82         if (data.getSize() > 0) {
83                 memcpy(&(b[header_size]), *data, data.getSize());
84         }
85         return b;
86 }
87
88 // Split data in chunks and add TYPE_SPLIT headers to them
89 void makeSplitPacket(const SharedBuffer<u8> &data, u32 chunksize_max, u16 seqnum,
90                 std::list<SharedBuffer<u8>> *chunks)
91 {
92         // Chunk packets, containing the TYPE_SPLIT header
93         u32 chunk_header_size = 7;
94         u32 maximum_data_size = chunksize_max - chunk_header_size;
95         u32 start = 0;
96         u32 end = 0;
97         u32 chunk_num = 0;
98         u16 chunk_count = 0;
99         do {
100                 end = start + maximum_data_size - 1;
101                 if (end > data.getSize() - 1)
102                         end = data.getSize() - 1;
103
104                 u32 payload_size = end - start + 1;
105                 u32 packet_size = chunk_header_size + payload_size;
106
107                 SharedBuffer<u8> chunk(packet_size);
108
109                 writeU8(&chunk[0], PACKET_TYPE_SPLIT);
110                 writeU16(&chunk[1], seqnum);
111                 // [3] u16 chunk_count is written at next stage
112                 writeU16(&chunk[5], chunk_num);
113                 memcpy(&chunk[chunk_header_size], &data[start], payload_size);
114
115                 chunks->push_back(chunk);
116                 chunk_count++;
117
118                 start = end + 1;
119                 chunk_num++;
120         }
121         while (end != data.getSize() - 1);
122
123         for (SharedBuffer<u8> &chunk : *chunks) {
124                 // Write chunk_count
125                 writeU16(&(chunk[3]), chunk_count);
126         }
127 }
128
129 void makeAutoSplitPacket(SharedBuffer<u8> data, u32 chunksize_max,
130                 u16 &split_seqnum, std::list<SharedBuffer<u8>> *list)
131 {
132         u32 original_header_size = 1;
133
134         if (data.getSize() + original_header_size > chunksize_max) {
135                 makeSplitPacket(data, chunksize_max, split_seqnum, list);
136                 split_seqnum++;
137                 return;
138         }
139
140         list->push_back(makeOriginalPacket(data));
141 }
142
143 SharedBuffer<u8> makeReliablePacket(SharedBuffer<u8> data, u16 seqnum)
144 {
145         u32 header_size = 3;
146         u32 packet_size = data.getSize() + header_size;
147         SharedBuffer<u8> b(packet_size);
148
149         writeU8(&b[0], PACKET_TYPE_RELIABLE);
150         writeU16(&b[1], seqnum);
151
152         memcpy(&b[header_size], *data, data.getSize());
153
154         return b;
155 }
156
157 /*
158         ReliablePacketBuffer
159 */
160
161 void ReliablePacketBuffer::print()
162 {
163         MutexAutoLock listlock(m_list_mutex);
164         LOG(dout_con<<"Dump of ReliablePacketBuffer:" << std::endl);
165         unsigned int index = 0;
166         for (BufferedPacket &bufferedPacket : m_list) {
167                 u16 s = readU16(&(bufferedPacket.data[BASE_HEADER_SIZE+1]));
168                 LOG(dout_con<<index<< ":" << s << std::endl);
169                 index++;
170         }
171 }
172 bool ReliablePacketBuffer::empty()
173 {
174         MutexAutoLock listlock(m_list_mutex);
175         return m_list.empty();
176 }
177
178 u32 ReliablePacketBuffer::size()
179 {
180         return m_list_size;
181 }
182
183 bool ReliablePacketBuffer::containsPacket(u16 seqnum)
184 {
185         return !(findPacket(seqnum) == m_list.end());
186 }
187
188 RPBSearchResult ReliablePacketBuffer::findPacket(u16 seqnum)
189 {
190         std::list<BufferedPacket>::iterator i = m_list.begin();
191         for(; i != m_list.end(); ++i)
192         {
193                 u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
194                 /*dout_con<<"findPacket(): finding seqnum="<<seqnum
195                                 <<", comparing to s="<<s<<std::endl;*/
196                 if (s == seqnum)
197                         break;
198         }
199         return i;
200 }
201 RPBSearchResult ReliablePacketBuffer::notFound()
202 {
203         return m_list.end();
204 }
205 bool ReliablePacketBuffer::getFirstSeqnum(u16& result)
206 {
207         MutexAutoLock listlock(m_list_mutex);
208         if (m_list.empty())
209                 return false;
210         BufferedPacket p = *m_list.begin();
211         result = readU16(&p.data[BASE_HEADER_SIZE+1]);
212         return true;
213 }
214
215 BufferedPacket ReliablePacketBuffer::popFirst()
216 {
217         MutexAutoLock listlock(m_list_mutex);
218         if (m_list.empty())
219                 throw NotFoundException("Buffer is empty");
220         BufferedPacket p = *m_list.begin();
221         m_list.erase(m_list.begin());
222         --m_list_size;
223
224         if (m_list_size == 0) {
225                 m_oldest_non_answered_ack = 0;
226         } else {
227                 m_oldest_non_answered_ack =
228                                 readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]);
229         }
230         return p;
231 }
232 BufferedPacket ReliablePacketBuffer::popSeqnum(u16 seqnum)
233 {
234         MutexAutoLock listlock(m_list_mutex);
235         RPBSearchResult r = findPacket(seqnum);
236         if (r == notFound()) {
237                 LOG(dout_con<<"Sequence number: " << seqnum
238                                 << " not found in reliable buffer"<<std::endl);
239                 throw NotFoundException("seqnum not found in buffer");
240         }
241         BufferedPacket p = *r;
242
243
244         RPBSearchResult next = r;
245         ++next;
246         if (next != notFound()) {
247                 u16 s = readU16(&(next->data[BASE_HEADER_SIZE+1]));
248                 m_oldest_non_answered_ack = s;
249         }
250
251         m_list.erase(r);
252         --m_list_size;
253
254         if (m_list_size == 0)
255         { m_oldest_non_answered_ack = 0; }
256         else
257         { m_oldest_non_answered_ack = readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]);     }
258         return p;
259 }
260 void ReliablePacketBuffer::insert(BufferedPacket &p,u16 next_expected)
261 {
262         MutexAutoLock listlock(m_list_mutex);
263         if (p.data.getSize() < BASE_HEADER_SIZE + 3) {
264                 errorstream << "ReliablePacketBuffer::insert(): Invalid data size for "
265                         "reliable packet" << std::endl;
266                 return;
267         }
268         u8 type = readU8(&p.data[BASE_HEADER_SIZE + 0]);
269         if (type != PACKET_TYPE_RELIABLE) {
270                 errorstream << "ReliablePacketBuffer::insert(): type is not reliable"
271                         << std::endl;
272                 return;
273         }
274         u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE + 1]);
275
276         if (!seqnum_in_window(seqnum, next_expected, MAX_RELIABLE_WINDOW_SIZE)) {
277                 errorstream << "ReliablePacketBuffer::insert(): seqnum is outside of "
278                         "expected window " << std::endl;
279                 return;
280         }
281         if (seqnum == next_expected) {
282                 errorstream << "ReliablePacketBuffer::insert(): seqnum is next expected"
283                         << std::endl;
284                 return;
285         }
286
287         ++m_list_size;
288         sanity_check(m_list_size <= SEQNUM_MAX+1);      // FIXME: Handle the error?
289
290         // Find the right place for the packet and insert it there
291         // If list is empty, just add it
292         if (m_list.empty())
293         {
294                 m_list.push_back(p);
295                 m_oldest_non_answered_ack = seqnum;
296                 // Done.
297                 return;
298         }
299
300         // Otherwise find the right place
301         std::list<BufferedPacket>::iterator i = m_list.begin();
302         // Find the first packet in the list which has a higher seqnum
303         u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
304
305         /* case seqnum is smaller then next_expected seqnum */
306         /* this is true e.g. on wrap around */
307         if (seqnum < next_expected) {
308                 while(((s < seqnum) || (s >= next_expected)) && (i != m_list.end())) {
309                         ++i;
310                         if (i != m_list.end())
311                                 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
312                 }
313         }
314         /* non wrap around case (at least for incoming and next_expected */
315         else
316         {
317                 while(((s < seqnum) && (s >= next_expected)) && (i != m_list.end())) {
318                         ++i;
319                         if (i != m_list.end())
320                                 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
321                 }
322         }
323
324         if (s == seqnum) {
325                 if (
326                         (readU16(&(i->data[BASE_HEADER_SIZE+1])) != seqnum) ||
327                         (i->data.getSize() != p.data.getSize()) ||
328                         (i->address != p.address)
329                         )
330                 {
331                         /* if this happens your maximum transfer window may be to big */
332                         fprintf(stderr,
333                                         "Duplicated seqnum %d non matching packet detected:\n",
334                                         seqnum);
335                         fprintf(stderr, "Old: seqnum: %05d size: %04d, address: %s\n",
336                                         readU16(&(i->data[BASE_HEADER_SIZE+1])),i->data.getSize(),
337                                         i->address.serializeString().c_str());
338                         fprintf(stderr, "New: seqnum: %05d size: %04u, address: %s\n",
339                                         readU16(&(p.data[BASE_HEADER_SIZE+1])),p.data.getSize(),
340                                         p.address.serializeString().c_str());
341                         throw IncomingDataCorruption("duplicated packet isn't same as original one");
342                 }
343
344                 /* nothing to do this seems to be a resent packet */
345                 /* for paranoia reason data should be compared */
346                 --m_list_size;
347         }
348         /* insert or push back */
349         else if (i != m_list.end()) {
350                 m_list.insert(i, p);
351         }
352         else {
353                 m_list.push_back(p);
354         }
355
356         /* update last packet number */
357         m_oldest_non_answered_ack = readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]);
358 }
359
360 void ReliablePacketBuffer::incrementTimeouts(float dtime)
361 {
362         MutexAutoLock listlock(m_list_mutex);
363         for (BufferedPacket &bufferedPacket : m_list) {
364                 bufferedPacket.time += dtime;
365                 bufferedPacket.totaltime += dtime;
366         }
367 }
368
369 std::list<BufferedPacket> ReliablePacketBuffer::getTimedOuts(float timeout,
370                                                                                                         unsigned int max_packets)
371 {
372         MutexAutoLock listlock(m_list_mutex);
373         std::list<BufferedPacket> timed_outs;
374         for (BufferedPacket &bufferedPacket : m_list) {
375                 if (bufferedPacket.time >= timeout) {
376                         timed_outs.push_back(bufferedPacket);
377
378                         //this packet will be sent right afterwards reset timeout here
379                         bufferedPacket.time = 0.0f;
380                         if (timed_outs.size() >= max_packets)
381                                 break;
382                 }
383         }
384         return timed_outs;
385 }
386
387 /*
388         IncomingSplitBuffer
389 */
390
391 IncomingSplitBuffer::~IncomingSplitBuffer()
392 {
393         MutexAutoLock listlock(m_map_mutex);
394         for (auto &i : m_buf) {
395                 delete i.second;
396         }
397 }
398 /*
399         This will throw a GotSplitPacketException when a full
400         split packet is constructed.
401 */
402 SharedBuffer<u8> IncomingSplitBuffer::insert(const BufferedPacket &p, bool reliable)
403 {
404         MutexAutoLock listlock(m_map_mutex);
405         u32 headersize = BASE_HEADER_SIZE + 7;
406         if (p.data.getSize() < headersize) {
407                 errorstream << "Invalid data size for split packet" << std::endl;
408                 return SharedBuffer<u8>();
409         }
410         u8 type = readU8(&p.data[BASE_HEADER_SIZE+0]);
411         u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]);
412         u16 chunk_count = readU16(&p.data[BASE_HEADER_SIZE+3]);
413         u16 chunk_num = readU16(&p.data[BASE_HEADER_SIZE+5]);
414
415         if (type != PACKET_TYPE_SPLIT) {
416                 errorstream << "IncomingSplitBuffer::insert(): type is not split"
417                         << std::endl;
418                 return SharedBuffer<u8>();
419         }
420
421         // Add if doesn't exist
422         if (m_buf.find(seqnum) == m_buf.end()) {
423                 m_buf[seqnum] = new IncomingSplitPacket(chunk_count, reliable);
424         }
425
426         IncomingSplitPacket *sp = m_buf[seqnum];
427
428         if (chunk_count != sp->chunk_count)
429                 LOG(derr_con<<"Connection: WARNING: chunk_count="<<chunk_count
430                                 <<" != sp->chunk_count="<<sp->chunk_count
431                                 <<std::endl);
432         if (reliable != sp->reliable)
433                 LOG(derr_con<<"Connection: WARNING: reliable="<<reliable
434                                 <<" != sp->reliable="<<sp->reliable
435                                 <<std::endl);
436
437         // If chunk already exists, ignore it.
438         // Sometimes two identical packets may arrive when there is network
439         // lag and the server re-sends stuff.
440         if (sp->chunks.find(chunk_num) != sp->chunks.end())
441                 return SharedBuffer<u8>();
442
443         // Cut chunk data out of packet
444         u32 chunkdatasize = p.data.getSize() - headersize;
445         SharedBuffer<u8> chunkdata(chunkdatasize);
446         memcpy(*chunkdata, &(p.data[headersize]), chunkdatasize);
447
448         // Set chunk data in buffer
449         sp->chunks[chunk_num] = chunkdata;
450
451         // If not all chunks are received, return empty buffer
452         if (!sp->allReceived())
453                 return SharedBuffer<u8>();
454
455         // Calculate total size
456         u32 totalsize = 0;
457         for (const auto &chunk : sp->chunks) {
458                 totalsize += chunk.second.getSize();
459         }
460
461         SharedBuffer<u8> fulldata(totalsize);
462
463         // Copy chunks to data buffer
464         u32 start = 0;
465         for (u32 chunk_i=0; chunk_i<sp->chunk_count; chunk_i++) {
466                 const SharedBuffer<u8> &buf = sp->chunks[chunk_i];
467                 u16 buf_chunkdatasize = buf.getSize();
468                 memcpy(&fulldata[start], *buf, buf_chunkdatasize);
469                 start += buf_chunkdatasize;
470         }
471
472         // Remove sp from buffer
473         m_buf.erase(seqnum);
474         delete sp;
475
476         return fulldata;
477 }
478 void IncomingSplitBuffer::removeUnreliableTimedOuts(float dtime, float timeout)
479 {
480         std::deque<u16> remove_queue;
481         {
482                 MutexAutoLock listlock(m_map_mutex);
483                 for (auto &i : m_buf) {
484                         IncomingSplitPacket *p = i.second;
485                         // Reliable ones are not removed by timeout
486                         if (p->reliable)
487                                 continue;
488                         p->time += dtime;
489                         if (p->time >= timeout)
490                                 remove_queue.push_back(i.first);
491                 }
492         }
493         for (u16 j : remove_queue) {
494                 MutexAutoLock listlock(m_map_mutex);
495                 LOG(dout_con<<"NOTE: Removing timed out unreliable split packet"<<std::endl);
496                 delete m_buf[j];
497                 m_buf.erase(j);
498         }
499 }
500
501 /*
502         ConnectionCommand
503  */
504
505 void ConnectionCommand::send(session_t peer_id_, u8 channelnum_, NetworkPacket *pkt,
506         bool reliable_)
507 {
508         type = CONNCMD_SEND;
509         peer_id = peer_id_;
510         channelnum = channelnum_;
511         data = pkt->oldForgePacket();
512         reliable = reliable_;
513 }
514
515 /*
516         Channel
517 */
518
519 u16 Channel::readNextIncomingSeqNum()
520 {
521         MutexAutoLock internal(m_internal_mutex);
522         return next_incoming_seqnum;
523 }
524
525 u16 Channel::incNextIncomingSeqNum()
526 {
527         MutexAutoLock internal(m_internal_mutex);
528         u16 retval = next_incoming_seqnum;
529         next_incoming_seqnum++;
530         return retval;
531 }
532
533 u16 Channel::readNextSplitSeqNum()
534 {
535         MutexAutoLock internal(m_internal_mutex);
536         return next_outgoing_split_seqnum;
537 }
538 void Channel::setNextSplitSeqNum(u16 seqnum)
539 {
540         MutexAutoLock internal(m_internal_mutex);
541         next_outgoing_split_seqnum = seqnum;
542 }
543
544 u16 Channel::getOutgoingSequenceNumber(bool& successful)
545 {
546         MutexAutoLock internal(m_internal_mutex);
547         u16 retval = next_outgoing_seqnum;
548         u16 lowest_unacked_seqnumber;
549
550         /* shortcut if there ain't any packet in outgoing list */
551         if (outgoing_reliables_sent.empty())
552         {
553                 next_outgoing_seqnum++;
554                 return retval;
555         }
556
557         if (outgoing_reliables_sent.getFirstSeqnum(lowest_unacked_seqnumber))
558         {
559                 if (lowest_unacked_seqnumber < next_outgoing_seqnum) {
560                         // ugly cast but this one is required in order to tell compiler we
561                         // know about difference of two unsigned may be negative in general
562                         // but we already made sure it won't happen in this case
563                         if (((u16)(next_outgoing_seqnum - lowest_unacked_seqnumber)) > window_size) {
564                                 successful = false;
565                                 return 0;
566                         }
567                 }
568                 else {
569                         // ugly cast but this one is required in order to tell compiler we
570                         // know about difference of two unsigned may be negative in general
571                         // but we already made sure it won't happen in this case
572                         if ((next_outgoing_seqnum + (u16)(SEQNUM_MAX - lowest_unacked_seqnumber)) >
573                                 window_size) {
574                                 successful = false;
575                                 return 0;
576                         }
577                 }
578         }
579
580         next_outgoing_seqnum++;
581         return retval;
582 }
583
584 u16 Channel::readOutgoingSequenceNumber()
585 {
586         MutexAutoLock internal(m_internal_mutex);
587         return next_outgoing_seqnum;
588 }
589
590 bool Channel::putBackSequenceNumber(u16 seqnum)
591 {
592         if (((seqnum + 1) % (SEQNUM_MAX+1)) == next_outgoing_seqnum) {
593
594                 next_outgoing_seqnum = seqnum;
595                 return true;
596         }
597         return false;
598 }
599
600 void Channel::UpdateBytesSent(unsigned int bytes, unsigned int packets)
601 {
602         MutexAutoLock internal(m_internal_mutex);
603         current_bytes_transfered += bytes;
604         current_packet_successful += packets;
605 }
606
607 void Channel::UpdateBytesReceived(unsigned int bytes) {
608         MutexAutoLock internal(m_internal_mutex);
609         current_bytes_received += bytes;
610 }
611
612 void Channel::UpdateBytesLost(unsigned int bytes)
613 {
614         MutexAutoLock internal(m_internal_mutex);
615         current_bytes_lost += bytes;
616 }
617
618
619 void Channel::UpdatePacketLossCounter(unsigned int count)
620 {
621         MutexAutoLock internal(m_internal_mutex);
622         current_packet_loss += count;
623 }
624
625 void Channel::UpdatePacketTooLateCounter()
626 {
627         MutexAutoLock internal(m_internal_mutex);
628         current_packet_too_late++;
629 }
630
631 void Channel::UpdateTimers(float dtime)
632 {
633         bpm_counter += dtime;
634         packet_loss_counter += dtime;
635
636         if (packet_loss_counter > 1.0f) {
637                 packet_loss_counter -= 1.0f;
638
639                 unsigned int packet_loss = 11; /* use a neutral value for initialization */
640                 unsigned int packets_successful = 0;
641                 //unsigned int packet_too_late = 0;
642
643                 bool reasonable_amount_of_data_transmitted = false;
644
645                 {
646                         MutexAutoLock internal(m_internal_mutex);
647                         packet_loss = current_packet_loss;
648                         //packet_too_late = current_packet_too_late;
649                         packets_successful = current_packet_successful;
650
651                         if (current_bytes_transfered > (unsigned int) (window_size*512/2)) {
652                                 reasonable_amount_of_data_transmitted = true;
653                         }
654                         current_packet_loss = 0;
655                         current_packet_too_late = 0;
656                         current_packet_successful = 0;
657                 }
658
659                 /* dynamic window size */
660                 float successful_to_lost_ratio = 0.0f;
661                 bool done = false;
662
663                 if (packets_successful > 0) {
664                         successful_to_lost_ratio = packet_loss/packets_successful;
665                 } else if (packet_loss > 0) {
666                         window_size = std::max(
667                                         (window_size - 10),
668                                         MIN_RELIABLE_WINDOW_SIZE);
669                         done = true;
670                 }
671
672                 if (!done) {
673                         if ((successful_to_lost_ratio < 0.01f) &&
674                                 (window_size < MAX_RELIABLE_WINDOW_SIZE)) {
675                                 /* don't even think about increasing if we didn't even
676                                  * use major parts of our window */
677                                 if (reasonable_amount_of_data_transmitted)
678                                         window_size = std::min(
679                                                         (window_size + 100),
680                                                         MAX_RELIABLE_WINDOW_SIZE);
681                         } else if ((successful_to_lost_ratio < 0.05f) &&
682                                         (window_size < MAX_RELIABLE_WINDOW_SIZE)) {
683                                 /* don't even think about increasing if we didn't even
684                                  * use major parts of our window */
685                                 if (reasonable_amount_of_data_transmitted)
686                                         window_size = std::min(
687                                                         (window_size + 50),
688                                                         MAX_RELIABLE_WINDOW_SIZE);
689                         } else if (successful_to_lost_ratio > 0.15f) {
690                                 window_size = std::max(
691                                                 (window_size - 100),
692                                                 MIN_RELIABLE_WINDOW_SIZE);
693                         } else if (successful_to_lost_ratio > 0.1f) {
694                                 window_size = std::max(
695                                                 (window_size - 50),
696                                                 MIN_RELIABLE_WINDOW_SIZE);
697                         }
698                 }
699         }
700
701         if (bpm_counter > 10.0f) {
702                 {
703                         MutexAutoLock internal(m_internal_mutex);
704                         cur_kbps                 =
705                                         (((float) current_bytes_transfered)/bpm_counter)/1024.0f;
706                         current_bytes_transfered = 0;
707                         cur_kbps_lost            =
708                                         (((float) current_bytes_lost)/bpm_counter)/1024.0f;
709                         current_bytes_lost       = 0;
710                         cur_incoming_kbps        =
711                                         (((float) current_bytes_received)/bpm_counter)/1024.0f;
712                         current_bytes_received   = 0;
713                         bpm_counter              = 0.0f;
714                 }
715
716                 if (cur_kbps > max_kbps) {
717                         max_kbps = cur_kbps;
718                 }
719
720                 if (cur_kbps_lost > max_kbps_lost) {
721                         max_kbps_lost = cur_kbps_lost;
722                 }
723
724                 if (cur_incoming_kbps > max_incoming_kbps) {
725                         max_incoming_kbps = cur_incoming_kbps;
726                 }
727
728                 rate_samples       = MYMIN(rate_samples+1,10);
729                 float old_fraction = ((float) (rate_samples-1) )/( (float) rate_samples);
730                 avg_kbps           = avg_kbps * old_fraction +
731                                 cur_kbps * (1.0 - old_fraction);
732                 avg_kbps_lost      = avg_kbps_lost * old_fraction +
733                                 cur_kbps_lost * (1.0 - old_fraction);
734                 avg_incoming_kbps  = avg_incoming_kbps * old_fraction +
735                                 cur_incoming_kbps * (1.0 - old_fraction);
736         }
737 }
738
739
740 /*
741         Peer
742 */
743
744 PeerHelper::PeerHelper(Peer* peer) :
745         m_peer(peer)
746 {
747         if (peer && !peer->IncUseCount())
748                 m_peer = nullptr;
749 }
750
751 PeerHelper::~PeerHelper()
752 {
753         if (m_peer)
754                 m_peer->DecUseCount();
755
756         m_peer = nullptr;
757 }
758
759 PeerHelper& PeerHelper::operator=(Peer* peer)
760 {
761         m_peer = peer;
762         if (peer && !peer->IncUseCount())
763                 m_peer = nullptr;
764         return *this;
765 }
766
767 Peer* PeerHelper::operator->() const
768 {
769         return m_peer;
770 }
771
772 Peer* PeerHelper::operator&() const
773 {
774         return m_peer;
775 }
776
777 bool PeerHelper::operator!()
778 {
779         return ! m_peer;
780 }
781
782 bool PeerHelper::operator!=(void* ptr)
783 {
784         return ((void*) m_peer != ptr);
785 }
786
787 bool Peer::IncUseCount()
788 {
789         MutexAutoLock lock(m_exclusive_access_mutex);
790
791         if (!m_pending_deletion) {
792                 this->m_usage++;
793                 return true;
794         }
795
796         return false;
797 }
798
799 void Peer::DecUseCount()
800 {
801         {
802                 MutexAutoLock lock(m_exclusive_access_mutex);
803                 sanity_check(m_usage > 0);
804                 m_usage--;
805
806                 if (!((m_pending_deletion) && (m_usage == 0)))
807                         return;
808         }
809         delete this;
810 }
811
812 void Peer::RTTStatistics(float rtt, const std::string &profiler_id)
813 {
814         static const float avg_factor = 100.0f / MAX_RELIABLE_WINDOW_SIZE;
815
816         if (m_last_rtt > 0) {
817                 /* set min max values */
818                 if (rtt < m_rtt.min_rtt)
819                         m_rtt.min_rtt = rtt;
820                 if (rtt >= m_rtt.max_rtt)
821                         m_rtt.max_rtt = rtt;
822
823                 /* do average calculation */
824                 if (m_rtt.avg_rtt < 0.0)
825                         m_rtt.avg_rtt = rtt;
826                 else
827                         m_rtt.avg_rtt += (rtt - m_rtt.avg_rtt) * avg_factor;
828
829                 /* do jitter calculation */
830
831                 //just use some neutral value at beginning
832                 float jitter = std::fabs(rtt - m_last_rtt);
833
834                 if (jitter < m_rtt.jitter_min)
835                         m_rtt.jitter_min = jitter;
836                 if (jitter >= m_rtt.jitter_max)
837                         m_rtt.jitter_max = jitter;
838
839                 if (m_rtt.jitter_avg < 0.0)
840                         m_rtt.jitter_avg = jitter;
841                 else
842                         m_rtt.jitter_avg += (jitter - m_rtt.jitter_avg) * avg_factor;
843
844                 if (!profiler_id.empty()) {
845                         g_profiler->graphAdd(profiler_id + "_rtt", rtt);
846                         g_profiler->graphAdd(profiler_id + "_jitter", jitter);
847                 }
848         }
849         /* save values required for next loop */
850         m_last_rtt = rtt;
851 }
852
853 bool Peer::isTimedOut(float timeout)
854 {
855         MutexAutoLock lock(m_exclusive_access_mutex);
856         u64 current_time = porting::getTimeMs();
857
858         float dtime = CALC_DTIME(m_last_timeout_check,current_time);
859         m_last_timeout_check = current_time;
860
861         m_timeout_counter += dtime;
862
863         return m_timeout_counter > timeout;
864 }
865
866 void Peer::Drop()
867 {
868         {
869                 MutexAutoLock usage_lock(m_exclusive_access_mutex);
870                 m_pending_deletion = true;
871                 if (m_usage != 0)
872                         return;
873         }
874
875         PROFILE(std::stringstream peerIdentifier1);
876         PROFILE(peerIdentifier1 << "runTimeouts[" << m_connection->getDesc()
877                         << ";" << id << ";RELIABLE]");
878         PROFILE(g_profiler->remove(peerIdentifier1.str()));
879         PROFILE(std::stringstream peerIdentifier2);
880         PROFILE(peerIdentifier2 << "sendPackets[" << m_connection->getDesc()
881                         << ";" << id << ";RELIABLE]");
882         PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier2.str(), SPT_AVG));
883
884         delete this;
885 }
886
887 UDPPeer::UDPPeer(u16 a_id, Address a_address, Connection* connection) :
888         Peer(a_address,a_id,connection)
889 {
890         for (Channel &channel : channels)
891                 channel.setWindowSize(g_settings->getU16("max_packets_per_iteration"));
892 }
893
894 bool UDPPeer::getAddress(MTProtocols type,Address& toset)
895 {
896         if ((type == MTP_UDP) || (type == MTP_MINETEST_RELIABLE_UDP) || (type == MTP_PRIMARY))
897         {
898                 toset = address;
899                 return true;
900         }
901
902         return false;
903 }
904
905 void UDPPeer::reportRTT(float rtt)
906 {
907         assert(rtt >= 0.0f);
908
909         RTTStatistics(rtt, "rudp");
910
911         float timeout = getStat(AVG_RTT) * RESEND_TIMEOUT_FACTOR;
912         timeout = rangelim(timeout, RESEND_TIMEOUT_MIN, RESEND_TIMEOUT_MAX);
913
914         MutexAutoLock usage_lock(m_exclusive_access_mutex);
915         resend_timeout = timeout;
916 }
917
918 bool UDPPeer::Ping(float dtime,SharedBuffer<u8>& data)
919 {
920         m_ping_timer += dtime;
921         if (m_ping_timer >= PING_TIMEOUT)
922         {
923                 // Create and send PING packet
924                 writeU8(&data[0], PACKET_TYPE_CONTROL);
925                 writeU8(&data[1], CONTROLTYPE_PING);
926                 m_ping_timer = 0.0;
927                 return true;
928         }
929         return false;
930 }
931
932 void UDPPeer::PutReliableSendCommand(ConnectionCommand &c,
933                 unsigned int max_packet_size)
934 {
935         if (m_pending_disconnect)
936                 return;
937
938         if ( channels[c.channelnum].queued_commands.empty() &&
939                         /* don't queue more packets then window size */
940                         (channels[c.channelnum].queued_reliables.size()
941                         < (channels[c.channelnum].getWindowSize()/2))) {
942                 LOG(dout_con<<m_connection->getDesc()
943                                 <<" processing reliable command for peer id: " << c.peer_id
944                                 <<" data size: " << c.data.getSize() << std::endl);
945                 if (!processReliableSendCommand(c,max_packet_size)) {
946                         channels[c.channelnum].queued_commands.push_back(c);
947                 }
948         }
949         else {
950                 LOG(dout_con<<m_connection->getDesc()
951                                 <<" Queueing reliable command for peer id: " << c.peer_id
952                                 <<" data size: " << c.data.getSize() <<std::endl);
953                 channels[c.channelnum].queued_commands.push_back(c);
954         }
955 }
956
957 bool UDPPeer::processReliableSendCommand(
958                                 ConnectionCommand &c,
959                                 unsigned int max_packet_size)
960 {
961         if (m_pending_disconnect)
962                 return true;
963
964         u32 chunksize_max = max_packet_size
965                                                         - BASE_HEADER_SIZE
966                                                         - RELIABLE_HEADER_SIZE;
967
968         sanity_check(c.data.getSize() < MAX_RELIABLE_WINDOW_SIZE*512);
969
970         std::list<SharedBuffer<u8>> originals;
971         u16 split_sequence_number = channels[c.channelnum].readNextSplitSeqNum();
972
973         if (c.raw) {
974                 originals.emplace_back(c.data);
975         } else {
976                 makeAutoSplitPacket(c.data, chunksize_max,split_sequence_number, &originals);
977                 channels[c.channelnum].setNextSplitSeqNum(split_sequence_number);
978         }
979
980         bool have_sequence_number = true;
981         bool have_initial_sequence_number = false;
982         std::queue<BufferedPacket> toadd;
983         volatile u16 initial_sequence_number = 0;
984
985         for (SharedBuffer<u8> &original : originals) {
986                 u16 seqnum = channels[c.channelnum].getOutgoingSequenceNumber(have_sequence_number);
987
988                 /* oops, we don't have enough sequence numbers to send this packet */
989                 if (!have_sequence_number)
990                         break;
991
992                 if (!have_initial_sequence_number)
993                 {
994                         initial_sequence_number = seqnum;
995                         have_initial_sequence_number = true;
996                 }
997
998                 SharedBuffer<u8> reliable = makeReliablePacket(original, seqnum);
999
1000                 // Add base headers and make a packet
1001                 BufferedPacket p = con::makePacket(address, reliable,
1002                                 m_connection->GetProtocolID(), m_connection->GetPeerID(),
1003                                 c.channelnum);
1004
1005                 toadd.push(p);
1006         }
1007
1008         if (have_sequence_number) {
1009                 volatile u16 pcount = 0;
1010                 while (!toadd.empty()) {
1011                         BufferedPacket p = toadd.front();
1012                         toadd.pop();
1013 //                      LOG(dout_con<<connection->getDesc()
1014 //                                      << " queuing reliable packet for peer_id: " << c.peer_id
1015 //                                      << " channel: " << (c.channelnum&0xFF)
1016 //                                      << " seqnum: " << readU16(&p.data[BASE_HEADER_SIZE+1])
1017 //                                      << std::endl)
1018                         channels[c.channelnum].queued_reliables.push(p);
1019                         pcount++;
1020                 }
1021                 sanity_check(channels[c.channelnum].queued_reliables.size() < 0xFFFF);
1022                 return true;
1023         }
1024
1025         volatile u16 packets_available = toadd.size();
1026         /* we didn't get a single sequence number no need to fill queue */
1027         if (!have_initial_sequence_number) {
1028                 return false;
1029         }
1030
1031         while (!toadd.empty()) {
1032                 /* remove packet */
1033                 toadd.pop();
1034
1035                 bool successfully_put_back_sequence_number
1036                         = channels[c.channelnum].putBackSequenceNumber(
1037                                 (initial_sequence_number+toadd.size() % (SEQNUM_MAX+1)));
1038
1039                 FATAL_ERROR_IF(!successfully_put_back_sequence_number, "error");
1040         }
1041
1042         LOG(dout_con<<m_connection->getDesc()
1043                         << " Windowsize exceeded on reliable sending "
1044                         << c.data.getSize() << " bytes"
1045                         << std::endl << "\t\tinitial_sequence_number: "
1046                         << initial_sequence_number
1047                         << std::endl << "\t\tgot at most            : "
1048                         << packets_available << " packets"
1049                         << std::endl << "\t\tpackets queued         : "
1050                         << channels[c.channelnum].outgoing_reliables_sent.size()
1051                         << std::endl);
1052
1053         return false;
1054 }
1055
1056 void UDPPeer::RunCommandQueues(
1057                                                         unsigned int max_packet_size,
1058                                                         unsigned int maxcommands,
1059                                                         unsigned int maxtransfer)
1060 {
1061
1062         for (Channel &channel : channels) {
1063                 unsigned int commands_processed = 0;
1064
1065                 if ((!channel.queued_commands.empty()) &&
1066                                 (channel.queued_reliables.size() < maxtransfer) &&
1067                                 (commands_processed < maxcommands)) {
1068                         try {
1069                                 ConnectionCommand c = channel.queued_commands.front();
1070
1071                                 LOG(dout_con << m_connection->getDesc()
1072                                                 << " processing queued reliable command " << std::endl);
1073
1074                                 // Packet is processed, remove it from queue
1075                                 if (processReliableSendCommand(c,max_packet_size)) {
1076                                         channel.queued_commands.pop_front();
1077                                 } else {
1078                                         LOG(dout_con << m_connection->getDesc()
1079                                                         << " Failed to queue packets for peer_id: " << c.peer_id
1080                                                         << ", delaying sending of " << c.data.getSize()
1081                                                         << " bytes" << std::endl);
1082                                 }
1083                         }
1084                         catch (ItemNotFoundException &e) {
1085                                 // intentionally empty
1086                         }
1087                 }
1088         }
1089 }
1090
1091 u16 UDPPeer::getNextSplitSequenceNumber(u8 channel)
1092 {
1093         assert(channel < CHANNEL_COUNT); // Pre-condition
1094         return channels[channel].readNextSplitSeqNum();
1095 }
1096
1097 void UDPPeer::setNextSplitSequenceNumber(u8 channel, u16 seqnum)
1098 {
1099         assert(channel < CHANNEL_COUNT); // Pre-condition
1100         channels[channel].setNextSplitSeqNum(seqnum);
1101 }
1102
1103 SharedBuffer<u8> UDPPeer::addSplitPacket(u8 channel, const BufferedPacket &toadd,
1104         bool reliable)
1105 {
1106         assert(channel < CHANNEL_COUNT); // Pre-condition
1107         return channels[channel].incoming_splits.insert(toadd, reliable);
1108 }
1109
1110 /*
1111         Connection
1112 */
1113
1114 Connection::Connection(u32 protocol_id, u32 max_packet_size, float timeout,
1115                 bool ipv6, PeerHandler *peerhandler) :
1116         m_udpSocket(ipv6),
1117         m_protocol_id(protocol_id),
1118         m_sendThread(new ConnectionSendThread(max_packet_size, timeout)),
1119         m_receiveThread(new ConnectionReceiveThread(max_packet_size)),
1120         m_bc_peerhandler(peerhandler)
1121
1122 {
1123         m_udpSocket.setTimeoutMs(5);
1124
1125         m_sendThread->setParent(this);
1126         m_receiveThread->setParent(this);
1127
1128         m_sendThread->start();
1129         m_receiveThread->start();
1130 }
1131
1132
1133 Connection::~Connection()
1134 {
1135         m_shutting_down = true;
1136         // request threads to stop
1137         m_sendThread->stop();
1138         m_receiveThread->stop();
1139
1140         //TODO for some unkonwn reason send/receive threads do not exit as they're
1141         // supposed to be but wait on peer timeout. To speed up shutdown we reduce
1142         // timeout to half a second.
1143         m_sendThread->setPeerTimeout(0.5);
1144
1145         // wait for threads to finish
1146         m_sendThread->wait();
1147         m_receiveThread->wait();
1148
1149         // Delete peers
1150         for (auto &peer : m_peers) {
1151                 delete peer.second;
1152         }
1153 }
1154
1155 /* Internal stuff */
1156 void Connection::putEvent(ConnectionEvent &e)
1157 {
1158         assert(e.type != CONNEVENT_NONE); // Pre-condition
1159         m_event_queue.push_back(e);
1160 }
1161
1162 void Connection::TriggerSend()
1163 {
1164         m_sendThread->Trigger();
1165 }
1166
1167 PeerHelper Connection::getPeerNoEx(session_t peer_id)
1168 {
1169         MutexAutoLock peerlock(m_peers_mutex);
1170         std::map<session_t, Peer *>::iterator node = m_peers.find(peer_id);
1171
1172         if (node == m_peers.end()) {
1173                 return PeerHelper(NULL);
1174         }
1175
1176         // Error checking
1177         FATAL_ERROR_IF(node->second->id != peer_id, "Invalid peer id");
1178
1179         return PeerHelper(node->second);
1180 }
1181
1182 /* find peer_id for address */
1183 u16 Connection::lookupPeer(Address& sender)
1184 {
1185         MutexAutoLock peerlock(m_peers_mutex);
1186         std::map<u16, Peer*>::iterator j;
1187         j = m_peers.begin();
1188         for(; j != m_peers.end(); ++j)
1189         {
1190                 Peer *peer = j->second;
1191                 if (peer->isPendingDeletion())
1192                         continue;
1193
1194                 Address tocheck;
1195
1196                 if ((peer->getAddress(MTP_MINETEST_RELIABLE_UDP, tocheck)) && (tocheck == sender))
1197                         return peer->id;
1198
1199                 if ((peer->getAddress(MTP_UDP, tocheck)) && (tocheck == sender))
1200                         return peer->id;
1201         }
1202
1203         return PEER_ID_INEXISTENT;
1204 }
1205
1206 bool Connection::deletePeer(session_t peer_id, bool timeout)
1207 {
1208         Peer *peer = 0;
1209
1210         /* lock list as short as possible */
1211         {
1212                 MutexAutoLock peerlock(m_peers_mutex);
1213                 if (m_peers.find(peer_id) == m_peers.end())
1214                         return false;
1215                 peer = m_peers[peer_id];
1216                 m_peers.erase(peer_id);
1217                 m_peer_ids.remove(peer_id);
1218         }
1219
1220         Address peer_address;
1221         //any peer has a primary address this never fails!
1222         peer->getAddress(MTP_PRIMARY, peer_address);
1223         // Create event
1224         ConnectionEvent e;
1225         e.peerRemoved(peer_id, timeout, peer_address);
1226         putEvent(e);
1227
1228
1229         peer->Drop();
1230         return true;
1231 }
1232
1233 /* Interface */
1234
1235 ConnectionEvent Connection::waitEvent(u32 timeout_ms)
1236 {
1237         try {
1238                 return m_event_queue.pop_front(timeout_ms);
1239         } catch(ItemNotFoundException &ex) {
1240                 ConnectionEvent e;
1241                 e.type = CONNEVENT_NONE;
1242                 return e;
1243         }
1244 }
1245
1246 void Connection::putCommand(ConnectionCommand &c)
1247 {
1248         if (!m_shutting_down) {
1249                 m_command_queue.push_back(c);
1250                 m_sendThread->Trigger();
1251         }
1252 }
1253
1254 void Connection::Serve(Address bind_addr)
1255 {
1256         ConnectionCommand c;
1257         c.serve(bind_addr);
1258         putCommand(c);
1259 }
1260
1261 void Connection::Connect(Address address)
1262 {
1263         ConnectionCommand c;
1264         c.connect(address);
1265         putCommand(c);
1266 }
1267
1268 bool Connection::Connected()
1269 {
1270         MutexAutoLock peerlock(m_peers_mutex);
1271
1272         if (m_peers.size() != 1)
1273                 return false;
1274
1275         std::map<session_t, Peer *>::iterator node = m_peers.find(PEER_ID_SERVER);
1276         if (node == m_peers.end())
1277                 return false;
1278
1279         if (m_peer_id == PEER_ID_INEXISTENT)
1280                 return false;
1281
1282         return true;
1283 }
1284
1285 void Connection::Disconnect()
1286 {
1287         ConnectionCommand c;
1288         c.disconnect();
1289         putCommand(c);
1290 }
1291
1292 void Connection::Receive(NetworkPacket* pkt)
1293 {
1294         for(;;) {
1295                 ConnectionEvent e = waitEvent(m_bc_receive_timeout);
1296                 if (e.type != CONNEVENT_NONE)
1297                         LOG(dout_con << getDesc() << ": Receive: got event: "
1298                                         << e.describe() << std::endl);
1299                 switch(e.type) {
1300                 case CONNEVENT_NONE:
1301                         throw NoIncomingDataException("No incoming data");
1302                 case CONNEVENT_DATA_RECEIVED:
1303                         // Data size is lesser than command size, ignoring packet
1304                         if (e.data.getSize() < 2) {
1305                                 continue;
1306                         }
1307
1308                         pkt->putRawPacket(*e.data, e.data.getSize(), e.peer_id);
1309                         return;
1310                 case CONNEVENT_PEER_ADDED: {
1311                         UDPPeer tmp(e.peer_id, e.address, this);
1312                         if (m_bc_peerhandler)
1313                                 m_bc_peerhandler->peerAdded(&tmp);
1314                         continue;
1315                 }
1316                 case CONNEVENT_PEER_REMOVED: {
1317                         UDPPeer tmp(e.peer_id, e.address, this);
1318                         if (m_bc_peerhandler)
1319                                 m_bc_peerhandler->deletingPeer(&tmp, e.timeout);
1320                         continue;
1321                 }
1322                 case CONNEVENT_BIND_FAILED:
1323                         throw ConnectionBindFailed("Failed to bind socket "
1324                                         "(port already in use?)");
1325                 }
1326         }
1327         throw NoIncomingDataException("No incoming data");
1328 }
1329
1330 void Connection::Send(session_t peer_id, u8 channelnum,
1331                 NetworkPacket *pkt, bool reliable)
1332 {
1333         assert(channelnum < CHANNEL_COUNT); // Pre-condition
1334
1335         ConnectionCommand c;
1336
1337         c.send(peer_id, channelnum, pkt, reliable);
1338         putCommand(c);
1339 }
1340
1341 Address Connection::GetPeerAddress(session_t peer_id)
1342 {
1343         PeerHelper peer = getPeerNoEx(peer_id);
1344
1345         if (!peer)
1346                 throw PeerNotFoundException("No address for peer found!");
1347         Address peer_address;
1348         peer->getAddress(MTP_PRIMARY, peer_address);
1349         return peer_address;
1350 }
1351
1352 float Connection::getPeerStat(session_t peer_id, rtt_stat_type type)
1353 {
1354         PeerHelper peer = getPeerNoEx(peer_id);
1355         if (!peer) return -1;
1356         return peer->getStat(type);
1357 }
1358
1359 float Connection::getLocalStat(rate_stat_type type)
1360 {
1361         PeerHelper peer = getPeerNoEx(PEER_ID_SERVER);
1362
1363         FATAL_ERROR_IF(!peer, "Connection::getLocalStat we couldn't get our own peer? are you serious???");
1364
1365         float retval = 0.0;
1366
1367         for (Channel &channel : dynamic_cast<UDPPeer *>(&peer)->channels) {
1368                 switch(type) {
1369                         case CUR_DL_RATE:
1370                                 retval += channel.getCurrentDownloadRateKB();
1371                                 break;
1372                         case AVG_DL_RATE:
1373                                 retval += channel.getAvgDownloadRateKB();
1374                                 break;
1375                         case CUR_INC_RATE:
1376                                 retval += channel.getCurrentIncomingRateKB();
1377                                 break;
1378                         case AVG_INC_RATE:
1379                                 retval += channel.getAvgIncomingRateKB();
1380                                 break;
1381                         case AVG_LOSS_RATE:
1382                                 retval += channel.getAvgLossRateKB();
1383                                 break;
1384                         case CUR_LOSS_RATE:
1385                                 retval += channel.getCurrentLossRateKB();
1386                                 break;
1387                 default:
1388                         FATAL_ERROR("Connection::getLocalStat Invalid stat type");
1389                 }
1390         }
1391         return retval;
1392 }
1393
1394 u16 Connection::createPeer(Address& sender, MTProtocols protocol, int fd)
1395 {
1396         // Somebody wants to make a new connection
1397
1398         // Get a unique peer id (2 or higher)
1399         session_t peer_id_new = m_next_remote_peer_id;
1400         u16 overflow =  MAX_UDP_PEERS;
1401
1402         /*
1403                 Find an unused peer id
1404         */
1405         MutexAutoLock lock(m_peers_mutex);
1406         bool out_of_ids = false;
1407         for(;;) {
1408                 // Check if exists
1409                 if (m_peers.find(peer_id_new) == m_peers.end())
1410
1411                         break;
1412                 // Check for overflow
1413                 if (peer_id_new == overflow) {
1414                         out_of_ids = true;
1415                         break;
1416                 }
1417                 peer_id_new++;
1418         }
1419
1420         if (out_of_ids) {
1421                 errorstream << getDesc() << " ran out of peer ids" << std::endl;
1422                 return PEER_ID_INEXISTENT;
1423         }
1424
1425         // Create a peer
1426         Peer *peer = 0;
1427         peer = new UDPPeer(peer_id_new, sender, this);
1428
1429         m_peers[peer->id] = peer;
1430         m_peer_ids.push_back(peer->id);
1431
1432         m_next_remote_peer_id = (peer_id_new +1 ) % MAX_UDP_PEERS;
1433
1434         LOG(dout_con << getDesc()
1435                         << "createPeer(): giving peer_id=" << peer_id_new << std::endl);
1436
1437         ConnectionCommand cmd;
1438         SharedBuffer<u8> reply(4);
1439         writeU8(&reply[0], PACKET_TYPE_CONTROL);
1440         writeU8(&reply[1], CONTROLTYPE_SET_PEER_ID);
1441         writeU16(&reply[2], peer_id_new);
1442         cmd.createPeer(peer_id_new,reply);
1443         putCommand(cmd);
1444
1445         // Create peer addition event
1446         ConnectionEvent e;
1447         e.peerAdded(peer_id_new, sender);
1448         putEvent(e);
1449
1450         // We're now talking to a valid peer_id
1451         return peer_id_new;
1452 }
1453
1454 void Connection::PrintInfo(std::ostream &out)
1455 {
1456         m_info_mutex.lock();
1457         out<<getDesc()<<": ";
1458         m_info_mutex.unlock();
1459 }
1460
1461 const std::string Connection::getDesc()
1462 {
1463         return std::string("con(")+
1464                         itos(m_udpSocket.GetHandle())+"/"+itos(m_peer_id)+")";
1465 }
1466
1467 void Connection::DisconnectPeer(session_t peer_id)
1468 {
1469         ConnectionCommand discon;
1470         discon.disconnect_peer(peer_id);
1471         putCommand(discon);
1472 }
1473
1474 void Connection::sendAck(session_t peer_id, u8 channelnum, u16 seqnum)
1475 {
1476         assert(channelnum < CHANNEL_COUNT); // Pre-condition
1477
1478         LOG(dout_con<<getDesc()
1479                         <<" Queuing ACK command to peer_id: " << peer_id <<
1480                         " channel: " << (channelnum & 0xFF) <<
1481                         " seqnum: " << seqnum << std::endl);
1482
1483         ConnectionCommand c;
1484         SharedBuffer<u8> ack(4);
1485         writeU8(&ack[0], PACKET_TYPE_CONTROL);
1486         writeU8(&ack[1], CONTROLTYPE_ACK);
1487         writeU16(&ack[2], seqnum);
1488
1489         c.ack(peer_id, channelnum, ack);
1490         putCommand(c);
1491         m_sendThread->Trigger();
1492 }
1493
1494 UDPPeer* Connection::createServerPeer(Address& address)
1495 {
1496         if (getPeerNoEx(PEER_ID_SERVER) != 0)
1497         {
1498                 throw ConnectionException("Already connected to a server");
1499         }
1500
1501         UDPPeer *peer = new UDPPeer(PEER_ID_SERVER, address, this);
1502
1503         {
1504                 MutexAutoLock lock(m_peers_mutex);
1505                 m_peers[peer->id] = peer;
1506                 m_peer_ids.push_back(peer->id);
1507         }
1508
1509         return peer;
1510 }
1511
1512 } // namespace