-
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathutp_stream.cpp
3343 lines (2855 loc) · 97.9 KB
/
utp_stream.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (c) 2016, Pavel Pimenov
Copyright (c) 2010-2021, Arvid Norberg
Copyright (c) 2015-2018, Alden Torres
Copyright (c) 2016, milesdong
Copyright (c) 2017, Andrei Kurushin
Copyright (c) 2017, Steven Siloti
Copyright (c) 2018, V.G. Bulavintsev
Copyright (c) 2020, Paul-Louis Ageneau
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/config.hpp"
#include "libtorrent/aux_/utp_stream.hpp"
#include "libtorrent/aux_/utp_socket_manager.hpp"
#include "libtorrent/aux_/alloca.hpp"
#include "libtorrent/error.hpp"
#include "libtorrent/random.hpp"
#include "libtorrent/aux_/invariant_check.hpp"
#include "libtorrent/performance_counters.hpp"
#include "libtorrent/io_context.hpp"
#include "libtorrent/aux_/storage_utils.hpp" // for iovec_t
#include <cstdint>
#include <limits>
#if TORRENT_USE_INVARIANT_CHECKS
#include <numeric> // for accumulate
#endif
#if TORRENT_UTP_LOG
#include <cstdarg>
#include <cinttypes> // for PRId64 et.al.
#include "libtorrent/socket_io.hpp"
#endif
namespace libtorrent {
namespace aux {
#if TORRENT_UTP_LOG
static char const* packet_type_names[] = { "ST_DATA", "ST_FIN", "ST_STATE", "ST_RESET", "ST_SYN" };
static char const* socket_state_names[] = { "NONE", "SYN_SENT", "CONNECTED", "FIN_SENT", "ERROR", "DELETE" };
static struct utp_logger
{
FILE* utp_log_file;
std::mutex utp_log_mutex;
utp_logger() : utp_log_file(nullptr) {}
~utp_logger()
{
if (utp_log_file) fclose(utp_log_file);
}
} log_file_holder;
TORRENT_FORMAT(1, 2)
void utp_log(char const* fmt, ...)
{
if (log_file_holder.utp_log_file == nullptr) return;
std::lock_guard<std::mutex> lock(log_file_holder.utp_log_mutex);
static time_point start = clock_type::now();
std::fprintf(log_file_holder.utp_log_file, "[%012" PRId64 "] ", total_microseconds(clock_type::now() - start));
va_list l;
va_start(l, fmt);
vfprintf(log_file_holder.utp_log_file, fmt, l);
va_end(l);
}
bool is_utp_stream_logging() {
return log_file_holder.utp_log_file != nullptr;
}
void set_utp_stream_logging(bool enable) {
if (enable)
{
if (log_file_holder.utp_log_file == nullptr)
{
log_file_holder.utp_log_file = fopen("utp.log", "w+");
}
}
else
{
if (log_file_holder.utp_log_file != nullptr)
{
FILE* f = log_file_holder.utp_log_file;
log_file_holder.utp_log_file = nullptr;
fclose(f);
}
}
}
#define UTP_LOG utp_log
#if TORRENT_VERBOSE_UTP_LOG
#define UTP_LOGV utp_log
#else
#define UTP_LOGV TORRENT_WHILE_0 printf
#endif
#else
#define UTP_LOG(...) do {} while(false)
#define UTP_LOGV(...) do {} while(false)
#endif
enum
{
ACK_MASK = 0xffff,
// if a packet receives more than this number of
// duplicate acks, we'll trigger a fast re-send
dup_ack_limit = 3
};
// compare if lhs is less than rhs, taking wrapping
// into account. if lhs is close to UINT_MAX and rhs
// is close to 0, lhs is assumed to have wrapped and
// considered smaller
bool compare_less_wrap(std::uint32_t lhs
, std::uint32_t rhs, std::uint32_t mask)
{
// distance walking from lhs to rhs, downwards
std::uint32_t dist_down = (lhs - rhs) & mask;
// distance walking from lhs to rhs, upwards
std::uint32_t dist_up = (rhs - lhs) & mask;
// if the distance walking up is shorter, lhs
// is less than rhs. If the distance walking down
// is shorter, then rhs is less than lhs
return dist_up < dist_down;
}
utp_socket_impl::utp_socket_impl(std::uint16_t const recv_id
, std::uint16_t const send_id
, utp_stream* userdata, utp_socket_manager& sm)
: m_sm(sm)
, m_userdata(userdata)
, m_timeout(clock_type::now() + milliseconds(m_sm.connect_timeout()))
, m_send_id(send_id)
, m_recv_id(recv_id)
, m_delay_sample_idx(0)
, m_state(static_cast<std::uint8_t>(state_t::none))
, m_eof(false)
, m_attached(true)
, m_nagle(true)
, m_slow_start(true)
, m_cwnd_full(false)
, m_null_buffers(false)
, m_deferred_ack(false)
, m_subscribe_drained(false)
, m_stalled(false)
, m_confirmed(false)
{
TORRENT_ASSERT((m_recv_id == ((m_send_id + 1) & 0xffff))
|| (m_send_id == ((m_recv_id + 1) & 0xffff)));
m_sm.inc_stats_counter(counters::num_utp_idle);
TORRENT_ASSERT(m_userdata);
m_delay_sample_hist.fill(std::numeric_limits<std::uint32_t>::max());
}
tcp::endpoint utp_socket_impl::remote_endpoint(error_code& ec) const
{
if (state() == state_t::none)
ec = boost::asio::error::not_connected;
else
TORRENT_ASSERT(m_remote_address != address_v4::any());
return {m_remote_address, m_port};
}
packet_ptr utp_socket_impl::acquire_packet(int const allocate)
{
return m_sm.acquire_packet(allocate);
}
void utp_socket_impl::release_packet(packet_ptr p)
{
m_sm.release_packet(std::move(p));
}
void utp_socket_impl::abort()
{
m_error = boost::asio::error::connection_aborted;
set_state(utp_socket_impl::state_t::error_wait);
test_socket_state();
}
bool utp_socket_impl::match(udp::endpoint const& ep, std::uint16_t const id) const
{
return m_recv_id == id
&& m_port == ep.port()
&& m_remote_address == ep.address();
}
udp::endpoint utp_socket_impl::remote_endpoint() const
{
return {m_remote_address, m_port};
}
void utp_socket_impl::send_ack()
{
TORRENT_ASSERT(m_deferred_ack);
m_deferred_ack = false;
send_pkt(utp_socket_impl::pkt_ack);
}
void utp_socket_impl::socket_drained()
{
m_subscribe_drained = false;
// at this point, we know we won't receive any
// more packets this round. So, we may want to
// call the receive callback function to
// let the user consume it
maybe_trigger_receive_callback();
maybe_trigger_send_callback();
}
void utp_socket_impl::update_mtu_limits()
{
INVARIANT_CHECK;
if (m_mtu_floor > m_mtu_ceiling)
{
// this is the case where we drop an MTU probe once we're in steady
// state. Assume the probe was lost by chance, and don't decrement the
// ceiling. We're still restarting the Path MTU discovery, so if the MTU
// did in fact chance, we'll be notified again, when not in steady
// state.
m_mtu_ceiling = m_mtu_floor;
// the path MTU may have changed. Perform another search
// dont' start all the way from start, just half way down.
m_mtu_floor = ((TORRENT_INET_MIN_MTU - TORRENT_IPV4_HEADER - TORRENT_UDP_HEADER) + m_mtu_ceiling) / 2;
UTP_LOGV("%8p: reducing MTU floor\n", static_cast<void*>(this));
}
m_mtu = (m_mtu_floor + m_mtu_ceiling) / 2;
if ((m_cwnd >> 16) < m_mtu) m_cwnd = std::int64_t(m_mtu) * (1 << 16);
UTP_LOGV("%8p: updating MTU to: %d [%d, %d]\n"
, static_cast<void*>(this), m_mtu, m_mtu_floor, m_mtu_ceiling);
// clear the mtu probe sequence number since
// it was either dropped or acked
m_mtu_seq = 0;
}
int utp_stream::send_delay() const
{
return m_impl ? m_impl->send_delay() : 0;
}
int utp_stream::recv_delay() const
{
return m_impl ? m_impl->recv_delay() : 0;
}
utp_stream::utp_stream(io_context& io_context)
: m_io_service(io_context)
, m_impl(nullptr)
, m_open(false)
{
}
utp_socket_impl* utp_stream::get_impl()
{
return m_impl;
}
void utp_stream::set_close_reason(close_reason_t code)
{
if (!m_impl) return;
m_impl->set_close_reason(code);
}
close_reason_t utp_stream::get_close_reason() const
{
return m_incoming_close_reason;
}
void utp_stream::close()
{
if (!m_impl) return;
if (!m_impl->destroy())
{
if (!m_impl) return;
m_impl->detach();
m_impl = nullptr;
}
}
std::size_t utp_stream::available() const
{
return m_impl ? m_impl->available() : 0;
}
utp_stream::endpoint_type utp_stream::remote_endpoint(error_code& ec) const
{
if (!m_impl)
{
ec = boost::asio::error::not_connected;
return {};
}
return m_impl->remote_endpoint(ec);
}
utp_stream::endpoint_type utp_stream::local_endpoint(error_code& ec) const
{
if (m_impl == nullptr)
{
ec = boost::asio::error::not_connected;
return {};
}
auto s = m_impl->m_sock.lock();
if (!s)
{
ec = boost::asio::error::not_connected;
return {};
}
udp::endpoint ep = s->get_local_endpoint();
return {ep.address(), ep.port()};
}
utp_stream::utp_stream(utp_stream&& rhs) noexcept
: m_io_service(rhs.m_io_service)
, m_impl(rhs.m_impl)
, m_open(rhs.m_open)
{
if (&rhs == this) return;
rhs.m_open = false;
rhs.m_impl = nullptr;
if (m_impl) m_impl->set_userdata(this);
}
utp_stream::~utp_stream()
{
if (m_impl)
{
UTP_LOGV("%8p: utp_stream destructed\n", static_cast<void*>(m_impl));
m_impl->destroy();
m_impl->detach();
m_impl = nullptr;
}
}
void utp_stream::set_impl(utp_socket_impl* impl)
{
TORRENT_ASSERT(m_impl == nullptr);
TORRENT_ASSERT(!m_open);
m_impl = impl;
m_open = true;
}
int utp_stream::read_buffer_size() const
{
TORRENT_ASSERT(m_impl);
return m_impl->receive_buffer_size();
}
void utp_stream::on_close_reason(utp_stream* s, close_reason_t reason)
{
// it's possible the socket has been unlinked already, in which case m_impl
// will be nullptr
if (s->m_impl)
s->m_incoming_close_reason = reason;
}
void utp_stream::on_read(utp_stream* s, std::size_t const bytes_transferred
, error_code const& ec, bool const shutdown)
{
UTP_LOGV("%8p: calling read handler read:%d ec:%s shutdown:%d\n", static_cast<void*>(s->m_impl)
, int(bytes_transferred), ec.message().c_str(), shutdown);
TORRENT_ASSERT(s->m_read_handler);
TORRENT_ASSERT(bytes_transferred > 0 || ec || s->m_impl->null_buffers());
post(s->m_io_service, std::bind<void>(std::move(s->m_read_handler), ec, bytes_transferred));
s->m_read_handler = nullptr;
if (shutdown && s->m_impl)
{
TORRENT_ASSERT(ec);
s->m_impl->detach();
s->m_impl = nullptr;
}
}
void utp_stream::on_write(utp_stream* s, std::size_t const bytes_transferred
, error_code const& ec, bool const shutdown)
{
UTP_LOGV("%8p: calling write handler written:%d ec:%s shutdown:%d\n"
, static_cast<void*>(s->m_impl)
, int(bytes_transferred), ec.message().c_str(), shutdown);
TORRENT_ASSERT(s->m_write_handler);
TORRENT_ASSERT(bytes_transferred > 0 || ec);
post(s->m_io_service, std::bind<void>(std::move(s->m_write_handler), ec, bytes_transferred));
s->m_write_handler = nullptr;
if (shutdown && s->m_impl)
{
TORRENT_ASSERT(ec);
s->m_impl->detach();
s->m_impl = nullptr;
}
}
void utp_stream::on_connect(utp_stream* s, error_code const& ec, bool const shutdown)
{
TORRENT_ASSERT(s);
UTP_LOGV("%8p: calling connect handler ec:%s shutdown:%d\n"
, static_cast<void*>(s->m_impl), ec.message().c_str(), shutdown);
TORRENT_ASSERT(s->m_connect_handler);
post(s->m_io_service, std::bind<void>(std::move(s->m_connect_handler), ec));
s->m_connect_handler = nullptr;
if (shutdown && s->m_impl)
{
TORRENT_ASSERT(ec);
s->m_impl->detach();
s->m_impl = nullptr;
}
}
void utp_stream::add_read_buffer(void* buf, int const len)
{
TORRENT_ASSERT(m_impl);
TORRENT_ASSERT(len < INT_MAX);
TORRENT_ASSERT(len > 0);
TORRENT_ASSERT(buf);
m_impl->add_read_buffer(buf, len);
}
// this is the wrapper to add a user provided write buffer to the
// utp_socket_impl. It makes sure the m_write_buffer_size is kept
// up to date
void utp_stream::add_write_buffer(void const* buf, int const len)
{
TORRENT_ASSERT(m_impl);
TORRENT_ASSERT(len < INT_MAX);
TORRENT_ASSERT(len > 0);
TORRENT_ASSERT(buf);
m_impl->add_write_buffer(buf, len);
}
// this is called when all user provided read buffers have been added
// and it's time to execute the async operation. The first thing we
// do is to copy any data stored in m_receive_buffer into the user
// provided buffer. This might be enough to in turn trigger the read
// handler immediately.
void utp_stream::issue_read()
{
m_impl->issue_read();
}
std::size_t utp_stream::read_some(bool const clear_buffers)
{
return m_impl->read_some(clear_buffers);
}
// Warning: this is always non-blocking, it only tries to send
// immediately if there is some space in the congestion window.
std::size_t utp_stream::write_some(bool const clear_buffers)
{
return m_impl->write_some(clear_buffers);
}
// this is called when all user provided write buffers have been
// added. Start trying to send packets with the payload immediately.
void utp_stream::issue_write()
{
m_impl->issue_write();
}
void utp_stream::do_connect(tcp::endpoint const& ep)
{
m_impl->do_connect(ep);
}
// =========== utp_socket_impl ============
void utp_socket_impl::add_read_buffer(void* buf, int const len)
{
UTP_LOGV("%8p: add_read_buffer %d bytes\n", static_cast<void*>(this), len);
if (len <= 0) return;
m_read_buffer.emplace_back(reinterpret_cast<char*>(buf), len);
m_read_buffer_size += len;
}
void utp_socket_impl::add_write_buffer(void const* buf, int const len)
{
UTP_LOGV("%8p: add_write_buffer %d bytes\n", static_cast<void const*>(this), len);
if (len <= 0) return;
#if TORRENT_USE_ASSERTS
std::ptrdiff_t write_buffer_size = 0;
for (auto const& i : m_write_buffer)
{
TORRENT_ASSERT(std::numeric_limits<int>::max() - i.size() > write_buffer_size);
write_buffer_size += i.size();
}
TORRENT_ASSERT(m_write_buffer_size == write_buffer_size);
#endif
m_write_buffer.emplace_back(reinterpret_cast<char const*>(buf), len);
m_write_buffer_size += len;
#if TORRENT_USE_ASSERTS
write_buffer_size = 0;
for (auto const& i : m_write_buffer)
{
TORRENT_ASSERT(std::numeric_limits<int>::max() - i.size() > write_buffer_size);
write_buffer_size += i.size();
}
TORRENT_ASSERT(m_write_buffer_size == write_buffer_size);
#endif
}
void utp_socket_impl::issue_read()
{
TORRENT_ASSERT(m_userdata);
TORRENT_ASSERT(!m_read_handler);
m_null_buffers = m_read_buffer_size == 0;
m_read_handler = true;
if (test_socket_state()) return;
UTP_LOGV("%8p: new read handler. %d bytes in buffer\n"
, static_cast<void*>(this), m_receive_buffer_size);
// so, the client wants to read. If we already
// have some data in the read buffer, move it into the
// client's buffer right away
m_read += int(read_some(false));
maybe_trigger_receive_callback();
}
std::size_t utp_socket_impl::read_some(bool const clear_buffers)
{
TORRENT_ASSERT(m_receive_buffer_size >= 0);
if (m_receive_buffer_size <= 0)
{
if (clear_buffers)
{
m_read_buffer_size = 0;
m_read_buffer.clear();
}
return 0;
}
auto target = m_read_buffer.begin();
std::size_t ret = 0;
int pop_packets = 0;
for (auto i = m_receive_buffer.begin()
, end(m_receive_buffer.end()); i != end;)
{
if (target == m_read_buffer.end())
{
UTP_LOGV(" No more target buffers: %d bytes left in buffer\n"
, m_receive_buffer_size);
TORRENT_ASSERT(m_read_buffer.empty());
break;
}
#if TORRENT_USE_INVARIANT_CHECKS
check_receive_buffers();
#endif
packet* const p = i->get();
// the number of bytes to copy is added to the 16 bit header field
// p->header_size, so we have to make sure we stay within that limit
int const to_copy = static_cast<int>(std::min({
std::ptrdiff_t(p->size - p->header_size)
, target->size()
, std::ptrdiff_t(std::numeric_limits<std::uint16_t>::max() - p->header_size)}));
TORRENT_ASSERT(to_copy >= 0);
std::memcpy(target->data(), p->buf + p->header_size, std::size_t(to_copy));
ret += std::size_t(to_copy);
TORRENT_ASSERT(target->size() >= to_copy);
*target = target->subspan(to_copy);
TORRENT_ASSERT(m_receive_buffer_size >= to_copy);
m_receive_buffer_size -= to_copy;
TORRENT_ASSERT(m_read_buffer_size >= to_copy);
m_read_buffer_size -= to_copy;
p->header_size += std::uint16_t(to_copy);
if (target->size() == 0) target = m_read_buffer.erase(target);
#if TORRENT_USE_INVARIANT_CHECKS
check_receive_buffers();
#endif
// Consumed entire packet
if (p->header_size == p->size)
{
release_packet(std::move(*i));
i->reset();
++pop_packets;
++i;
}
TORRENT_ASSERT(m_receive_buffer_size >= 0);
if (m_receive_buffer_size <= 0)
{
UTP_LOGV("%8p: Didn't fill entire target: %d bytes left in buffer\n"
, static_cast<void*>(this), m_receive_buffer_size);
break;
}
}
// remove the packets from the receive_buffer that we already copied over
// and freed
m_receive_buffer.erase(m_receive_buffer.begin()
, m_receive_buffer.begin() + pop_packets);
// we exited either because we ran out of bytes to copy
// or because we ran out of space to copy the bytes to
TORRENT_ASSERT(m_receive_buffer_size == 0 || m_read_buffer.empty());
UTP_LOGV("%8p: %d packets moved from buffer to user space (%d bytes)\n"
, static_cast<void*>(this), pop_packets, int(ret));
if (clear_buffers)
{
m_read_buffer_size = 0;
m_read_buffer.clear();
}
TORRENT_ASSERT(ret > 0 || m_null_buffers);
return ret;
}
void utp_socket_impl::issue_write()
{
UTP_LOGV("%8p: new write handler. %d bytes to write\n"
, static_cast<void*>(this), m_write_buffer_size);
TORRENT_ASSERT(m_write_buffer_size > 0);
TORRENT_ASSERT(m_write_handler == false);
TORRENT_ASSERT(m_userdata);
m_write_handler = true;
m_written = 0;
if (test_socket_state()) return;
// try to write. send_pkt returns false if there's
// no more payload to send or if the congestion window
// is full and we can't send more packets right now
while (send_pkt());
maybe_trigger_send_callback();
}
std::size_t utp_socket_impl::write_some(bool const clear_buffers)
{
m_written = 0;
// try to write if the congestion window allows it
while (send_pkt());
if (clear_buffers)
{
m_write_buffer_size = 0;
m_write_buffer.clear();
}
return std::size_t(m_written);
}
void utp_socket_impl::do_connect(tcp::endpoint const& ep)
{
int const mtu = m_sm.mtu_for_dest(ep.address());
init_mtu(mtu);
TORRENT_ASSERT(m_connect_handler == false);
m_remote_address = ep.address();
m_port = ep.port();
m_connect_handler = true;
if (test_socket_state()) return;
send_syn();
}
utp_socket_impl::~utp_socket_impl()
{
INVARIANT_CHECK;
TORRENT_ASSERT(!m_attached);
TORRENT_ASSERT(!m_deferred_ack);
m_sm.inc_stats_counter(counters::num_utp_idle + m_state, -1);
UTP_LOGV("%8p: destroying utp socket state\n", static_cast<void*>(this));
// free any buffers we're holding
for (std::uint16_t i = std::uint16_t(m_inbuf.cursor()), end((m_inbuf.cursor()
+ m_inbuf.capacity()) & ACK_MASK);
i != end; i = (i + 1) & ACK_MASK)
{
packet_ptr p = m_inbuf.remove(i);
release_packet(std::move(p));
}
for (std::uint16_t i = std::uint16_t(m_outbuf.cursor()), end((m_outbuf.cursor()
+ m_outbuf.capacity()) & ACK_MASK);
i != end; i = (i + 1) & ACK_MASK)
{
packet_ptr p = m_outbuf.remove(i);
release_packet(std::move(p));
}
for (auto& p : m_receive_buffer)
release_packet(std::move(p));
release_packet(std::move(m_nagle_packet));
m_nagle_packet.reset();
}
bool utp_socket_impl::should_delete() const
{
INVARIANT_CHECK;
// if the socket state is not attached anymore we're free
// to delete it from the client's point of view. The other
// endpoint however might still need to be told that we're
// closing the socket. Only delete the state if we're not
// attached and we're in a state where the other end doesn't
// expect the socket to still be alive
// when m_stalled is true, it means the socket manager has a
// pointer to this socket, waiting for the UDP socket to
// become writable again. We have to wait for that, so that
// the pointer is removed from that queue. Otherwise we would
// leave a dangling pointer in the socket manager
bool ret = (m_state >= static_cast<std::uint8_t>(state_t::error_wait) || state() == state_t::none)
&& !m_attached && !m_stalled;
if (ret)
{
UTP_LOGV("%8p: should_delete() = true\n", static_cast<void const*>(this));
}
return ret;
}
void utp_socket_impl::maybe_trigger_receive_callback()
{
INVARIANT_CHECK;
if (m_read_handler == false) return;
// nothing has been read or there's no outstanding read operation
if (m_null_buffers && m_receive_buffer_size == 0) return;
else if (!m_null_buffers && m_read == 0) return;
UTP_LOGV("%8p: calling read handler read:%d\n", static_cast<void*>(this), m_read);
m_read_handler = false;
utp_stream::on_read(m_userdata, aux::numeric_cast<std::size_t>(m_read), m_error, false);
m_read = 0;
m_read_buffer_size = 0;
m_read_buffer.clear();
}
void utp_socket_impl::maybe_trigger_send_callback()
{
INVARIANT_CHECK;
// nothing has been written or there's no outstanding write operation
if (m_written == 0 || m_write_handler == false) return;
UTP_LOGV("%8p: calling write handler written:%d\n", static_cast<void*>(this), m_written);
m_write_handler = false;
utp_stream::on_write(m_userdata, aux::numeric_cast<std::size_t>(m_written), m_error, false);
m_written = 0;
m_write_buffer_size = 0;
m_write_buffer.clear();
}
void utp_socket_impl::set_close_reason(close_reason_t code)
{
#if TORRENT_UTP_LOG
UTP_LOGV("%8p: set_close_reason: %d\n"
, static_cast<void*>(this), static_cast<int>(m_close_reason));
#endif
m_close_reason = code;
}
bool utp_socket_impl::destroy()
{
INVARIANT_CHECK;
#if TORRENT_UTP_LOG
UTP_LOGV("%8p: destroy state:%s (close-reason: %d)\n"
, static_cast<void*>(this), socket_state_names[m_state], int(m_close_reason));
#endif
if (m_userdata == nullptr) return false;
if (state() == state_t::connected)
send_fin();
bool cancelled = cancel_handlers(boost::asio::error::operation_aborted, true);
m_userdata = nullptr;
m_read_buffer.clear();
m_read_buffer_size = 0;
m_write_buffer.clear();
m_write_buffer_size = 0;
if ((state() == state_t::error_wait
|| state() == state_t::none
|| state() == state_t::syn_sent) && cancelled)
{
set_state(state_t::deleting);
#if TORRENT_UTP_LOG
UTP_LOGV("%8p: state:%s\n", static_cast<void*>(this), socket_state_names[m_state]);
#endif
}
return cancelled;
// #error our end is closing. Wait for everything to be acked
}
void utp_socket_impl::detach()
{
INVARIANT_CHECK;
UTP_LOGV("%8p: detach()\n", static_cast<void*>(this));
m_attached = false;
}
void utp_socket_impl::send_syn()
{
INVARIANT_CHECK;
m_seq_nr = std::uint16_t(random(0xffff));
m_acked_seq_nr = (m_seq_nr - 1) & ACK_MASK;
m_loss_seq_nr = m_acked_seq_nr;
m_ack_nr = 0;
m_fast_resend_seq_nr = m_seq_nr;
packet_ptr p = acquire_packet(sizeof(utp_header));
p->size = sizeof(utp_header);
p->header_size = sizeof(utp_header);
p->num_transmissions = 0;
p->mtu_probe = false;
#if TORRENT_USE_ASSERTS
p->num_fast_resend = 0;
#endif
p->need_resend = false;
auto* h = reinterpret_cast<utp_header*>(p->buf);
h->type_ver = (ST_SYN << 4) | 1;
h->extension = utp_no_extension;
// using recv_id here is intentional! This is an odd
// thing in uTP. The syn packet is sent with the connection
// ID that it expects to receive the syn ack on. All
// subsequent connection IDs will be this plus one.
h->connection_id = m_recv_id;
h->timestamp_difference_microseconds = m_reply_micro;
h->wnd_size = 0;
h->seq_nr = m_seq_nr;
h->ack_nr = 0;
time_point const now = clock_type::now();
p->send_time = now;
h->timestamp_microseconds = std::uint32_t(
total_microseconds(now.time_since_epoch()) & 0xffffffff);
#if TORRENT_UTP_LOG
UTP_LOGV("%8p: send_syn seq_nr:%d id:%d target:%s\n"
, static_cast<void*>(this), int(m_seq_nr), int(m_recv_id)
, print_endpoint(udp::endpoint(m_remote_address, m_port)).c_str());
#endif
error_code ec;
m_sm.send_packet(m_sock, udp::endpoint(m_remote_address, m_port)
, reinterpret_cast<char const*>(h) , sizeof(utp_header), ec);
if (ec == error::would_block || ec == error::try_again)
{
#if TORRENT_UTP_LOG
UTP_LOGV("%8p: socket stalled\n", static_cast<void*>(this));
#endif
if (!m_stalled)
{
m_stalled = true;
m_sm.subscribe_writable(this);
}
}
else if (ec)
{
release_packet(std::move(p));
m_error = ec;
set_state(state_t::error_wait);
test_socket_state();
return;
}
if (!m_stalled)
++p->num_transmissions;
TORRENT_ASSERT(!m_outbuf.at(m_seq_nr));
TORRENT_ASSERT(h->seq_nr == m_seq_nr);
TORRENT_ASSERT(p->buf == reinterpret_cast<std::uint8_t*>(h));
m_outbuf.insert(m_seq_nr, std::move(p));
m_seq_nr = (m_seq_nr + 1) & ACK_MASK;
TORRENT_ASSERT(!m_error);
set_state(state_t::syn_sent);
#if TORRENT_UTP_LOG
UTP_LOGV("%8p: state:%s\n", static_cast<void*>(this), socket_state_names[m_state]);
#endif
}
// if a send ever failed with EWOULDBLOCK, we
// subscribe to the udp socket and will be
// signalled with this function.
void utp_socket_impl::writable()
{
#if TORRENT_UTP_LOG
UTP_LOGV("%8p: writable\n", static_cast<void*>(this));
#endif
TORRENT_ASSERT(m_stalled);
m_stalled = false;
if (should_delete()) return;
while(send_pkt());
maybe_trigger_send_callback();
}
void utp_socket_impl::send_fin()
{
INVARIANT_CHECK;
send_pkt(pkt_fin);
// unless there was an error, we're now
// in FIN-SENT state
if (!m_error)
set_state(state_t::fin_sent);
#if TORRENT_UTP_LOG
UTP_LOGV("%8p: state:%s\n", static_cast<void*>(this), socket_state_names[m_state]);
#endif
}
void utp_socket_impl::send_reset(utp_header const* ph)
{
INVARIANT_CHECK;
utp_header h;
h.type_ver = (ST_RESET << 4) | 1;
h.extension = utp_no_extension;
h.connection_id = m_send_id;
h.timestamp_difference_microseconds = m_reply_micro;
h.wnd_size = 0;
h.seq_nr = std::uint16_t(random(0xffff));
h.ack_nr = ph->seq_nr;
time_point const now = clock_type::now();
h.timestamp_microseconds = std::uint32_t(
total_microseconds(now.time_since_epoch()) & 0xffffffff);
UTP_LOGV("%8p: send_reset seq_nr:%d id:%d ack_nr:%d\n"
, static_cast<void*>(this), int(h.seq_nr), int(m_send_id), int(ph->seq_nr));