-
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathtorrent.cpp
10984 lines (9396 loc) · 310 KB
/
torrent.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-2016, Arvid Norberg
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 <cstdarg> // for va_list
#include <ctime>
#include <algorithm>
#include <set>
#include <map>
#include <vector>
#include <cctype>
#include <numeric>
#include <limits> // for numeric_limits
#include <cstdio> // for snprintf
#include <functional>
#include "libtorrent/aux_/disable_warnings_push.hpp"
#ifdef TORRENT_USE_OPENSSL
#include "libtorrent/ssl_stream.hpp"
#include <boost/asio/ssl/context.hpp>
#include <boost/asio/ssl/verify_context.hpp>
#endif // TORRENT_USE_OPENSSL
#include "libtorrent/aux_/disable_warnings_pop.hpp"
#include "libtorrent/torrent_handle.hpp"
#include "libtorrent/announce_entry.hpp"
#include "libtorrent/torrent_info.hpp"
#include "libtorrent/tracker_manager.hpp"
#include "libtorrent/parse_url.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/hasher.hpp"
#include "libtorrent/entry.hpp"
#include "libtorrent/peer.hpp"
#include "libtorrent/peer_connection.hpp"
#include "libtorrent/bt_peer_connection.hpp"
#include "libtorrent/web_peer_connection.hpp"
#include "libtorrent/http_seed_connection.hpp"
#include "libtorrent/peer_connection_handle.hpp"
#include "libtorrent/peer_id.hpp"
#include "libtorrent/identify_client.hpp"
#include "libtorrent/alert_types.hpp"
#include "libtorrent/extensions.hpp"
#include "libtorrent/aux_/session_interface.hpp"
#include "libtorrent/instantiate_connection.hpp"
#include "libtorrent/assert.hpp"
#include "libtorrent/broadcast_socket.hpp"
#include "libtorrent/kademlia/dht_tracker.hpp"
#include "libtorrent/peer_info.hpp"
#include "libtorrent/http_connection.hpp"
#include "libtorrent/random.hpp"
#include "libtorrent/peer_class.hpp" // for peer_class
#include "libtorrent/socket_io.hpp" // for read_*_endpoint
#include "libtorrent/ip_filter.hpp"
#include "libtorrent/request_blocks.hpp"
#include "libtorrent/performance_counters.hpp" // for counters
#include "libtorrent/resolver_interface.hpp"
#include "libtorrent/alloca.hpp"
#include "libtorrent/resolve_links.hpp"
#include "libtorrent/aux_/file_progress.hpp"
#include "libtorrent/aux_/has_block.hpp"
#include "libtorrent/alert_manager.hpp"
#include "libtorrent/disk_interface.hpp"
#include "libtorrent/broadcast_socket.hpp" // for is_ip_address
#include "libtorrent/hex.hpp" // to_hex
// TODO: factor out cache_status to its own header
#include "libtorrent/disk_io_thread.hpp" // for cache_status
#ifndef TORRENT_DISABLE_LOGGING
#include "libtorrent/aux_/session_impl.hpp" // for tracker_logger
#endif
using namespace std::placeholders;
namespace libtorrent
{
namespace {
int root2(int x)
{
int ret = 0;
x >>= 1;
while (x > 0)
{
// if this assert triggers, the block size
// is not an even 2 exponent!
TORRENT_ASSERT(x == 1 || (x & 1) == 0);
++ret;
x >>= 1;
}
return ret;
}
constexpr int default_piece_priority = 4;
} // anonymous namespace
web_seed_t::web_seed_t(web_seed_entry const& wse)
: web_seed_entry(wse)
{
peer_info.web_seed = true;
}
web_seed_t::web_seed_t(std::string const& url_, web_seed_entry::type_t type_
, std::string const& auth_
, web_seed_entry::headers_t const& extra_headers_)
: web_seed_entry(url_, type_, auth_, extra_headers_)
{
peer_info.web_seed = true;
}
torrent_hot_members::torrent_hot_members(aux::session_interface& ses
, add_torrent_params const& p, int const block_size
, bool const session_paused)
: m_ses(ses)
, m_complete(0xffffff)
, m_upload_mode((p.flags & add_torrent_params::flag_upload_mode) != 0)
, m_connections_initialized(false)
, m_abort(false)
, m_paused((p.flags & add_torrent_params::flag_paused) != 0)
, m_session_paused(session_paused)
, m_share_mode((p.flags & add_torrent_params::flag_share_mode) != 0)
, m_have_all(false)
, m_graceful_pause_mode(false)
, m_state_subscription((p.flags & add_torrent_params::flag_update_subscribe) != 0)
, m_max_connections(0xffffff)
, m_block_size_shift(root2(block_size))
, m_state(torrent_status::checking_resume_data)
{}
torrent::torrent(
aux::session_interface& ses
, int const block_size
, int const seq
, bool const session_paused
, add_torrent_params const& p
, sha1_hash const& info_hash)
: torrent_hot_members(ses, p, block_size, session_paused)
, m_tracker_timer(ses.get_io_service())
, m_inactivity_timer(ses.get_io_service())
, m_trackerid(p.trackerid)
, m_save_path(complete(p.save_path))
#ifndef TORRENT_NO_DEPRECATE
// deprecated in 1.2
, m_url(p.url)
, m_uuid(p.uuid)
#endif
, m_stats_counters(ses.stats_counters())
, m_storage_constructor(p.storage)
, m_added_time(time(nullptr))
, m_info_hash(info_hash)
, m_last_saved_resume(ses.session_time())
, m_started(ses.session_time())
, m_error_file(torrent_status::error_file_none)
, m_sequence_number(seq)
, m_announce_to_trackers((p.flags & add_torrent_params::flag_paused) == 0)
, m_announce_to_lsd((p.flags & add_torrent_params::flag_paused) == 0)
, m_has_incoming(false)
, m_files_checked(false)
, m_storage_mode(p.storage_mode)
, m_announcing(false)
, m_added(false)
, m_active_time(0)
, m_finished_time(0)
, m_sequential_download(false)
, m_auto_sequential(false)
, m_seed_mode(false)
, m_super_seeding(false)
, m_stop_when_ready((p.flags & add_torrent_params::flag_stop_when_ready) != 0)
, m_need_save_resume_data((p.flags & add_torrent_params::flag_need_save_resume) != 0)
, m_seeding_time(0)
, m_max_uploads((1<<24)-1)
, m_num_uploads(0)
, m_need_connect_boost(true)
, m_lsd_seq(0)
, m_magnet_link(false)
, m_apply_ip_filter((p.flags & add_torrent_params::flag_apply_ip_filter) != 0)
, m_pending_active_change(false)
, m_padding(0)
, m_incomplete(0xffffff)
, m_announce_to_dht((p.flags & add_torrent_params::flag_paused) == 0)
, m_in_state_updates(false)
, m_is_active_download(false)
, m_is_active_finished(false)
, m_ssl_torrent(false)
, m_deleted(false)
, m_auto_managed((p.flags & add_torrent_params::flag_auto_managed) != 0)
, m_current_gauge_state(no_gauge_state)
, m_moving_storage(false)
, m_inactive(false)
, m_downloaded(0xffffff)
, m_progress_ppm(0)
{
// we cannot log in the constructor, because it relies on shared_from_this
// being initialized, which happens after the constructor returns.
// TODO: 3 we could probably get away with just saving a few fields here
// TODO: 2 p should probably be moved in here
m_add_torrent_params.reset(new add_torrent_params(p));
#if TORRENT_USE_UNC_PATHS
m_save_path = canonicalize_path(m_save_path);
#endif
if (!m_apply_ip_filter)
{
inc_stats_counter(counters::non_filter_torrents);
}
if (!p.ti || !p.ti->is_valid())
{
// we don't have metadata for this torrent. We'll download
// it either through the URL passed in, or through a metadata
// extension. Make sure that when we save resume data for this
// torrent, we also save the metadata
m_magnet_link = true;
}
if (!m_torrent_file)
m_torrent_file = (p.ti ? p.ti : std::make_shared<torrent_info>(info_hash));
// --- WEB SEEDS ---
// if override web seed flag is set, don't load any web seeds from the
// torrent file.
if ((p.flags & add_torrent_params::flag_override_web_seeds) == 0)
{
std::vector<web_seed_entry> const& web_seeds = m_torrent_file->web_seeds();
m_web_seeds.insert(m_web_seeds.end(), web_seeds.begin(), web_seeds.end());
}
// add web seeds from add_torrent_params
bool const multi_file = m_torrent_file->is_valid()
&& m_torrent_file->num_files() > 1;
for (auto const& u : p.url_seeds)
{
m_web_seeds.push_back(web_seed_t(u, web_seed_entry::url_seed));
// correct URLs to end with a "/" for multi-file torrents
std::string& url = m_web_seeds.back().url;
if (multi_file && url[url.size()-1] != '/') url += '/';
}
for (auto const& e : p.http_seeds)
{
m_web_seeds.push_back(web_seed_t(e, web_seed_entry::http_seed));
}
// --- TRACKERS ---
// if override trackers flag is set, don't load trackers from torrent file
if ((p.flags & add_torrent_params::flag_override_trackers) == 0)
{
m_trackers = m_torrent_file->trackers();
}
int tier = 0;
auto tier_iter = p.tracker_tiers.begin();
for (auto const& url : p.trackers)
{
announce_entry e(url);
if (tier_iter != p.tracker_tiers.end())
tier = *tier_iter++;
e.fail_limit = 0;
e.source = announce_entry::source_magnet_link;
e.tier = std::uint8_t(tier);
if (!find_tracker(e.url))
{
m_trackers.push_back(e);
}
}
std::sort(m_trackers.begin(), m_trackers.end()
, [] (announce_entry const& lhs, announce_entry const& rhs)
{ return lhs.tier < rhs.tier; });
if (settings().get_bool(settings_pack::prefer_udp_trackers))
prioritize_udp_trackers();
// --- MERKLE TREE ---
if (m_torrent_file->is_valid()
&& m_torrent_file->is_merkle_torrent())
{
if (p.merkle_tree.size() == m_torrent_file->merkle_tree().size())
{
// TODO: 2 set_merkle_tree should probably take the vector as &&
std::vector<sha1_hash> tree(p.merkle_tree);
m_torrent_file->set_merkle_tree(tree);
}
else
{
// TODO: 0 if this is a merkle torrent and we can't
// restore the tree, we need to wipe all the
// bits in the have array, but not necessarily
// we might want to do a full check to see if we have
// all the pieces. This is low priority since almost
// no one uses merkle torrents
TORRENT_ASSERT_FAIL();
}
}
if (m_torrent_file->is_valid())
{
// setting file- or piece priorities for seed mode makes no sense. If a
// torrent ends up in seed mode by accident, it can be very confusing,
// so assume the seed mode flag is not intended and don't enable it in
// that case. Also, if the resume data says we're missing a piece, we
// can't be in seed-mode.
m_seed_mode = (p.flags & add_torrent_params::flag_seed_mode) != 0
&& std::find(p.file_priorities.begin(), p.file_priorities.end(), 0) == p.file_priorities.end()
&& std::find(p.piece_priorities.begin(), p.piece_priorities.end(), 0) == p.piece_priorities.end()
&& std::find(p.have_pieces.begin(), p.have_pieces.end(), false) == p.have_pieces.end();
m_connections_initialized = true;
m_block_size_shift = root2((std::min)(block_size, m_torrent_file->piece_length()));
}
else
{
if (!p.name.empty()) m_name.reset(new std::string(p.name));
}
#ifndef TORRENT_NO_DEPRECATE
// deprecated in 1.2
if (!m_url.empty() && m_uuid.empty()) m_uuid = m_url;
#endif
TORRENT_ASSERT(is_single_thread());
m_file_priority.assign(p.file_priorities.begin(), p.file_priorities.end());
if (m_seed_mode)
{
m_verified.resize(m_torrent_file->num_pieces(), false);
m_verifying.resize(m_torrent_file->num_pieces(), false);
}
m_total_uploaded = p.total_uploaded;
m_total_downloaded = p.total_downloaded;
// the number of seconds this torrent has spent in started, finished and
// seeding state so far, respectively.
m_active_time = p.active_time;
m_finished_time = p.finished_time;
m_seeding_time = p.seeding_time;
m_added_time = p.added_time ? p.added_time : time(nullptr);
m_completed_time = p.completed_time;
if (m_completed_time != 0 && m_completed_time < m_added_time)
m_completed_time = m_added_time;
}
void torrent::inc_stats_counter(int c, int value)
{ m_ses.stats_counters().inc_stats_counter(c, value); }
#ifndef TORRENT_NO_DEPRECATE
// deprecated in 1.2
void torrent::on_torrent_download(error_code const& ec
, http_parser const& parser, char const* data, int size) try
{
if (m_abort) return;
if (ec && ec != boost::asio::error::eof)
{
set_error(ec, torrent_status::error_file_url);
pause();
return;
}
if (parser.status_code() != 200)
{
set_error(error_code(parser.status_code(), http_category()), torrent_status::error_file_url);
pause();
return;
}
error_code e;
auto tf = std::make_shared<torrent_info>(data, size, std::ref(e), 0);
if (e)
{
set_error(e, torrent_status::error_file_url);
pause();
return;
}
// update our torrent_info object and move the
// torrent from the old info-hash to the new one
// as we replace the torrent_info object
// we're about to erase the session's reference to this
// torrent, create another reference
auto me = shared_from_this();
m_ses.remove_torrent_impl(me, 0);
if (alerts().should_post<torrent_update_alert>())
alerts().emplace_alert<torrent_update_alert>(get_handle(), info_hash(), tf->info_hash());
m_torrent_file = tf;
m_info_hash = tf->info_hash();
// now, we might already have this torrent in the session.
std::shared_ptr<torrent> t = m_ses.find_torrent(m_torrent_file->info_hash()).lock();
if (t)
{
if (!m_uuid.empty() && t->uuid().empty())
t->set_uuid(m_uuid);
if (!m_url.empty() && t->url().empty())
t->set_url(m_url);
// insert this torrent in the uuid index
if (!m_uuid.empty() || !m_url.empty())
{
m_ses.insert_uuid_torrent(m_uuid.empty() ? m_url : m_uuid, t);
}
// TODO: if the existing torrent doesn't have metadata, insert
// the metadata we just downloaded into it.
set_error(errors::duplicate_torrent, torrent_status::error_file_url);
abort();
return;
}
m_ses.insert_torrent(m_torrent_file->info_hash(), me, m_uuid);
// if the user added any trackers while downloading the
// .torrent file, merge them into the new tracker list
std::vector<announce_entry> new_trackers = m_torrent_file->trackers();
for (auto const& tr : m_trackers)
{
// if we already have this tracker, ignore it
if (std::any_of(new_trackers.begin(), new_trackers.end()
, [&tr] (announce_entry const& ae) { return ae.url == tr.url; }))
continue;
// insert the tracker ordered by tier
new_trackers.insert(std::find_if(new_trackers.begin(), new_trackers.end()
, [&tr] (announce_entry const& ae) { return ae.tier >= tr.tier; }), tr);
}
m_trackers.swap(new_trackers);
// add the web seeds from the .torrent file
std::vector<web_seed_entry> const& web_seeds = m_torrent_file->web_seeds();
m_web_seeds.insert(m_web_seeds.end(), web_seeds.begin(), web_seeds.end());
#if !defined(TORRENT_DISABLE_ENCRYPTION) && !defined(TORRENT_DISABLE_EXTENSIONS)
static char const req2[4] = {'r', 'e', 'q', '2'};
hasher h(req2);
h.update(m_torrent_file->info_hash());
m_ses.add_obfuscated_hash(h.final(), shared_from_this());
#endif
if (m_ses.alerts().should_post<metadata_received_alert>())
{
m_ses.alerts().emplace_alert<metadata_received_alert>(
get_handle());
}
state_updated();
set_state(torrent_status::downloading);
init();
}
catch (...) { handle_exception(); }
#endif // TORRENT_NO_DEPRECATE
int torrent::current_stats_state() const
{
if (m_abort || !m_added)
return counters::num_checking_torrents + no_gauge_state;
if (has_error()) return counters::num_error_torrents;
if (m_paused || m_graceful_pause_mode)
{
if (!is_auto_managed()) return counters::num_stopped_torrents;
if (is_seed()) return counters::num_queued_seeding_torrents;
return counters::num_queued_download_torrents;
}
if (state() == torrent_status::checking_files
#ifndef TORRENT_NO_DEPRECATE
|| state() == torrent_status::queued_for_checking
#endif
)
return counters::num_checking_torrents;
else if (is_seed()) return counters::num_seeding_torrents;
else if (is_upload_only()) return counters::num_upload_only_torrents;
return counters::num_downloading_torrents;
}
void torrent::update_gauge()
{
int const new_gauge_state = current_stats_state() - counters::num_checking_torrents;
TORRENT_ASSERT(new_gauge_state >= 0);
TORRENT_ASSERT(new_gauge_state <= no_gauge_state);
if (new_gauge_state == m_current_gauge_state) return;
if (m_current_gauge_state != no_gauge_state)
inc_stats_counter(m_current_gauge_state + counters::num_checking_torrents, -1);
if (new_gauge_state != no_gauge_state)
inc_stats_counter(new_gauge_state + counters::num_checking_torrents, 1);
m_current_gauge_state = new_gauge_state;
}
void torrent::leave_seed_mode(bool skip_checking)
{
if (!m_seed_mode) return;
if (!skip_checking)
{
// this means the user promised we had all the
// files, but it turned out we didn't. This is
// an error.
// TODO: 2 post alert
#ifndef TORRENT_DISABLE_LOGGING
debug_log("*** FAILED SEED MODE, rechecking");
#endif
}
#ifndef TORRENT_DISABLE_LOGGING
debug_log("*** LEAVING SEED MODE (%s)"
, skip_checking ? "as seed" : "as non-seed");
#endif
m_seed_mode = false;
// seed is false if we turned out not
// to be a seed after all
if (!skip_checking)
{
m_have_all = false;
set_state(torrent_status::downloading);
force_recheck();
}
m_num_verified = 0;
m_verified.clear();
m_verifying.clear();
set_need_save_resume();
}
void torrent::verified(piece_index_t const piece)
{
TORRENT_ASSERT(m_verified.get_bit(piece) == false);
++m_num_verified;
m_verified.set_bit(piece);
}
void torrent::start(add_torrent_params const& p)
{
TORRENT_ASSERT(is_single_thread());
TORRENT_ASSERT(m_was_started == false);
#if TORRENT_USE_ASSERTS
m_was_started = true;
#endif
#ifndef TORRENT_NO_DEPRECATE
if (m_add_torrent_params
&& m_add_torrent_params->internal_resume_data_error
&& m_ses.alerts().should_post<fastresume_rejected_alert>())
{
m_ses.alerts().emplace_alert<fastresume_rejected_alert>(get_handle()
, m_add_torrent_params->internal_resume_data_error, "", "");
}
#endif
// TODO: 3 why isn't this done in the constructor?
#ifndef TORRENT_DISABLE_LOGGING
if (should_log())
{
debug_log("creating torrent: %s max-uploads: %d max-connections: %d "
"upload-limit: %d download-limit: %d flags: %s%s%s%s%s%s%s%s%s%s%s "
"save-path: %s"
, torrent_file().name().c_str()
, p.max_uploads
, p.max_connections
, p.upload_limit
, p.download_limit
, (p.flags & add_torrent_params::flag_seed_mode)
? "seed-mode " : ""
, (p.flags & add_torrent_params::flag_upload_mode)
? "upload-mode " : ""
, (p.flags & add_torrent_params::flag_share_mode)
? "share-mode " : ""
, (p.flags & add_torrent_params::flag_apply_ip_filter)
? "apply-ip-filter " : ""
, (p.flags & add_torrent_params::flag_paused)
? "paused " : ""
, (p.flags & add_torrent_params::flag_auto_managed)
? "auto-managed " : ""
, (p.flags & add_torrent_params::flag_update_subscribe)
? "update-subscribe " : ""
, (p.flags & add_torrent_params::flag_super_seeding)
? "super-seeding " : ""
, (p.flags & add_torrent_params::flag_sequential_download)
? "sequential-download " : ""
, (p.flags & add_torrent_params::flag_override_trackers)
? "override-trackers" : ""
, (p.flags & add_torrent_params::flag_override_web_seeds)
? "override-web-seeds " : ""
, p.save_path.c_str()
);
}
#endif
if (p.flags & add_torrent_params::flag_sequential_download)
m_sequential_download = true;
if (p.flags & add_torrent_params::flag_super_seeding)
{
m_super_seeding = true;
set_need_save_resume();
}
set_max_uploads(p.max_uploads, false);
set_max_connections(p.max_connections, false);
set_limit_impl(p.upload_limit, peer_connection::upload_channel, false);
set_limit_impl(p.download_limit, peer_connection::download_channel, false);
for (auto const& peer : p.peers)
{
add_peer(peer, peer_info::resume_data);
}
#ifndef TORRENT_NO_DEPRECATE
if (!m_name && !m_url.empty()) m_name.reset(new std::string(m_url));
#endif
if (valid_metadata())
{
inc_stats_counter(counters::num_total_pieces_added
, m_torrent_file->num_pieces());
}
update_gauge();
m_file_progress.clear();
update_want_peers();
update_want_scrape();
update_want_tick();
update_state_list();
#ifndef TORRENT_NO_DEPRECATE
// deprecated in 1.2
if (!m_torrent_file->is_valid() && !m_url.empty())
{
// we need to download the .torrent file from m_url
start_download_url();
}
else
#endif
if (m_torrent_file->is_valid())
{
init();
}
else
{
// we need to start announcing since we don't have any
// metadata. To receive peers to ask for it.
set_state(torrent_status::downloading_metadata);
start_announcing();
}
#if TORRENT_USE_INVARIANT_CHECKS
check_invariant();
#endif
}
#ifndef TORRENT_NO_DEPRECATE
// deprecated in 1.2
void torrent::start_download_url()
{
TORRENT_ASSERT(!m_url.empty());
TORRENT_ASSERT(!m_torrent_file->is_valid());
std::shared_ptr<http_connection> conn(
new http_connection(m_ses.get_io_service()
, m_ses.get_resolver()
, std::bind(&torrent::on_torrent_download, shared_from_this()
, _1, _2, _3, _4)
, true // bottled
//bottled buffer size
, settings().get_int(settings_pack::max_http_recv_buffer_size)
, http_connect_handler()
, http_filter_handler()
#ifdef TORRENT_USE_OPENSSL
, m_ssl_ctx.get()
#endif
));
aux::proxy_settings ps = m_ses.proxy();
conn->get(m_url, seconds(30), 0, &ps
, 5
, settings().get_bool(settings_pack::anonymous_mode)
? "" : settings().get_str(settings_pack::user_agent));
set_state(torrent_status::downloading_metadata);
}
#endif
void torrent::set_apply_ip_filter(bool b)
{
if (b == m_apply_ip_filter) return;
if (b)
{
inc_stats_counter(counters::non_filter_torrents, -1);
}
else
{
inc_stats_counter(counters::non_filter_torrents);
}
m_apply_ip_filter = b;
ip_filter_updated();
state_updated();
}
void torrent::set_ip_filter(std::shared_ptr<const ip_filter> ipf)
{
m_ip_filter = ipf;
if (!m_apply_ip_filter) return;
ip_filter_updated();
}
#ifndef TORRENT_DISABLE_DHT
bool torrent::should_announce_dht() const
{
TORRENT_ASSERT(is_single_thread());
if (!m_ses.announce_dht()) return false;
if (!m_ses.dht()) return false;
if (m_torrent_file->is_valid() && !m_files_checked) return false;
if (!m_announce_to_dht) return false;
if (m_paused) return false;
#ifndef TORRENT_NO_DEPRECATE
// deprecated in 1.2
// if we don't have the metadata, and we're waiting
// for a web server to serve it to us, no need to announce
// because the info-hash is just the URL hash
if (!m_torrent_file->is_valid() && !m_url.empty()) return false;
#endif
// don't announce private torrents
if (m_torrent_file->is_valid() && m_torrent_file->priv()) return false;
if (m_trackers.empty()) return true;
if (!settings().get_bool(settings_pack::use_dht_as_fallback)) return true;
int verified_trackers = 0;
for (auto const& tr : m_trackers)
if (tr.verified) ++verified_trackers;
return verified_trackers == 0;
}
#endif
torrent::~torrent()
{
// TODO: 3 assert there are no outstanding async operations on this
// torrent
#if TORRENT_USE_ASSERTS
for (int i = 0; i < aux::session_interface::num_torrent_lists; ++i)
{
if (!m_links[i].in_list()) continue;
m_links[i].unlink(m_ses.torrent_list(i), i);
}
#endif
// The invariant can't be maintained here, since the torrent
// is being destructed, all weak references to it have been
// reset, which means that all its peers already have an
// invalidated torrent pointer (so it cannot be verified to be correct)
// i.e. the invariant can only be maintained if all connections have
// been closed by the time the torrent is destructed. And they are
// supposed to be closed. So we can still do the invariant check.
// however, the torrent object may be destructed from the main
// thread when shutting down, if the disk cache has references to it.
// this means that the invariant check that this is called from the
// network thread cannot be maintained
TORRENT_ASSERT(m_peer_class == 0);
TORRENT_ASSERT(m_connections.empty());
if (!m_connections.empty())
disconnect_all(errors::torrent_aborted, op_bittorrent);
}
void torrent::read_piece(piece_index_t const piece)
{
if (m_abort || m_deleted)
{
// failed
m_ses.alerts().emplace_alert<read_piece_alert>(
get_handle(), piece, error_code(boost::system::errc::operation_canceled, generic_category()));
return;
}
const int piece_size = m_torrent_file->piece_size(piece);
const int blocks_in_piece = (piece_size + block_size() - 1) / block_size();
TORRENT_ASSERT(blocks_in_piece > 0);
TORRENT_ASSERT(piece_size > 0);
if (blocks_in_piece == 0)
{
// this shouldn't actually happen
boost::shared_array<char> buf;
m_ses.alerts().emplace_alert<read_piece_alert>(
get_handle(), piece, buf, 0);
return;
}
std::shared_ptr<read_piece_struct> rp = std::make_shared<read_piece_struct>();
rp->piece_data.reset(new (std::nothrow) char[piece_size]);
rp->blocks_left = 0;
rp->fail = false;
peer_request r;
r.piece = piece;
r.start = 0;
rp->blocks_left = blocks_in_piece;
for (int i = 0; i < blocks_in_piece; ++i, r.start += block_size())
{
r.length = (std::min)(piece_size - r.start, block_size());
m_ses.disk_thread().async_read(&storage(), r
, std::bind(&torrent::on_disk_read_complete
, shared_from_this(), _1, _2, _3, _4, r, rp), reinterpret_cast<void*>(1));
}
}
void torrent::send_share_mode()
{
#ifndef TORRENT_DISABLE_EXTENSIONS
for (peer_iterator i = m_connections.begin()
, end(m_connections.end()); i != end; ++i)
{
if ((*i)->type() != connection_type::bittorrent) continue;
bt_peer_connection* p = static_cast<bt_peer_connection*>(*i);
p->write_share_mode();
}
#endif
}
void torrent::send_upload_only()
{
#ifndef TORRENT_DISABLE_EXTENSIONS
if (share_mode()) return;
if (super_seeding()) return;
int idx = 0;
for (peer_iterator i = m_connections.begin();
i != m_connections.end(); ++idx)
{
// since the call to disconnect_if_redundant() may
// delete the entry from this container, make sure
// to increment the iterator early
peer_connection* p = *i;
if (p->type() == connection_type::bittorrent)
{
bt_peer_connection* btp = static_cast<bt_peer_connection*>(p);
std::shared_ptr<peer_connection> me(btp->self());
if (!btp->is_disconnecting())
{
btp->send_not_interested();
btp->write_upload_only();
}
}
if (p->is_disconnecting())
{
i = m_connections.begin() + idx;
--idx;
}
else
{
++i;
}
}
#endif
}
void torrent::set_share_mode(bool s)
{
if (s == m_share_mode) return;
m_share_mode = s;
#ifndef TORRENT_DISABLE_LOGGING
debug_log("*** set-share-mode: %d", s);
#endif
// in share mode, all pieces have their priorities initialized to 0
if (m_share_mode && valid_metadata())
{
m_file_priority.clear();
m_file_priority.resize(m_torrent_file->num_files(), 0);
}
update_piece_priorities();
if (m_share_mode) recalc_share_mode();
}
void torrent::set_upload_mode(bool b)
{
if (b == m_upload_mode) return;
m_upload_mode = b;
#ifndef TORRENT_DISABLE_LOGGING
debug_log("*** set-upload-mode: %d", b);
#endif
update_gauge();
state_updated();
send_upload_only();
if (m_upload_mode)
{
// clear request queues of all peers
for (peer_iterator i = m_connections.begin()
, end(m_connections.end()); i != end; ++i)
{
peer_connection* p = (*i);
// we may want to disconnect other upload-only peers
if (p->upload_only())
p->update_interest();
p->cancel_all_requests();
}
// this is used to try leaving upload only mode periodically
m_upload_mode_time = m_ses.session_time();
}
else if (m_peer_list)
{
// reset last_connected, to force fast reconnect after leaving upload mode
for (auto pe : *m_peer_list)
{
pe->last_connected = 0;
}
// send_block_requests on all peers
for (peer_iterator i = m_connections.begin()
, end(m_connections.end()); i != end; ++i)
{
peer_connection* p = (*i);
// we may be interested now, or no longer interested
p->update_interest();
p->send_block_requests();
}
}
}
void torrent::need_peer_list()
{
if (m_peer_list) return;
m_peer_list.reset(new peer_list);
}
void torrent::handle_exception()
{
try
{
throw;
}
catch (system_error const& err)
{