-
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathsession_impl.cpp
7368 lines (6404 loc) · 218 KB
/
session_impl.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) 2003, Magnus Jonsson
Copyright (c) 2015, Thomas
Copyright (c) 2006-2022, Arvid Norberg
Copyright (c) 2009, Andrew Resch
Copyright (c) 2014-2020, Steven Siloti
Copyright (c) 2015-2021, Alden Torres
Copyright (c) 2015, Mikhail Titov
Copyright (c) 2015, Thomas Yuan
Copyright (c) 2016-2017, Andrei Kurushin
Copyright (c) 2016, Falcosc
Copyright (c) 2016-2017, Pavel Pimenov
Copyright (c) 2017, sledgehammer_999
Copyright (c) 2018, Xiyue Deng
Copyright (c) 2020, Fonic
Copyright (c) 2020, Paul-Louis Ageneau
Copyright (c) 2022, Vladimir Golovnev (glassez)
Copyright (c) 2022, thrnz
Copyright (c) 2023, Joris Carrier
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 <ctime>
#include <algorithm>
#include <cctype>
#include <cstdio> // for snprintf
#include <cinttypes> // for PRId64 et.al.
#include <functional>
#include <type_traits>
#include <numeric> // for accumulate
#if TORRENT_USE_INVARIANT_CHECKS
#include <unordered_set>
#endif
#include "libtorrent/aux_/disable_warnings_push.hpp"
#include <boost/asio/ts/internet.hpp>
#include <boost/asio/ts/executor.hpp>
#include "libtorrent/aux_/disable_warnings_pop.hpp"
#include "libtorrent/ssl.hpp"
#include "libtorrent/peer_id.hpp"
#include "libtorrent/torrent_info.hpp"
#include "libtorrent/tracker_manager.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/hasher.hpp"
#include "libtorrent/entry.hpp"
#include "libtorrent/session.hpp"
#include "libtorrent/fingerprint.hpp"
#include "libtorrent/alert_types.hpp"
#include "libtorrent/aux_/invariant_check.hpp"
#include "libtorrent/bt_peer_connection.hpp"
#include "libtorrent/peer_connection_handle.hpp"
#include "libtorrent/ip_filter.hpp"
#include "libtorrent/socket.hpp"
#include "libtorrent/aux_/session_impl.hpp"
#ifndef TORRENT_DISABLE_DHT
#include "libtorrent/kademlia/dht_tracker.hpp"
#include "libtorrent/kademlia/types.hpp"
#include "libtorrent/kademlia/node_entry.hpp"
#endif
#include "libtorrent/enum_net.hpp"
#include "libtorrent/utf8.hpp"
#include "libtorrent/upnp.hpp"
#include "libtorrent/natpmp.hpp"
#include "libtorrent/lsd.hpp"
#include "libtorrent/aux_/instantiate_connection.hpp"
#include "libtorrent/peer_info.hpp"
#include "libtorrent/random.hpp"
#include "libtorrent/magnet_uri.hpp"
#include "libtorrent/aux_/session_settings.hpp"
#include "libtorrent/torrent_peer.hpp"
#include "libtorrent/torrent_handle.hpp"
#include "libtorrent/choker.hpp"
#include "libtorrent/error.hpp"
#include "libtorrent/platform_util.hpp"
#include "libtorrent/aux_/bind_to_device.hpp"
#include "libtorrent/hex.hpp" // to_hex, from_hex
#include "libtorrent/aux_/scope_end.hpp"
#include "libtorrent/aux_/set_socket_buffer.hpp"
#include "libtorrent/aux_/generate_peer_id.hpp"
#include "libtorrent/aux_/ffs.hpp"
#include "libtorrent/aux_/array.hpp"
#include "libtorrent/aux_/set_traffic_class.hpp"
#ifndef TORRENT_DISABLE_LOGGING
#include "libtorrent/socket_io.hpp"
// for logging stat layout
#include "libtorrent/stat.hpp"
#include <cstdarg> // for va_list
// for logging the size of DHT structures
#ifndef TORRENT_DISABLE_DHT
#include <libtorrent/kademlia/find_data.hpp>
#include <libtorrent/kademlia/refresh.hpp>
#include <libtorrent/kademlia/node.hpp>
#include <libtorrent/kademlia/observer.hpp>
#include <libtorrent/kademlia/item.hpp>
#endif // TORRENT_DISABLE_DHT
#include "libtorrent/http_tracker_connection.hpp"
#include "libtorrent/udp_tracker_connection.hpp"
#endif // TORRENT_DISABLE_LOGGING
#ifdef TORRENT_USE_LIBGCRYPT
#if GCRYPT_VERSION_NUMBER < 0x010600
extern "C" {
GCRY_THREAD_OPTION_PTHREAD_IMPL;
}
#endif
namespace {
// libgcrypt requires this to initialize the library
struct gcrypt_setup
{
gcrypt_setup()
{
gcry_check_version(nullptr);
#if GCRYPT_VERSION_NUMBER < 0x010600
gcry_error_t e = gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
if (e != 0) std::fprintf(stderr, "libcrypt ERROR: %s\n", gcry_strerror(e));
e = gcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0);
if (e != 0) std::fprintf(stderr, "initialization finished error: %s\n", gcry_strerror(e));
#endif
}
} gcrypt_global_constructor;
}
#endif // TORRENT_USE_LIBGCRYPT
#ifdef TORRENT_USE_OPENSSL
#ifdef TORRENT_WINDOWS
#include <wincrypt.h>
#endif
#endif // TORRENT_USE_OPENSSL
#ifdef TORRENT_WINDOWS
// for ERROR_SEM_TIMEOUT
#include <winerror.h>
#endif
using namespace std::placeholders;
#ifdef BOOST_NO_EXCEPTIONS
namespace boost {
void throw_exception(std::exception const& e) { std::abort(); }
}
#endif
namespace libtorrent {
#if defined TORRENT_ASIO_DEBUGGING
std::map<std::string, async_t> _async_ops;
std::deque<wakeup_t> _wakeups;
int _async_ops_nthreads = 0;
std::mutex _async_ops_mutex;
std::map<int, handler_alloc_t> _handler_storage;
std::mutex _handler_storage_mutex;
bool _handler_logger_registered = false;
#endif
namespace aux {
constexpr listen_socket_flags_t listen_socket_t::accept_incoming;
constexpr listen_socket_flags_t listen_socket_t::local_network;
constexpr listen_socket_flags_t listen_socket_t::was_expanded;
constexpr listen_socket_flags_t listen_socket_t::proxy;
constexpr ip_source_t session_interface::source_dht;
constexpr ip_source_t session_interface::source_peer;
constexpr ip_source_t session_interface::source_tracker;
constexpr ip_source_t session_interface::source_router;
void apply_deprecated_dht_settings(settings_pack& sett, bdecode_node const& s)
{
bdecode_node val;
val = s.dict_find_int("max_peers_reply");
if (val) sett.set_int(settings_pack::dht_max_peers_reply, int(val.int_value()));
val = s.dict_find_int("search_branching");
if (val) sett.set_int(settings_pack::dht_search_branching, int(val.int_value()));
val = s.dict_find_int("max_fail_count");
if (val) sett.set_int(settings_pack::dht_max_fail_count, int(val.int_value()));
val = s.dict_find_int("max_torrents");
if (val) sett.set_int(settings_pack::dht_max_torrents, int(val.int_value()));
val = s.dict_find_int("max_dht_items");
if (val) sett.set_int(settings_pack::dht_max_dht_items, int(val.int_value()));
val = s.dict_find_int("max_peers");
if (val) sett.set_int(settings_pack::dht_max_peers, int(val.int_value()));
val = s.dict_find_int("max_torrent_search_reply");
if (val) sett.set_int(settings_pack::dht_max_torrent_search_reply, int(val.int_value()));
val = s.dict_find_int("restrict_routing_ips");
if (val) sett.set_bool(settings_pack::dht_restrict_routing_ips, (val.int_value() != 0));
val = s.dict_find_int("restrict_search_ips");
if (val) sett.set_bool(settings_pack::dht_restrict_search_ips, (val.int_value() != 0));
val = s.dict_find_int("extended_routing_table");
if (val) sett.set_bool(settings_pack::dht_extended_routing_table, (val.int_value() != 0));
val = s.dict_find_int("aggressive_lookups");
if (val) sett.set_bool(settings_pack::dht_aggressive_lookups, (val.int_value() != 0));
val = s.dict_find_int("privacy_lookups");
if (val) sett.set_bool(settings_pack::dht_privacy_lookups, (val.int_value() != 0));
val = s.dict_find_int("enforce_node_id");
if (val) sett.set_bool(settings_pack::dht_enforce_node_id, (val.int_value() != 0));
val = s.dict_find_int("ignore_dark_internet");
if (val) sett.set_bool(settings_pack::dht_ignore_dark_internet, (val.int_value() != 0));
val = s.dict_find_int("block_timeout");
if (val) sett.set_int(settings_pack::dht_block_timeout, int(val.int_value()));
val = s.dict_find_int("block_ratelimit");
if (val) sett.set_int(settings_pack::dht_block_ratelimit, int(val.int_value()));
val = s.dict_find_int("read_only");
if (val) sett.set_bool(settings_pack::dht_read_only, (val.int_value() != 0));
val = s.dict_find_int("item_lifetime");
if (val) sett.set_int(settings_pack::dht_item_lifetime, int(val.int_value()));
}
std::vector<std::shared_ptr<listen_socket_t>>::iterator partition_listen_sockets(
std::vector<listen_endpoint_t>& eps
, std::vector<std::shared_ptr<listen_socket_t>>& sockets)
{
return std::partition(sockets.begin(), sockets.end()
, [&eps](std::shared_ptr<listen_socket_t> const& sock)
{
auto match = std::find_if(eps.begin(), eps.end()
, [&sock](listen_endpoint_t const& ep)
{
return ep.ssl == sock->ssl
&& ep.port == sock->original_port
&& ep.device == sock->device
&& ep.flags == sock->flags
&& ep.addr == sock->local_endpoint.address();
});
if (match != eps.end())
{
// remove the matched endpoint so that another socket can't match it
// this also signals to the caller that it doesn't need to create a
// socket for the endpoint
eps.erase(match);
return true;
}
else
{
return false;
}
});
}
// To comply with BEP 45 multi homed clients must run separate DHT nodes
// on each interface they use to talk to the DHT. This is enforced
// by prohibiting creating a listen socket on [::] and 0.0.0.0. Instead the list of
// interfaces is enumerated and sockets are created for each of them.
void expand_unspecified_address(span<ip_interface const> const ifs
, span<ip_route const> const routes
, std::vector<listen_endpoint_t>& eps)
{
auto unspecified_begin = std::partition(eps.begin(), eps.end()
, [](listen_endpoint_t const& ep) { return !ep.addr.is_unspecified(); });
std::vector<listen_endpoint_t> unspecified_eps(unspecified_begin, eps.end());
eps.erase(unspecified_begin, eps.end());
for (auto const& uep : unspecified_eps)
{
bool const v4 = uep.addr.is_v4();
for (auto const& ipface : ifs)
{
if (!ipface.preferred)
continue;
if (ipface.interface_address.is_v4() != v4)
continue;
if (!uep.device.empty() && uep.device != ipface.name)
continue;
if (std::any_of(eps.begin(), eps.end(), [&](listen_endpoint_t const& e)
{
// ignore device name because we don't want to create
// duplicates if the user explicitly configured an address
// without a device name
return e.addr == ipface.interface_address
&& e.port == uep.port
&& e.ssl == uep.ssl;
}))
{
continue;
}
// ignore interfaces that are down
if (ipface.state != if_state::up && ipface.state != if_state::unknown)
continue;
if (!(ipface.flags & if_flags::up))
continue;
// we assume this listen_socket_t is local-network under some
// conditions, meaning we won't announce it to internet trackers
// if "routes" does not contain a single route to the internet,
// we don't use the last case. On MacOS, we can be notified of
// network changes *before* the routing table is updated
bool const local
= ipface.interface_address.is_loopback()
|| is_link_local(ipface.interface_address)
|| (ipface.flags & if_flags::loopback)
|| (!is_global(ipface.interface_address)
&& !(ipface.flags & if_flags::pointopoint)
&& has_any_internet_route(routes)
&& !has_internet_route(ipface.name, family(ipface.interface_address), routes));
eps.emplace_back(ipface.interface_address, uep.port, uep.device
, uep.ssl, uep.flags | listen_socket_t::was_expanded
| (local ? listen_socket_t::local_network : listen_socket_flags_t{}));
}
}
}
void expand_devices(span<ip_interface const> const ifs
, std::vector<listen_endpoint_t>& eps)
{
for (auto& ep : eps)
{
auto const iface = ep.device.empty()
? std::find_if(ifs.begin(), ifs.end(), [&](ip_interface const& ipface)
{
return match_addr_mask(ipface.interface_address, ep.addr, ipface.netmask);
})
: std::find_if(ifs.begin(), ifs.end(), [&](ip_interface const& ipface)
{
return ipface.name == ep.device
&& match_addr_mask(ipface.interface_address, ep.addr, ipface.netmask);
});
if (iface == ifs.end())
{
// we can't find which device this is for, just assume we can't
// reach anything on it
ep.netmask = build_netmask(0, ep.addr.is_v4() ? AF_INET : AF_INET6);
continue;
}
ep.netmask = iface->netmask;
ep.device = iface->name;
}
}
bool listen_socket_t::can_route(address const& addr) const
{
// if this is a proxy, we assume it can reach everything
if (flags & proxy) return true;
if (is_v4(local_endpoint) != addr.is_v4()) return false;
if (local_endpoint.address().is_v6()
&& local_endpoint.address().to_v6().scope_id() != addr.to_v6().scope_id())
return false;
if (local_endpoint.address() == addr) return true;
if (local_endpoint.address().is_unspecified()) return true;
if (match_addr_mask(addr, local_endpoint.address(), netmask)) return true;
return !(flags & local_network);
}
void session_impl::init_peer_class_filter(bool unlimited_local)
{
// set the default peer_class_filter to use the local peer class
// for peers on local networks
std::uint32_t lfilter = 1 << static_cast<std::uint32_t>(m_local_peer_class);
std::uint32_t gfilter = 1 << static_cast<std::uint32_t>(m_global_class);
struct class_mapping
{
char const* first;
char const* last;
std::uint32_t filter;
};
static const class_mapping v4_classes[] =
{
// everything
{"0.0.0.0", "255.255.255.255", gfilter},
// local networks
{"10.0.0.0", "10.255.255.255", lfilter},
{"172.16.0.0", "172.31.255.255", lfilter},
{"192.168.0.0", "192.168.255.255", lfilter},
// link-local
{"169.254.0.0", "169.254.255.255", lfilter},
// loop-back
{"127.0.0.0", "127.255.255.255", lfilter},
};
static const class_mapping v6_classes[] =
{
// everything
{"::0", "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", gfilter},
// local networks
{"fc00::", "fdff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", lfilter},
// link-local
{"fe80::", "febf::ffff:ffff:ffff:ffff:ffff:ffff:ffff", lfilter},
// loop-back
{"::1", "::1", lfilter},
};
class_mapping const* p = v4_classes;
int len = sizeof(v4_classes) / sizeof(v4_classes[0]);
if (!unlimited_local) len = 1;
for (int i = 0; i < len; ++i)
{
error_code ec;
address_v4 begin = make_address_v4(p[i].first, ec);
address_v4 end = make_address_v4(p[i].last, ec);
if (ec) continue;
m_peer_class_filter.add_rule(begin, end, p[i].filter);
}
p = v6_classes;
len = sizeof(v6_classes) / sizeof(v6_classes[0]);
if (!unlimited_local) len = 1;
for (int i = 0; i < len; ++i)
{
error_code ec;
address_v6 begin = make_address_v6(p[i].first, ec);
address_v6 end = make_address_v6(p[i].last, ec);
if (ec) continue;
m_peer_class_filter.add_rule(begin, end, p[i].filter);
}
}
#ifdef TORRENT_SSL_PEERS
namespace {
// when running bittorrent over SSL, the SNI (server name indication)
// extension is used to know which torrent the incoming connection is
// trying to connect to. The 40 first bytes in the name is expected to
// be the hex encoded info-hash
bool ssl_server_name_callback_impl(ssl::stream_handle_type stream_handle, std::string const& name, session_impl* si)
{
if (name.size() < 40)
return false;
info_hash_t info_hash;
bool valid = aux::from_hex({name.c_str(), 40}, info_hash.v1.data());
// the server name is not a valid hex-encoded info-hash
if (!valid)
return false;
// see if there is a torrent with this info-hash
std::shared_ptr<torrent> t = si ? si->find_torrent(info_hash).lock() : nullptr;
// if there isn't, fail
if (!t) return false;
// if the torrent we found isn't an SSL torrent, also fail.
if (!t->is_ssl_torrent()) return false;
// if the torrent doesn't have an SSL context and should not allow
// incoming SSL connections
auto* torrent_ctx = t->ssl_ctx();
if (!torrent_ctx) return false;
// use this torrent's certificate
ssl::set_context(stream_handle, ssl::get_handle(*torrent_ctx));
return true;
}
#if defined TORRENT_USE_OPENSSL
int ssl_server_name_callback(SSL* s, int*, void* arg)
{
char const* name = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
auto* si = reinterpret_cast<session_impl*>(arg);
return ssl_server_name_callback_impl(s, name ? std::string(name) : "", si)
? SSL_TLSEXT_ERR_OK
: SSL_TLSEXT_ERR_ALERT_FATAL;
}
#elif defined TORRENT_USE_GNUTLS
bool ssl_server_name_callback(ssl::stream_handle_type stream_handle, std::string const& name, void* arg)
{
session_impl* si = reinterpret_cast<session_impl*>(arg);
return ssl_server_name_callback_impl(stream_handle, name, si);
}
#endif
} // anonymous namespace
#endif // TORRENT_SSL_PEERS
session_impl::session_impl(io_context& ioc, settings_pack const& pack
, disk_io_constructor_type disk_io_constructor
, session_flags_t const flags)
: m_settings(pack)
, m_io_context(ioc)
#if TORRENT_USE_SSL
, m_ssl_ctx(ssl::context::tls_client)
#ifdef TORRENT_SSL_PEERS
, m_peer_ssl_ctx(ssl::context::tls)
#endif
#endif // TORRENT_USE_SSL
, m_alerts(m_settings.get_int(settings_pack::alert_queue_size)
, alert_category_t{static_cast<unsigned int>(m_settings.get_int(settings_pack::alert_mask))})
, m_disk_thread((disk_io_constructor ? disk_io_constructor : default_disk_io_constructor)
(m_io_context, m_settings, m_stats_counters))
, m_download_rate(peer_connection::download_channel)
, m_upload_rate(peer_connection::upload_channel)
, m_host_resolver(m_io_context)
, m_tracker_manager(
std::bind(&session_impl::send_udp_packet_listen, this, _1, _2, _3, _4, _5)
, std::bind(&session_impl::send_udp_packet_hostname_listen, this, _1, _2, _3, _4, _5, _6)
, m_stats_counters
, m_host_resolver
, m_settings
#if !defined TORRENT_DISABLE_LOGGING || TORRENT_USE_ASSERTS
, *this
#endif
)
, m_work(make_work_guard(m_io_context))
#if TORRENT_USE_I2P
, m_i2p_conn(m_io_context)
#endif
, m_created(clock_type::now())
, m_last_tick(m_created)
, m_last_second_tick(m_created - milliseconds(900))
, m_last_choke(m_created)
, m_last_auto_manage(m_created)
#ifndef TORRENT_DISABLE_DHT
, m_dht_announce_timer(m_io_context)
#endif
, m_utp_socket_manager(
std::bind(&session_impl::send_udp_packet, this, _1, _2, _3, _4, _5)
, [this](socket_type s) { this->incoming_connection(std::move(s)); }
, m_io_context
, m_settings, m_stats_counters, nullptr)
#ifdef TORRENT_SSL_PEERS
, m_ssl_utp_socket_manager(
std::bind(&session_impl::send_udp_packet, this, _1, _2, _3, _4, _5)
, std::bind(&session_impl::on_incoming_utp_ssl, this, _1)
, m_io_context
, m_settings, m_stats_counters
, &m_peer_ssl_ctx)
#endif
, m_timer(m_io_context)
, m_lsd_announce_timer(m_io_context)
, m_close_file_timer(m_io_context)
, m_paused(flags & session::paused)
{
#if !defined TORRENT_DISABLE_LOGGING || TORRENT_USE_ASSERTS
validate_settings();
#endif
}
template <typename Fun, typename... Args>
void session_impl::wrap(Fun f, Args&&... a)
#ifndef BOOST_NO_EXCEPTIONS
try
#endif
{
(this->*f)(std::forward<Args>(a)...);
}
#ifndef BOOST_NO_EXCEPTIONS
catch (system_error const& e) {
alerts().emplace_alert<session_error_alert>(e.code(), e.what());
pause();
} catch (std::exception const& e) {
alerts().emplace_alert<session_error_alert>(error_code(), e.what());
pause();
} catch (...) {
alerts().emplace_alert<session_error_alert>(error_code(), "unknown error");
pause();
}
#endif
// This function is called by the creating thread, not in the message loop's
// io_context thread.
// TODO: 2 is there a reason not to move all of this into init()? and just
// post it to the io_context?
void session_impl::start_session()
{
#ifndef TORRENT_DISABLE_LOGGING
session_log("start session");
#endif
#if TORRENT_USE_SSL
error_code ec;
m_ssl_ctx.set_default_verify_paths(ec);
#ifndef TORRENT_DISABLE_LOGGING
if (ec) session_log("SSL set_default verify_paths failed: %s", ec.message().c_str());
ec.clear();
#endif
#if defined TORRENT_WINDOWS && defined TORRENT_USE_OPENSSL && !defined TORRENT_WINRT
// TODO: come up with some abstraction to do this for gnutls as well
// load certificates from the windows system certificate store
X509_STORE* store = X509_STORE_new();
if (store)
{
HCERTSTORE system_store = CertOpenSystemStoreA(0, "ROOT");
// this is best effort
if (system_store)
{
CERT_CONTEXT const* ctx = nullptr;
while ((ctx = CertEnumCertificatesInStore(system_store, ctx)) != nullptr)
{
unsigned char const* cert_ptr = reinterpret_cast<unsigned char const*>(ctx->pbCertEncoded);
X509* x509 = d2i_X509(nullptr, &cert_ptr, ctx->cbCertEncoded);
// this is best effort
if (!x509) continue;
X509_STORE_add_cert(store, x509);
X509_free(x509);
}
CertFreeCertificateContext(ctx);
CertCloseStore(system_store, 0);
}
}
SSL_CTX* ssl_ctx = m_ssl_ctx.native_handle();
SSL_CTX_set_cert_store(ssl_ctx, store);
#endif
#ifdef __APPLE__
m_ssl_ctx.load_verify_file("/etc/ssl/cert.pem", ec);
#ifndef TORRENT_DISABLE_LOGGING
if (ec) session_log("SSL load_verify_file failed: %s", ec.message().c_str());
ec.clear();
#endif
m_ssl_ctx.add_verify_path("/etc/ssl/certs", ec);
#ifndef TORRENT_DISABLE_LOGGING
if (ec) session_log("SSL add_verify_path failed: %s", ec.message().c_str());
ec.clear();
#endif
#endif // __APPLE__
#endif // TORRENT_USE_SSL
#ifdef TORRENT_SSL_PEERS
m_peer_ssl_ctx.set_verify_mode(ssl::context::verify_none, ec);
ssl::set_server_name_callback(ssl::get_handle(m_peer_ssl_ctx), ssl_server_name_callback, this, ec);
#endif // TORRENT_SSL_PEERS
#ifndef TORRENT_DISABLE_DHT
m_next_dht_torrent = 0;
#endif
m_next_lsd_torrent = 0;
m_global_class = m_classes.new_peer_class("global");
m_tcp_peer_class = m_classes.new_peer_class("tcp");
m_local_peer_class = m_classes.new_peer_class("local");
// local peers are always unchoked
m_classes.at(m_local_peer_class)->ignore_unchoke_slots = true;
// local peers are allowed to exceed the normal connection
// limit by 50%
m_classes.at(m_local_peer_class)->connection_limit_factor = 150;
TORRENT_ASSERT(m_global_class == session::global_peer_class_id);
TORRENT_ASSERT(m_tcp_peer_class == session::tcp_peer_class_id);
TORRENT_ASSERT(m_local_peer_class == session::local_peer_class_id);
init_peer_class_filter(true);
// TCP, SSL/TCP and I2P connections should be assigned the TCP peer class
m_peer_class_type_filter.add(peer_class_type_filter::tcp_socket, m_tcp_peer_class);
m_peer_class_type_filter.add(peer_class_type_filter::ssl_tcp_socket, m_tcp_peer_class);
m_peer_class_type_filter.add(peer_class_type_filter::i2p_socket, m_tcp_peer_class);
#ifndef TORRENT_DISABLE_LOGGING
session_log("version: %s revision: %" PRIx64
, lt::version_str, lt::version_revision);
#endif // TORRENT_DISABLE_LOGGING
// ---- auto-cap max connections ----
int const max_files = max_open_files();
// deduct some margin for epoll/kqueue, log files,
// futexes, shared objects etc.
// 80% of the available file descriptors should go to connections
m_settings.set_int(settings_pack::connections_limit, std::min(
m_settings.get_int(settings_pack::connections_limit)
, std::max(5, (max_files - 20) * 8 / 10)));
// 20% goes towards regular files (see disk_io_thread)
#ifndef TORRENT_DISABLE_LOGGING
if (should_log())
{
session_log("max-connections: %d max-files: %d"
, m_settings.get_int(settings_pack::connections_limit)
, max_files);
}
#endif
post(m_io_context, [this] { wrap(&session_impl::init); });
}
void session_impl::init()
{
// this is a debug facility
// see single_threaded in debug.hpp
thread_started();
TORRENT_ASSERT(is_single_thread());
#ifndef TORRENT_DISABLE_LOGGING
session_log(" *** session thread init");
#endif
// this is where we should set up all async operations. This
// is called from within the network thread as opposed to the
// constructor which is called from the main thread
#if defined TORRENT_ASIO_DEBUGGING
async_inc_threads();
add_outstanding_async("session_impl::on_tick");
#endif
post(m_io_context, [this]{ wrap(&session_impl::on_tick, error_code()); });
int const lsd_announce_interval
= m_settings.get_int(settings_pack::local_service_announce_interval);
int const delay = std::max(lsd_announce_interval
/ std::max(static_cast<int>(m_torrents.size()), 1), 1);
m_lsd_announce_timer.expires_after(seconds(delay));
ADD_OUTSTANDING_ASYNC("session_impl::on_lsd_announce");
m_lsd_announce_timer.async_wait([this](error_code const& e) {
wrap(&session_impl::on_lsd_announce, e); } );
#ifndef TORRENT_DISABLE_LOGGING
session_log(" done starting session");
#endif
// this applies unchoke settings from m_settings
recalculate_unchoke_slots();
// apply all m_settings to this session
run_all_updates(*this);
reopen_listen_sockets(false);
#if TORRENT_USE_INVARIANT_CHECKS
check_invariant();
#endif
}
#if TORRENT_ABI_VERSION <= 2
// TODO: 2 the ip filter should probably be saved here too
void session_impl::save_state(entry* eptr, save_state_flags_t const flags) const
{
TORRENT_ASSERT(is_single_thread());
entry& e = *eptr;
// make it a dict
e.dict();
if (flags & session::save_settings)
{
entry::dictionary_type& sett = e["settings"].dict();
save_settings_to_dict(non_default_settings(m_settings), sett);
}
#ifndef TORRENT_DISABLE_DHT
if (flags & session::save_dht_settings)
{
e["dht"] = dht::save_dht_settings(get_dht_settings());
}
if (m_dht && (flags & session::save_dht_state))
{
e["dht state"] = dht::save_dht_state(m_dht->state());
}
#endif
#ifndef TORRENT_DISABLE_EXTENSIONS
for (auto const& ext : m_ses_extensions[plugins_all_idx])
{
ext->save_state(*eptr);
}
#endif
}
void session_impl::load_state(bdecode_node const* e
, save_state_flags_t const flags)
{
TORRENT_ASSERT(is_single_thread());
bdecode_node settings;
if (e->type() != bdecode_node::dict_t) return;
#ifndef TORRENT_DISABLE_DHT
bool need_update_dht = false;
if (flags & session_handle::save_dht_state)
{
settings = e->dict_find_dict("dht state");
if (settings)
{
m_dht_state = dht::read_dht_state(settings);
need_update_dht = true;
}
}
#endif
#if TORRENT_ABI_VERSION == 1
bool need_update_proxy = false;
if (flags & session_handle::save_proxy)
{
settings = e->dict_find_dict("proxy");
if (settings)
{
m_settings.bulk_set([&settings](session_settings_single_thread& s)
{
bdecode_node val;
val = settings.dict_find_int("port");
if (val) s.set_int(settings_pack::proxy_port, int(val.int_value()));
val = settings.dict_find_int("type");
if (val) s.set_int(settings_pack::proxy_type, int(val.int_value()));
val = settings.dict_find_int("proxy_hostnames");
if (val) s.set_bool(settings_pack::proxy_hostnames, val.int_value() != 0);
val = settings.dict_find_int("proxy_peer_connections");
if (val) s.set_bool(settings_pack::proxy_peer_connections, val.int_value() != 0);
val = settings.dict_find_string("hostname");
if (val) s.set_str(settings_pack::proxy_hostname, val.string_value().to_string());
val = settings.dict_find_string("password");
if (val) s.set_str(settings_pack::proxy_password, val.string_value().to_string());
val = settings.dict_find_string("username");
if (val) s.set_str(settings_pack::proxy_username, val.string_value().to_string());
});
need_update_proxy = true;
}
}
settings = e->dict_find_dict("encryption");
if (settings)
{
m_settings.bulk_set([&settings](session_settings_single_thread& s)
{
bdecode_node val;
val = settings.dict_find_int("prefer_rc4");
if (val) s.set_bool(settings_pack::prefer_rc4, val.int_value() != 0);
val = settings.dict_find_int("out_enc_policy");
if (val) s.set_int(settings_pack::out_enc_policy, int(val.int_value()));
val = settings.dict_find_int("in_enc_policy");
if (val) s.set_int(settings_pack::in_enc_policy, int(val.int_value()));
val = settings.dict_find_int("allowed_enc_level");
if (val) s.set_int(settings_pack::allowed_enc_level, int(val.int_value()));
});
}
#endif
if ((flags & session_handle::save_settings)
#if TORRENT_ABI_VERSION <= 2
|| (flags & session_handle::save_dht_settings)
#endif
)
{
settings = e->dict_find_dict("settings");
if (settings)
{
// apply_settings_pack will update dht and proxy
settings_pack pack = load_pack_from_dict(settings);
// these settings are not loaded from state
// they are set by the client software, not configured by users
pack.clear(settings_pack::user_agent);
pack.clear(settings_pack::peer_fingerprint);
apply_settings_pack_impl(pack);
#ifndef TORRENT_DISABLE_DHT
need_update_dht = false;
#endif
#if TORRENT_ABI_VERSION == 1
need_update_proxy = false;
#endif
}
}
#if TORRENT_ABI_VERSION <= 2
if (flags & session_handle::save_dht_settings)
#endif
{
// This is here for backwards compatibility, to support loading state
// files in the previous file format, where the DHT settings were in
// its own dictionary
settings = e->dict_find_dict("dht");
if (settings)
{
settings_pack sett;
aux::apply_deprecated_dht_settings(sett, settings);
apply_settings_pack_impl(sett);
}
}
#ifndef TORRENT_DISABLE_DHT
if (need_update_dht) start_dht();
#endif
#if TORRENT_ABI_VERSION == 1
if (need_update_proxy) update_proxy();
#endif
#ifndef TORRENT_DISABLE_EXTENSIONS
#if TORRENT_ABI_VERSION <= 2
for (auto& ext : m_ses_extensions[plugins_all_idx])
{
ext->load_state(*e);
}
#endif
#endif
}
#endif
session_params session_impl::session_state(save_state_flags_t const flags) const
{
TORRENT_ASSERT(is_single_thread());
session_params ret;
if (flags & session::save_settings)
ret.settings = non_default_settings(m_settings);
#ifndef TORRENT_DISABLE_DHT
#if TORRENT_ABI_VERSION <= 2
if (flags & session_handle::save_dht_settings)
{
ret.dht_settings = get_dht_settings();
}
#endif
if (m_dht && (flags & session::save_dht_state))
ret.dht_state = m_dht->state();
#endif
#ifndef TORRENT_DISABLE_EXTENSIONS
if (flags & session::save_extension_state)
{
for (auto const& ext : m_ses_extensions[plugins_all_idx])
{
auto state = ext->save_state();
for (auto& v : state)
ret.ext_state[std::move(v.first)] = std::move(v.second);
}
}
#endif
if ((flags & session::save_ip_filter) && m_ip_filter)
{
ret.ip_filter = *m_ip_filter;
}
return ret;
}
proxy_settings session_impl::proxy() const
{
return proxy_settings(m_settings);
}
#ifndef TORRENT_DISABLE_EXTENSIONS
void session_impl::add_extension(ext_function_t ext)
{
TORRENT_ASSERT(is_single_thread());
TORRENT_ASSERT(ext);
add_ses_extension(std::make_shared<session_plugin_wrapper>(ext));
}
void session_impl::add_ses_extension(std::shared_ptr<plugin> ext)
{
// this is called during startup of the session, from the thread creating
// it, not its own thread
// TORRENT_ASSERT(is_single_thread());
TORRENT_ASSERT_VAL(ext, ext);
feature_flags_t const features = ext->implemented_features();
m_ses_extensions[plugins_all_idx].push_back(ext);
if (features & plugin::optimistic_unchoke_feature)
m_ses_extensions[plugins_optimistic_unchoke_idx].push_back(ext);
if (features & plugin::tick_feature)
m_ses_extensions[plugins_tick_idx].push_back(ext);
if (features & plugin::dht_request_feature)
m_ses_extensions[plugins_dht_request_idx].push_back(ext);
if (features & plugin::unknown_torrent_feature)
m_ses_extensions[plugins_unknown_torrent_idx].push_back(ext);
if (features & plugin::alert_feature)
m_alerts.add_extension(ext);
session_handle h(shared_from_this());