forked from arvidn/libtorrent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient_test.cpp
2372 lines (2085 loc) · 68.2 KB
/
client_test.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-2022, Arvid Norberg
Copyright (c) 2015, Mike Tzou
Copyright (c) 2016, 2018-2019, Alden Torres
Copyright (c) 2016, Andrei Kurushin
Copyright (c) 2017, AllSeeingEyeTolledEweSew
Copyright (c) 2017-2018, Steven Siloti
Copyright (c) 2019, Pavel Pimenov
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 <cstdio> // for snprintf
#include <cstdlib> // for atoi
#include <cstring>
#include <utility>
#include <deque>
#include <fstream>
#include <regex>
#include <algorithm> // for min()/max()
#include "libtorrent/config.hpp"
#ifdef TORRENT_WINDOWS
#include <direct.h> // for _mkdir and _getcwd
#include <sys/types.h> // for _stat
#include <sys/stat.h>
#endif
#ifdef TORRENT_UTP_LOG_ENABLE
#include "libtorrent/utp_stream.hpp"
#endif
#include "libtorrent/torrent_info.hpp"
#include "libtorrent/announce_entry.hpp"
#include "libtorrent/entry.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/session.hpp"
#include "libtorrent/session_params.hpp"
#include "libtorrent/identify_client.hpp"
#include "libtorrent/alert_types.hpp"
#include "libtorrent/ip_filter.hpp"
#include "libtorrent/magnet_uri.hpp"
#include "libtorrent/peer_info.hpp"
#include "libtorrent/bdecode.hpp"
#include "libtorrent/add_torrent_params.hpp"
#include "libtorrent/time.hpp"
#include "libtorrent/read_resume_data.hpp"
#include "libtorrent/write_resume_data.hpp"
#include "libtorrent/string_view.hpp"
#include "libtorrent/disk_interface.hpp" // for open_file_state
#include "libtorrent/disabled_disk_io.hpp" // for disabled_disk_io_constructor
#include "libtorrent/load_torrent.hpp"
#include "torrent_view.hpp"
#include "session_view.hpp"
#include "print.hpp"
#ifdef _WIN32
#include <windows.h>
#include <conio.h>
#else
#include <termios.h>
#include <sys/ioctl.h>
#include <csignal>
#include <utility>
#include <dirent.h>
#endif
namespace {
using lt::total_milliseconds;
using lt::alert;
using lt::piece_index_t;
using lt::file_index_t;
using lt::torrent_handle;
using lt::add_torrent_params;
using lt::total_seconds;
using lt::torrent_flags_t;
using lt::seconds;
using lt::operator "" _sv;
using lt::address_v4;
using lt::address_v6;
using lt::make_address_v6;
using lt::make_address_v4;
using lt::make_address;
using std::chrono::duration_cast;
using std::stoi;
#ifdef _WIN32
bool sleep_and_input(int* c, lt::time_duration const sleep)
{
for (int i = 0; i < 2; ++i)
{
if (_kbhit())
{
*c = _getch();
return true;
}
std::this_thread::sleep_for(sleep / 2);
}
return false;
}
#else
struct set_keypress
{
enum terminal_mode {
echo = 1,
canonical = 2
};
explicit set_keypress(std::uint8_t const mode = 0)
{
using ul = unsigned long;
termios new_settings;
tcgetattr(0, &stored_settings);
new_settings = stored_settings;
// Disable canonical mode, and set buffer size to 1 byte
// and disable echo
if (mode & echo) new_settings.c_lflag |= ECHO;
else new_settings.c_lflag &= ul(~ECHO);
if (mode & canonical) new_settings.c_lflag |= ICANON;
else new_settings.c_lflag &= ul(~ICANON);
new_settings.c_cc[VTIME] = 0;
new_settings.c_cc[VMIN] = 1;
tcsetattr(0,TCSANOW,&new_settings);
}
~set_keypress() { tcsetattr(0, TCSANOW, &stored_settings); }
private:
termios stored_settings;
};
bool sleep_and_input(int* c, lt::time_duration const sleep)
{
lt::time_point const done = lt::clock_type::now() + sleep;
int ret = 0;
retry:
fd_set set;
FD_ZERO(&set);
FD_SET(0, &set);
auto const delay = total_milliseconds(done - lt::clock_type::now());
timeval tv = {int(delay / 1000), int((delay % 1000) * 1000) };
ret = select(1, &set, nullptr, nullptr, &tv);
if (ret > 0)
{
*c = getc(stdin);
return true;
}
if (errno == EINTR)
{
if (lt::clock_type::now() < done)
goto retry;
return false;
}
if (ret < 0 && errno != 0 && errno != ETIMEDOUT)
{
std::fprintf(stderr, "select failed: %s\n", strerror(errno));
std::this_thread::sleep_for(lt::milliseconds(500));
}
return false;
}
#endif
bool print_trackers = false;
bool print_peers = false;
bool print_peers_legend = false;
bool print_connecting_peers = false;
bool print_log = false;
bool print_downloads = false;
bool print_matrix = false;
bool print_file_progress = false;
bool print_piece_availability = false;
bool show_pad_files = false;
bool show_dht_status = false;
bool print_ip = true;
bool print_peaks = false;
bool print_local_ip = false;
bool print_timers = false;
bool print_block = false;
bool print_fails = false;
bool print_send_bufs = true;
bool print_disk_stats = false;
// the number of times we've asked to save resume data
// without having received a response (successful or failure)
int num_outstanding_resume_data = 0;
#ifndef TORRENT_DISABLE_DHT
std::vector<lt::dht_lookup> dht_active_requests;
std::vector<lt::dht_routing_bucket> dht_routing_table;
#endif
std::string to_hex(lt::sha1_hash const& s)
{
std::stringstream ret;
ret << s;
return ret.str();
}
bool load_file(std::string const& filename, std::vector<char>& v
, int limit = 8000000)
{
std::fstream f(filename, std::ios_base::in | std::ios_base::binary);
f.seekg(0, std::ios_base::end);
auto const s = f.tellg();
if (s > limit || s < 0) return false;
f.seekg(0, std::ios_base::beg);
v.resize(static_cast<std::size_t>(s));
if (s == std::fstream::pos_type(0)) return !f.fail();
f.read(v.data(), int(v.size()));
return !f.fail();
}
bool is_absolute_path(std::string const& f)
{
if (f.empty()) return false;
#if defined(TORRENT_WINDOWS) || defined(TORRENT_OS2)
int i = 0;
// match the xx:\ or xx:/ form
while (f[i] && strchr("abcdefghijklmnopqrstuvxyzABCDEFGHIJKLMNOPQRSTUVXYZ", f[i])) ++i;
if (i < int(f.size()-1) && f[i] == ':' && (f[i+1] == '\\' || f[i+1] == '/'))
return true;
// match the \\ form
if (int(f.size()) >= 2 && f[0] == '\\' && f[1] == '\\')
return true;
return false;
#else
if (f[0] == '/') return true;
return false;
#endif
}
std::string path_append(std::string const& lhs, std::string const& rhs)
{
if (lhs.empty() || lhs == ".") return rhs;
if (rhs.empty() || rhs == ".") return lhs;
#if defined(TORRENT_WINDOWS) || defined(TORRENT_OS2)
#define TORRENT_SEPARATOR "\\"
bool need_sep = lhs[lhs.size()-1] != '\\' && lhs[lhs.size()-1] != '/';
#else
#define TORRENT_SEPARATOR "/"
bool need_sep = lhs[lhs.size()-1] != '/';
#endif
return lhs + (need_sep?TORRENT_SEPARATOR:"") + rhs;
}
std::string make_absolute_path(std::string const& p)
{
if (is_absolute_path(p)) return p;
std::string ret;
#if defined TORRENT_WINDOWS
char* cwd = ::_getcwd(nullptr, 0);
ret = path_append(cwd, p);
std::free(cwd);
#else
char* cwd = ::getcwd(nullptr, 0);
ret = path_append(cwd, p);
std::free(cwd);
#endif
return ret;
}
std::string print_endpoint(lt::tcp::endpoint const& ep)
{
using namespace lt;
char buf[200];
address const& addr = ep.address();
if (addr.is_v6())
std::snprintf(buf, sizeof(buf), "[%s]:%d", addr.to_string().c_str(), ep.port());
else
std::snprintf(buf, sizeof(buf), "%s:%d", addr.to_string().c_str(), ep.port());
return buf;
}
using lt::torrent_status;
FILE* g_log_file = nullptr;
int peer_index(lt::tcp::endpoint addr, std::vector<lt::peer_info> const& peers)
{
using namespace lt;
auto i = std::find_if(peers.begin(), peers.end()
, [&addr](peer_info const& pi) { return pi.ip == addr; });
if (i == peers.end()) return -1;
return int(i - peers.begin());
}
#if TORRENT_USE_I2P
void base32encode_i2p(lt::sha256_hash const& s, std::string& out, int limit)
{
static char const base32_table[] =
{
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z', '2', '3', '4', '5', '6', '7'
};
static std::array<int, 6> const input_output_mapping{{0, 2, 4, 5, 7, 8}};
std::array<std::uint8_t, 5> inbuf;
std::array<std::uint8_t, 8> outbuf;
TORRENT_ASSERT(s.size() % 5 );
for (auto i = s.begin(); i != s.end();)
{
int const available_input = std::min(int(inbuf.size()), int(s.end() - i));
// clear input buffer
inbuf.fill(0);
// read a chunk of input into inbuf
std::copy(i, i + available_input, inbuf.begin());
i += available_input;
// encode inbuf to outbuf
outbuf[0] = (inbuf[0] & 0xf8) >> 3;
outbuf[1] = (((inbuf[0] & 0x07) << 2) | ((inbuf[1] & 0xc0) >> 6)) & 0xff;
outbuf[2] = ((inbuf[1] & 0x3e) >> 1);
outbuf[3] = (((inbuf[1] & 0x01) << 4) | ((inbuf[2] & 0xf0) >> 4)) & 0xff;
outbuf[4] = (((inbuf[2] & 0x0f) << 1) | ((inbuf[3] & 0x80) >> 7)) & 0xff;
outbuf[5] = ((inbuf[3] & 0x7c) >> 2);
outbuf[6] = (((inbuf[3] & 0x03) << 3) | ((inbuf[4] & 0xe0) >> 5)) & 0xff;
outbuf[7] = inbuf[4] & 0x1f;
// write output
int const num_out = input_output_mapping[std::size_t(available_input)];
for (int j = 0; j < num_out; ++j)
{
out += base32_table[outbuf[std::size_t(j)]];
--limit;
if (limit <= 0) return;
}
}
}
#endif
// returns the number of lines printed
int print_peer_info(std::string& out
, std::vector<lt::peer_info> const& peers, int max_lines)
{
using namespace lt;
int pos = 0;
if (print_ip) out += "IP ";
if (print_local_ip) out += "local IP ";
out += "progress down (total";
if (print_peaks) out += " | peak ";
out += " ) up (total";
if (print_peaks) out += " | peak ";
out += " ) sent-req tmo bsy rcv flags dn up source ";
if (print_fails) out += "fail hshf ";
if (print_send_bufs) out += " rq sndb (recvb |alloc | wmrk ) q-bytes ";
if (print_timers) out += "inactive wait timeout q-time ";
out += " v disk ^ rtt ";
if (print_block) out += "block-progress ";
out += "client \x1b[K\n";
++pos;
char str[500];
for (std::vector<peer_info>::const_iterator i = peers.begin();
i != peers.end(); ++i)
{
if ((i->flags & (peer_info::handshake | peer_info::connecting)
&& !print_connecting_peers))
{
continue;
}
if (print_ip)
{
#if TORRENT_USE_I2P
if (i->flags & peer_info::i2p_socket)
{
base32encode_i2p(i->i2p_destination(), out, 31);
}
else
#endif
{
std::snprintf(str, sizeof(str), "%-30s ", ::print_endpoint(i->ip).c_str());
out += str;
}
}
if (print_local_ip)
{
#if TORRENT_USE_I2P
if (i->flags & peer_info::i2p_socket)
out += " ";
else
#endif
{
std::snprintf(str, sizeof(str), "%-30s ", ::print_endpoint(i->local_endpoint).c_str());
out += str;
}
}
char temp[10];
std::snprintf(temp, sizeof(temp), "%d/%d"
, i->download_queue_length
, i->target_dl_queue_length);
temp[7] = 0;
char peer_progress[10];
std::snprintf(peer_progress, sizeof(peer_progress), "%.1f%%", i->progress_ppm / 10000.0);
std::snprintf(str, sizeof(str)
, "%s %s%s (%s%s) %s%s (%s%s) %s%7s %4d%4d%4d %s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s %s%s%s %s%s%s %s%s%s%s%s%s "
, progress_bar(i->progress_ppm / 1000, 15, col_green, '#', '-', peer_progress).c_str()
, esc("32"), add_suffix(i->down_speed, "/s").c_str()
, add_suffix(i->total_download).c_str()
, print_peaks ? ("|" + add_suffix(i->download_rate_peak, "/s")).c_str() : ""
, esc("31"), add_suffix(i->up_speed, "/s").c_str(), add_suffix(i->total_upload).c_str()
, print_peaks ? ("|" + add_suffix(i->upload_rate_peak, "/s")).c_str() : ""
, esc("0")
, temp // sent requests and target number of outstanding reqs.
, i->timed_out_requests
, i->busy_requests
, i->upload_queue_length
, color("I", (i->flags & peer_info::interesting)?col_white:col_blue).c_str()
, color("C", (i->flags & peer_info::choked)?col_white:col_blue).c_str()
, color("i", (i->flags & peer_info::remote_interested)?col_white:col_blue).c_str()
, color("c", (i->flags & peer_info::remote_choked)?col_white:col_blue).c_str()
, color("x", (i->flags & peer_info::supports_extensions)?col_white:col_blue).c_str()
, color("o", (i->flags & peer_info::local_connection)?col_white:col_blue).c_str()
, color("p", (i->flags & peer_info::on_parole)?col_white:col_blue).c_str()
, color("O", (i->flags & peer_info::optimistic_unchoke)?col_white:col_blue).c_str()
, color("S", (i->flags & peer_info::snubbed)?col_white:col_blue).c_str()
, color("U", (i->flags & peer_info::upload_only)?col_white:col_blue).c_str()
, color("e", (i->flags & peer_info::endgame_mode)?col_white:col_blue).c_str()
, color("E", (i->flags & peer_info::rc4_encrypted)?col_white:(i->flags & peer_info::plaintext_encrypted)?col_cyan:col_blue).c_str()
, color("h", (i->flags & peer_info::holepunched)?col_white:col_blue).c_str()
, color("s", (i->flags & peer_info::seed)?col_white:col_blue).c_str()
, color("u", (i->flags & peer_info::utp_socket)?col_white:col_blue).c_str()
, color("I", (i->flags & peer_info::i2p_socket)?col_white:col_blue).c_str()
, color("d", (i->read_state & peer_info::bw_disk)?col_white:col_blue).c_str()
, color("l", (i->read_state & peer_info::bw_limit)?col_white:col_blue).c_str()
, color("n", (i->read_state & peer_info::bw_network)?col_white:col_blue).c_str()
, color("d", (i->write_state & peer_info::bw_disk)?col_white:col_blue).c_str()
, color("l", (i->write_state & peer_info::bw_limit)?col_white:col_blue).c_str()
, color("n", (i->write_state & peer_info::bw_network)?col_white:col_blue).c_str()
, color("t", (i->source & peer_info::tracker)?col_white:col_blue).c_str()
, color("p", (i->source & peer_info::pex)?col_white:col_blue).c_str()
, color("d", (i->source & peer_info::dht)?col_white:col_blue).c_str()
, color("l", (i->source & peer_info::lsd)?col_white:col_blue).c_str()
, color("r", (i->source & peer_info::resume_data)?col_white:col_blue).c_str()
, color("i", (i->source & peer_info::incoming)?col_white:col_blue).c_str());
out += str;
if (print_fails)
{
std::snprintf(str, sizeof(str), "%4d %4d "
, i->failcount, i->num_hashfails);
out += str;
}
if (print_send_bufs)
{
std::snprintf(str, sizeof(str), "%3d %6s %6s|%6s|%6s%7s "
, i->requests_in_buffer
, add_suffix(i->used_send_buffer).c_str()
, add_suffix(i->used_receive_buffer).c_str()
, add_suffix(i->receive_buffer_size).c_str()
, add_suffix(i->receive_buffer_watermark).c_str()
, add_suffix(i->queue_bytes).c_str());
out += str;
}
if (print_timers)
{
char req_timeout[20] = "-";
// timeout is only meaningful if there is at least one outstanding
// request to the peer
if (i->download_queue_length > 0)
std::snprintf(req_timeout, sizeof(req_timeout), "%d", i->request_timeout);
std::snprintf(str, sizeof(str), "%8d %4d %7s %6d "
, int(total_seconds(i->last_active))
, int(total_seconds(i->last_request))
, req_timeout
, int(total_seconds(i->download_queue_time)));
out += str;
}
std::snprintf(str, sizeof(str), "%s|%s %5d "
, add_suffix(i->pending_disk_bytes).c_str()
, add_suffix(i->pending_disk_read_bytes).c_str()
, i->rtt);
out += str;
if (print_block)
{
if (i->downloading_piece_index >= piece_index_t(0))
{
char buf[50];
std::snprintf(buf, sizeof(buf), "%d:%d"
, static_cast<int>(i->downloading_piece_index), i->downloading_block_index);
out += progress_bar(
i->downloading_progress * 1000 / i->downloading_total, 14, col_green, '-', '#', buf);
}
else
{
out += progress_bar(0, 14);
}
}
out += " ";
if (i->flags & lt::peer_info::handshake)
{
out += esc("31");
out += " waiting for handshake";
out += esc("0");
}
else if (i->flags & lt::peer_info::connecting)
{
out += esc("31");
out += " connecting to peer";
out += esc("0");
}
else
{
out += " ";
out += i->client;
}
out += "\x1b[K\n";
++pos;
if (pos >= max_lines) break;
}
return pos;
}
// returns the number of lines printed
int print_peer_legend(std::string& out, int max_lines)
{
#ifdef _MSC_VER
#pragma warning(push, 1)
// warning C4566: character represented by universal-character-name '\u256F'
// cannot be represented in the current code page (1252)
#pragma warning(disable: 4566)
#endif
std::array<char const*, 13> lines{{
" we are interested \u2500\u2500\u2500\u256f\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502 \u2502\u2502\u2502 \u2502\u2502\u2502 \u2502\u2502\u2502\u2502\u2502\u2570\u2500\u2500\u2500 incoming\x1b[K\n",
" we have choked \u2500\u2500\u2500\u256f\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502 \u2502\u2502\u2502 \u2502\u2502\u2502 \u2502\u2502\u2502\u2502\u2570\u2500\u2500\u2500 resume data\x1b[K\n",
"remote is interested \u2500\u2500\u2500\u256f\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502 \u2502\u2502\u2502 \u2502\u2502\u2502 \u2502\u2502\u2502\u2570\u2500\u2500\u2500 local peer discovery\x1b[K\n",
" remote has choked \u2500\u2500\u2500\u256f\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502 \u2502\u2502\u2502 \u2502\u2502\u2502 \u2502\u2502\u2570\u2500\u2500\u2500 DHT\x1b[K\n",
" supports extensions \u2500\u2500\u2500\u256f\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502 \u2502\u2502\u2502 \u2502\u2502\u2502 \u2502\u2570\u2500\u2500\u2500 peer exchange\x1b[K\n",
" outgoing connection \u2500\u2500\u2500\u256f\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502 \u2502\u2502\u2502 \u2502\u2502\u2502 \u2570\u2500\u2500\u2500 tracker\x1b[K\n",
" on parole \u2500\u2500\u2500\u256f\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502 \u2502\u2502\u2570\u2500\u253c\u253c\u2534\u2500\u2500\u2500 network\x1b[K\n",
" optimistic unchoke \u2500\u2500\u2500\u256f\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502 \u2502\u2570\u2500\u2500\u253c\u2534\u2500\u2500\u2500 rate limit\x1b[K\n",
" snubbed \u2500\u2500\u2500\u256f\u2502\u2502\u2502\u2502\u2502\u2502\u2502 \u2570\u2500\u2500\u2500\u2534\u2500\u2500\u2500 disk\x1b[K\n",
" upload only \u2500\u2500\u2500\u256f\u2502\u2502\u2502\u2502\u2502\u2570\u2500\u2500\u2500 i2p\x1b[K\n",
" end-game mode \u2500\u2500\u2500\u256f\u2502\u2502\u2502\u2570\u2500\u2500\u2500 uTP\x1b[K\n",
" obfuscation level \u2500\u2500\u2500\u256f\u2502\u2570\u2500\u2500\u2500 seed\x1b[K\n",
" hole-punched \u2500\u2500\u2500\u256f\x1b[K\n",
}};
#ifdef _MSC_VER
#pragma warning(pop)
#endif
char const* ip = " ";
char const* indentation = " ";
int ret = 0;
for (auto const& l : lines)
{
if (max_lines <= 0) break;
++ret;
out += indentation;
if (print_ip)
out += ip;
if (print_local_ip)
out += ip;
out += l;
}
return ret;
}
lt::storage_mode_t allocation_mode = lt::storage_mode_sparse;
std::string save_path(".");
int torrent_upload_limit = 0;
int torrent_download_limit = 0;
std::string monitor_dir;
int poll_interval = 5;
int max_connections_per_torrent = 50;
bool seed_mode = false;
bool stats_enabled = false;
bool exit_on_finish = false;
bool share_mode = false;
bool quit = false;
#ifndef _WIN32
void signal_handler(int)
{
// make the main loop terminate
quit = true;
}
#endif
// if non-empty, a peer that will be added to all torrents
std::string peer;
void print_settings(int const start, int const num
, char const* const type)
{
for (int i = start; i < start + num; ++i)
{
char const* name = lt::name_for_setting(i);
if (!name || name[0] == '\0') continue;
std::printf("%s=<%s>\n", name, type);
}
}
void assign_setting(lt::settings_pack& settings, std::string const& key, char const* value)
{
int const sett_name = lt::setting_by_name(key);
if (sett_name < 0)
{
std::fprintf(stderr, "unknown setting: \"%s\"\n", key.c_str());
std::exit(1);
}
using lt::settings_pack;
switch (sett_name & settings_pack::type_mask)
{
case settings_pack::string_type_base:
settings.set_str(sett_name, value);
break;
case settings_pack::bool_type_base:
if (value == "1"_sv || value == "on"_sv || value == "true"_sv)
{
settings.set_bool(sett_name, true);
}
else if (value == "0"_sv || value == "off"_sv || value == "false"_sv)
{
settings.set_bool(sett_name, false);
}
else
{
std::fprintf(stderr, "invalid value for \"%s\". expected 0 or 1\n"
, key.c_str());
std::exit(1);
}
break;
case settings_pack::int_type_base:
using namespace lt::literals;
static std::map<lt::string_view, int> const enums = {
{"no_piece_suggestions"_sv, settings_pack::no_piece_suggestions},
{"suggest_read_cache"_sv, settings_pack::suggest_read_cache},
{"fixed_slots_choker"_sv, settings_pack::fixed_slots_choker},
{"rate_based_choker"_sv, settings_pack::rate_based_choker},
{"round_robin"_sv, settings_pack::round_robin},
{"fastest_upload"_sv, settings_pack::fastest_upload},
{"anti_leech"_sv, settings_pack::anti_leech},
{"enable_os_cache"_sv, settings_pack::enable_os_cache},
{"disable_os_cache"_sv, settings_pack::disable_os_cache},
{"write_through"_sv, settings_pack::write_through},
{"prefer_tcp"_sv, settings_pack::prefer_tcp},
{"peer_proportional"_sv, settings_pack::peer_proportional},
{"pe_forced"_sv, settings_pack::pe_forced},
{"pe_enabled"_sv, settings_pack::pe_enabled},
{"pe_disabled"_sv, settings_pack::pe_disabled},
{"pe_plaintext"_sv, settings_pack::pe_plaintext},
{"pe_rc4"_sv, settings_pack::pe_rc4},
{"pe_both"_sv, settings_pack::pe_both},
{"none"_sv, settings_pack::none},
{"socks4"_sv, settings_pack::socks4},
{"socks5"_sv, settings_pack::socks5},
{"socks5_pw"_sv, settings_pack::socks5_pw},
{"http"_sv, settings_pack::http},
{"http_pw"_sv, settings_pack::http_pw},
};
{
auto const it = enums.find(lt::string_view(value));
if (it != enums.end())
{
settings.set_int(sett_name, it->second);
break;
}
}
static std::map<lt::string_view, lt::alert_category_t> const alert_categories = {
{"error"_sv, lt::alert_category::error},
{"peer"_sv, lt::alert_category::peer},
{"port_mapping"_sv, lt::alert_category::port_mapping},
{"storage"_sv, lt::alert_category::storage},
{"tracker"_sv, lt::alert_category::tracker},
{"connect"_sv, lt::alert_category::connect},
{"status"_sv, lt::alert_category::status},
{"ip_block"_sv, lt::alert_category::ip_block},
{"performance_warning"_sv, lt::alert_category::performance_warning},
{"dht"_sv, lt::alert_category::dht},
{"session_log"_sv, lt::alert_category::session_log},
{"torrent_log"_sv, lt::alert_category::torrent_log},
{"peer_log"_sv, lt::alert_category::peer_log},
{"incoming_request"_sv, lt::alert_category::incoming_request},
{"dht_log"_sv, lt::alert_category::dht_log},
{"dht_operation"_sv, lt::alert_category::dht_operation},
{"port_mapping_log"_sv, lt::alert_category::port_mapping_log},
{"picker_log"_sv, lt::alert_category::picker_log},
{"file_progress"_sv, lt::alert_category::file_progress},
{"piece_progress"_sv, lt::alert_category::piece_progress},
{"upload"_sv, lt::alert_category::upload},
{"block_progress"_sv, lt::alert_category::block_progress},
{"all"_sv, lt::alert_category::all},
};
std::stringstream flags(value);
std::string f;
lt::alert_category_t val;
while (std::getline(flags, f, ',')) try
{
auto const it = alert_categories.find(f);
if (it == alert_categories.end())
val |= lt::alert_category_t{unsigned(std::stoi(f))};
else
val |= it->second;
}
catch (std::invalid_argument const&)
{
std::fprintf(stderr, "invalid value for \"%s\". expected integer or enum value\n"
, key.c_str());
std::exit(1);
}
settings.set_int(sett_name, val);
break;
}
}
std::string resume_file(lt::info_hash_t const& info_hash)
{
return path_append(save_path, path_append(".resume"
, to_hex(info_hash.get_best()) + ".resume"));
}
void set_torrent_params(lt::add_torrent_params& p)
{
p.max_connections = max_connections_per_torrent;
p.max_uploads = -1;
p.upload_limit = torrent_upload_limit;
p.download_limit = torrent_download_limit;
if (seed_mode) p.flags |= lt::torrent_flags::seed_mode;
if (share_mode) p.flags |= lt::torrent_flags::share_mode;
p.save_path = save_path;
p.storage_mode = allocation_mode;
}
void add_magnet(lt::session& ses, lt::string_view uri)
{
lt::error_code ec;
lt::add_torrent_params p = lt::parse_magnet_uri(uri.to_string(), ec);
if (ec)
{
std::printf("invalid magnet link \"%s\": %s\n"
, uri.to_string().c_str(), ec.message().c_str());
return;
}
std::vector<char> resume_data;
if (load_file(resume_file(p.info_hashes), resume_data))
{
p = lt::read_resume_data(resume_data, ec);
if (ec) std::printf(" failed to load resume data: %s\n", ec.message().c_str());
}
set_torrent_params(p);
std::printf("adding magnet: %s\n", uri.to_string().c_str());
ses.async_add_torrent(std::move(p));
}
// return false on failure
bool add_torrent(lt::session& ses, std::string torrent) try
{
using lt::storage_mode_t;
static int counter = 0;
std::printf("[%d] %s\n", counter++, torrent.c_str());
lt::error_code ec;
lt::add_torrent_params atp = lt::load_torrent_file(torrent);
std::vector<char> resume_data;
if (load_file(resume_file(atp.info_hashes), resume_data))
{
lt::add_torrent_params rd = lt::read_resume_data(resume_data, ec);
if (ec) std::printf(" failed to load resume data: %s\n", ec.message().c_str());
else atp = rd;
}
set_torrent_params(atp);
atp.flags &= ~lt::torrent_flags::duplicate_is_error;
ses.async_add_torrent(std::move(atp));
return true;
}
catch (lt::system_error const& e)
{
std::printf("failed to load torrent \"%s\": %s\n"
, torrent.c_str(), e.code().message().c_str());
return false;
}
std::vector<std::string> list_dir(std::string path
, bool (*filter_fun)(lt::string_view)
, lt::error_code& ec)
{
std::vector<std::string> ret;
#ifdef TORRENT_WINDOWS
if (!path.empty() && path[path.size()-1] != '\\') path += "\\*";
else path += "*";
WIN32_FIND_DATAA fd;
HANDLE handle = FindFirstFileA(path.c_str(), &fd);
if (handle == INVALID_HANDLE_VALUE)
{
ec.assign(GetLastError(), boost::system::system_category());
return ret;
}
do
{
lt::string_view p = fd.cFileName;
if (filter_fun(p))
ret.push_back(p.to_string());
} while (FindNextFileA(handle, &fd));
FindClose(handle);
#else
if (!path.empty() && path[path.size()-1] == '/')
path.resize(path.size()-1);
DIR* handle = opendir(path.c_str());
if (handle == nullptr)
{
ec.assign(errno, boost::system::system_category());
return ret;
}
struct dirent* de;
while ((de = readdir(handle)))
{
lt::string_view p(de->d_name);
if (filter_fun(p))
ret.push_back(p.to_string());
}
closedir(handle);
#endif
return ret;
}
void scan_dir(std::string const& dir_path, lt::session& ses)
{
using namespace lt;
error_code ec;
std::vector<std::string> ents = list_dir(dir_path
, [](lt::string_view p) { return p.size() > 8 && p.substr(p.size() - 8) == ".torrent"; }, ec);
if (ec)
{
std::fprintf(stderr, "failed to list directory: (%s : %d) %s\n"
, ec.category().name(), ec.value(), ec.message().c_str());
return;
}
for (auto const& e : ents)
{
std::string const file = path_append(dir_path, e);
// there's a new file in the monitor directory, load it up
if (add_torrent(ses, file))
{
if (::remove(file.c_str()) < 0)
{
std::fprintf(stderr, "failed to remove torrent file: \"%s\"\n"
, file.c_str());
}
}
}
}
char const* timestamp()
{
time_t t = std::time(nullptr);
#ifdef TORRENT_WINDOWS
std::tm const* timeinfo = localtime(&t);
#else
std::tm buf;
std::tm const* timeinfo = localtime_r(&t, &buf);
#endif
static char str[200];
std::strftime(str, 200, "%b %d %X", timeinfo);
return str;
}
void print_alert(lt::alert const* a, std::string& str)
{
using namespace lt;
if (a->category() & alert_category::error)
{
str += esc("31");
}
else if (a->category() & (alert_category::peer | alert_category::storage))
{
str += esc("33");
}
str += "[";
str += timestamp();
str += "] ";
str += a->message();
str += esc("0");
static auto const first_ts = a->timestamp();
if (g_log_file)
std::fprintf(g_log_file, "[%" PRId64 "] %s\n"
, std::int64_t(duration_cast<std::chrono::milliseconds>(a->timestamp() - first_ts).count())
, a->message().c_str());
}
int save_file(std::string const& filename, std::vector<char> const& v)
{
std::fstream f(filename, std::ios_base::trunc | std::ios_base::out | std::ios_base::binary);
f.write(v.data(), int(v.size()));
return !f.fail();
}
struct client_state_t
{
torrent_view& view;
session_view& ses_view;
std::deque<std::string> events;
std::vector<lt::peer_info> peers;
std::vector<std::int64_t> file_progress;
std::vector<lt::partial_piece_info> download_queue;
std::vector<lt::block_info> download_queue_block_info;
std::vector<int> piece_availability;
std::vector<lt::announce_entry> trackers;
void clear()
{
peers.clear();
file_progress.clear();
download_queue.clear();
download_queue_block_info.clear();
piece_availability.clear();