forked from arvidn/libtorrent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_dht.cpp
4089 lines (3414 loc) · 122 KB
/
test_dht.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) 2009-2020, Arvid Norberg
Copyright (c) 2015, Thomas Yuan
Copyright (c) 2015-2019, Steven Siloti
Copyright (c) 2016-2018, Alden Torres
Copyright (c) 2020, Fonic
Copyright (c) 2020, FranciscoPombal
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 "test.hpp"
#ifndef TORRENT_DISABLE_DHT
#include "libtorrent/config.hpp"
#include "libtorrent/session.hpp"
#include "libtorrent/kademlia/msg.hpp" // for verify_message
#include "libtorrent/kademlia/node.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/bdecode.hpp"
#include "libtorrent/socket_io.hpp" // for hash_address
#include "libtorrent/aux_/ip_helpers.hpp"
#include "libtorrent/performance_counters.hpp" // for counters
#include "libtorrent/random.hpp"
#include "libtorrent/kademlia/ed25519.hpp"
#include "libtorrent/hex.hpp" // to_hex, from_hex
#include "libtorrent/bloom_filter.hpp"
#include "libtorrent/hasher.hpp"
#include "libtorrent/aux_/time.hpp"
#include "libtorrent/aux_/listen_socket_handle.hpp"
#include "libtorrent/aux_/session_impl.hpp"
#include "libtorrent/kademlia/node_id.hpp"
#include "libtorrent/kademlia/routing_table.hpp"
#include "libtorrent/kademlia/item.hpp"
#include "libtorrent/kademlia/dht_observer.hpp"
#include "libtorrent/kademlia/dht_tracker.hpp"
#include <numeric>
#include <cstdarg>
#include <tuple>
#include <iostream>
#include <iomanip>
#include <cstdio> // for vsnprintf
#include "setup_transfer.hpp"
using namespace lt;
using namespace lt::dht;
using namespace std::placeholders;
namespace {
void get_test_keypair(public_key& pk, secret_key& sk)
{
aux::from_hex({"77ff84905a91936367c01360803104f92432fcd904a43511876df5cdf3e7e548", 64}
, pk.bytes.data());
aux::from_hex({"e06d3183d14159228433ed599221b80bd0a5ce8352e4bdf0262f76786ef1c74d"
"b7e7a9fea2c0eb269d61e3b38e450a22e754941ac78479d6c54e1faf6037881d", 128}
, sk.bytes.data());
}
sequence_number prev_seq(sequence_number s)
{
return sequence_number(s.value - 1);
}
sequence_number next_seq(sequence_number s)
{
return sequence_number(s.value + 1);
}
void add_and_replace(node_id& dst, node_id const& add)
{
bool carry = false;
for (int k = 19; k >= 0; --k)
{
int sum = dst[k] + add[k] + (carry ? 1 : 0);
dst[k] = sum & 255;
carry = sum > 255;
}
}
void node_push_back(std::vector<node_entry>* nv, node_entry const& n)
{
nv->push_back(n);
}
void nop_node() {}
// TODO: 3 make the mock_socket hold a reference to the list of where to record
// packets instead of having a global variable
std::list<std::pair<udp::endpoint, entry>> g_sent_packets;
struct mock_socket final : socket_manager
{
bool has_quota() override { return true; }
bool send_packet(aux::listen_socket_handle const&, entry& msg, udp::endpoint const& ep) override
{
// TODO: 3 ideally the mock_socket would contain this queue of packets, to
// make tests independent
g_sent_packets.push_back(std::make_pair(ep, msg));
return true;
}
};
std::shared_ptr<aux::listen_socket_t> dummy_listen_socket(udp::endpoint src)
{
auto ret = std::make_shared<aux::listen_socket_t>();
ret->local_endpoint = tcp::endpoint(src.address(), src.port());
ret->external_address.cast_vote(src.address()
, aux::session_interface::source_dht, rand_v4());
return ret;
}
std::shared_ptr<aux::listen_socket_t> dummy_listen_socket4()
{
auto ret = std::make_shared<aux::listen_socket_t>();
ret->local_endpoint = tcp::endpoint(addr4("192.168.4.1"), 6881);
ret->external_address.cast_vote(addr4("236.0.0.1")
, aux::session_interface::source_dht, rand_v4());
return ret;
}
std::shared_ptr<aux::listen_socket_t> dummy_listen_socket6()
{
auto ret = std::make_shared<aux::listen_socket_t>();
ret->local_endpoint = tcp::endpoint(addr6("2002::1"), 6881);
ret->external_address.cast_vote(addr6("2002::1")
, aux::session_interface::source_dht, rand_v6());
return ret;
}
node* get_foreign_node_stub(node_id const&, std::string const&)
{
return nullptr;
}
sha1_hash generate_next()
{
sha1_hash ret;
aux::random_bytes(ret);
return ret;
}
std::list<std::pair<udp::endpoint, entry>>::iterator
find_packet(udp::endpoint ep)
{
return std::find_if(g_sent_packets.begin(), g_sent_packets.end()
, [&ep] (std::pair<udp::endpoint, entry> const& p)
{ return p.first == ep; });
}
void node_from_entry(entry const& e, bdecode_node& l)
{
error_code ec;
static char inbuf[1500];
int len = bencode(inbuf, e);
int ret = bdecode(inbuf, inbuf + len, l, ec);
TEST_CHECK(ret == 0);
}
entry write_peers(std::set<tcp::endpoint> const& peers)
{
entry r;
entry::list_type& pe = r.list();
for (auto const& p : peers)
{
std::string endpoint(18, '\0');
std::string::iterator out = endpoint.begin();
lt::aux::write_endpoint(p, out);
endpoint.resize(std::size_t(out - endpoint.begin()));
pe.push_back(entry(endpoint));
}
return r;
}
struct msg_args
{
msg_args& info_hash(char const* i)
{ if (i) a["info_hash"] = std::string(i, 20); return *this; }
msg_args& name(char const* n)
{ if (n) a["n"] = n; return *this; }
msg_args& token(std::string t)
{ a["token"] = t; return *this; }
msg_args& port(int p)
{ a["port"] = p; return *this; }
msg_args& target(sha1_hash const& t)
{ a["target"] = t.to_string(); return *this; }
msg_args& value(entry const& v)
{ a["v"] = v; return *this; }
msg_args& scrape(bool s)
{ a["scrape"] = s ? 1 : 0; return *this; }
msg_args& seed(bool s)
{ a["seed"] = s ? 1 : 0; return *this; }
msg_args& key(public_key const& k)
{ a["k"] = k.bytes; return *this; }
msg_args& sig(signature const& s)
{ a["sig"] = s.bytes; return *this; }
msg_args& seq(sequence_number s)
{ a["seq"] = s.value; return *this; }
msg_args& cas(sequence_number c)
{ a["cas"] = c.value; return *this; }
msg_args& nid(sha1_hash const& n)
{ a["id"] = n.to_string(); return *this; }
msg_args& salt(span<char const> s)
{ if (!s.empty()) a["salt"] = s; return *this; }
msg_args& want(std::string w)
{ a["want"].list().push_back(w); return *this; }
msg_args& nodes(std::vector<node_entry> const& n)
{ if (!n.empty()) a["nodes"] = dht::write_nodes_entry(n); return *this; }
msg_args& nodes6(std::vector<node_entry> const& n)
{ if (!n.empty()) a["nodes6"] = dht::write_nodes_entry(n); return *this; }
msg_args& peers(std::set<tcp::endpoint> const& p)
{ if (!p.empty()) a.dict()["values"] = write_peers(p); return *this; }
msg_args& interval(time_duration interval)
{ a["interval"] = total_seconds(interval); return *this; }
msg_args& num(int num)
{ a["num"] = num; return *this; }
msg_args& samples(std::vector<sha1_hash> const& samples)
{
a["samples"] = span<char const>(
reinterpret_cast<char const*>(samples.data()), int(samples.size()) * 20);
return *this;
}
entry a;
};
void send_dht_request(node& node, char const* msg, udp::endpoint const& ep
, bdecode_node* reply, msg_args const& args = msg_args()
, char const* t = "10", bool has_response = true)
{
// we're about to clear out the backing buffer
// for this bdecode_node, so we better clear it now
reply->clear();
entry e;
e["q"] = msg;
e["t"] = t;
e["y"] = "q";
e["a"] = args.a;
e["a"].dict().insert(std::make_pair("id", generate_next().to_string()));
char msg_buf[1500];
int size = bencode(msg_buf, e);
bdecode_node decoded;
error_code ec;
bdecode(msg_buf, msg_buf + size, decoded, ec);
if (ec) std::printf("bdecode failed: %s\n", ec.message().c_str());
dht::msg m(decoded, ep);
node.incoming(node.m_sock, m);
// If the request is supposed to get a response, by now the node should have
// invoked the send function and put the response in g_sent_packets
auto const i = find_packet(ep);
if (has_response)
{
if (i == g_sent_packets.end())
{
TEST_ERROR("not response from DHT node");
return;
}
node_from_entry(i->second, *reply);
g_sent_packets.erase(i);
return;
}
// this request suppose won't be responsed.
if (i != g_sent_packets.end())
{
TEST_ERROR("shouldn't have response from DHT node");
return;
}
}
void send_dht_response(node& node, bdecode_node const& request, udp::endpoint const& ep
, msg_args const& args = msg_args())
{
entry e;
e["y"] = "r";
e["t"] = request.dict_find_string_value("t").to_string();
// e["ip"] = endpoint_to_bytes(ep);
e["r"] = args.a;
e["r"].dict().insert(std::make_pair("id", generate_next().to_string()));
char msg_buf[1500];
int const size = bencode(msg_buf, e);
bdecode_node decoded;
error_code ec;
bdecode(msg_buf, msg_buf + size, decoded, ec);
if (ec) std::printf("bdecode failed: %s\n", ec.message().c_str());
dht::msg m(decoded, ep);
node.incoming(node.m_sock, m);
}
struct announce_item
{
announce_item(sha1_hash nxt, int const num)
: next(nxt)
, num_peers(num)
{
num_peers = int(lt::random(5) + 2);
ent["next"] = next.to_string();
ent["A"] = "a";
ent["B"] = "b";
ent["num_peers"] = num_peers;
char buf[512];
char* ptr = buf;
int len = bencode(ptr, ent);
target = hasher(buf, len).final();
}
sha1_hash next;
int num_peers;
entry ent;
sha1_hash target;
};
void announce_immutable_items(node& node, udp::endpoint const* eps
, announce_item const* items, int num_items)
{
std::string token;
for (int i = 0; i < 1000; ++i)
{
for (int j = 0; j < num_items; ++j)
{
if ((i % items[j].num_peers) == 0) continue;
bdecode_node response;
send_dht_request(node, "get", eps[i], &response
, msg_args().target(items[j].target));
key_desc_t const desc[] =
{
{ "r", bdecode_node::dict_t, 0, key_desc_t::parse_children },
{ "id", bdecode_node::string_t, 20, 0},
{ "token", bdecode_node::string_t, 0, 0},
{ "ip", bdecode_node::string_t, 0, key_desc_t::optional | key_desc_t::last_child},
{ "y", bdecode_node::string_t, 1, 0},
};
bdecode_node parsed[5];
char error_string[200];
// std::printf("msg: %s\n", print_entry(response).c_str());
int ret = verify_message(response, desc, parsed, error_string);
if (ret)
{
TEST_EQUAL(parsed[4].string_value(), "r");
token = parsed[2].string_value().to_string();
// std::printf("got token: %s\n", token.c_str());
}
else
{
std::printf("msg: %s\n", print_entry(response).c_str());
std::printf(" invalid get response: %s\n", error_string);
TEST_ERROR(error_string);
}
if (parsed[3])
{
address_v4::bytes_type b;
memcpy(&b[0], parsed[3].string_ptr(), b.size());
address_v4 addr(b);
TEST_EQUAL(addr, eps[i].address());
}
send_dht_request(node, "put", eps[i], &response
, msg_args()
.token(token)
.target(items[j].target)
.value(items[j].ent));
key_desc_t const desc2[] =
{
{ "y", bdecode_node::string_t, 1, 0 }
};
bdecode_node parsed2[1];
ret = verify_message(response, desc2, parsed2, error_string);
if (ret)
{
if (parsed2[0].string_value() != "r")
std::printf("msg: %s\n", print_entry(response).c_str());
TEST_EQUAL(parsed2[0].string_value(), "r");
}
else
{
std::printf("msg: %s\n", print_entry(response).c_str());
std::printf(" invalid put response: %s\n", error_string);
TEST_ERROR(error_string);
}
}
}
std::set<int> items_num;
for (int j = 0; j < num_items; ++j)
{
bdecode_node response;
send_dht_request(node, "get", eps[j], &response
, msg_args().target(items[j].target));
key_desc_t const desc[] =
{
{ "r", bdecode_node::dict_t, 0, key_desc_t::parse_children },
{ "v", bdecode_node::dict_t, 0, 0},
{ "id", bdecode_node::string_t, 20, key_desc_t::last_child},
{ "y", bdecode_node::string_t, 1, 0},
};
bdecode_node parsed[4];
char error_string[200];
int ret = verify_message(response, desc, parsed, error_string);
if (ret)
{
items_num.insert(items_num.begin(), j);
}
}
// TODO: check to make sure the "best" items are stored
TEST_EQUAL(items_num.size(), 4);
}
int sum_distance_exp(int s, node_entry const& e, node_id const& ref)
{
return s + distance_exp(e.id, ref);
}
std::vector<tcp::endpoint> g_got_peers;
void get_peers_cb(std::vector<tcp::endpoint> const& peers)
{
g_got_peers.insert(g_got_peers.end(), peers.begin(), peers.end());
}
std::vector<dht::item> g_got_items;
dht::item g_put_item;
int g_put_count;
void get_mutable_item_cb(dht::item const& i, bool a)
{
if (!a) return;
if (!i.empty())
g_got_items.push_back(i);
}
void put_mutable_item_data_cb(dht::item& i)
{
if (!i.empty())
g_got_items.push_back(i);
TEST_CHECK(!g_put_item.empty());
i = g_put_item;
g_put_count++;
}
void put_mutable_item_cb(dht::item const&, int num, int expect)
{
TEST_EQUAL(num, expect);
}
void get_immutable_item_cb(dht::item const& i)
{
if (!i.empty())
g_got_items.push_back(i);
}
void put_immutable_item_cb(int num, int expect)
{
TEST_EQUAL(num, expect);
}
struct obs : dht::dht_observer
{
void set_external_address(aux::listen_socket_handle const& s, address const& addr
, address const& /*source*/) override
{
s.get()->external_address.cast_vote(addr
, aux::session_interface::source_dht, rand_v4());
}
int get_listen_port(aux::transport, aux::listen_socket_handle const& s) override
{ return s.get()->udp_external_port(); }
void get_peers(sha1_hash const&) override {}
void outgoing_get_peers(sha1_hash const& /*target*/
, sha1_hash const& /*sent_target*/, udp::endpoint const&) override {}
void announce(sha1_hash const&, address const&, int) override {}
#ifndef TORRENT_DISABLE_LOGGING
bool should_log(module_t) const override { return true; }
void log(dht_logger::module_t, char const* fmt, ...) override
{
va_list v;
va_start(v, fmt);
char buf[1024];
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wformat-nonliteral"
#endif
std::vsnprintf(buf, sizeof(buf), fmt, v);
#ifdef __clang__
#pragma clang diagnostic pop
#endif
va_end(v);
std::printf("%s\n", buf);
m_log.emplace_back(buf);
}
void log_packet(message_direction_t, span<char const>
, udp::endpoint const&) override {}
#endif
bool on_dht_request(string_view
, dht::msg const&, entry&) override { return false; }
virtual ~obs() = default;
#ifndef TORRENT_DISABLE_LOGGING
std::vector<std::string> m_log;
#endif
};
aux::session_settings test_settings()
{
aux::session_settings sett;
sett.set_int(settings_pack::dht_max_torrents, 4);
sett.set_int(settings_pack::dht_max_dht_items, 4);
sett.set_bool(settings_pack::dht_enforce_node_id, false);
return sett;
}
struct dht_test_setup
{
explicit dht_test_setup(udp::endpoint src)
: sett(test_settings())
, ls(dummy_listen_socket(src))
, dht_storage(dht_default_storage_constructor(sett))
, source(src)
, dht_node(ls, &s, sett
, node_id(nullptr), &observer, cnt, get_foreign_node_stub, *dht_storage)
{
dht_storage->update_node_ids({node_id::min()});
}
aux::session_settings sett;
mock_socket s;
std::shared_ptr<aux::listen_socket_t> ls;
obs observer;
counters cnt;
std::unique_ptr<dht_storage_interface> dht_storage;
udp::endpoint source;
dht::node dht_node;
char error_string[200];
};
dht::key_desc_t const err_desc[] = {
{"y", bdecode_node::string_t, 1, 0},
{"e", bdecode_node::list_t, 2, 0}
};
dht::key_desc_t const peer1_desc[] = {
{"y", bdecode_node::string_t, 1, 0},
{"r", bdecode_node::dict_t, 0, key_desc_t::parse_children},
{"token", bdecode_node::string_t, 0, 0},
{"id", bdecode_node::string_t, 20, key_desc_t::last_child},
};
dht::key_desc_t const get_item_desc[] = {
{"y", bdecode_node::string_t, 1, 0},
{"t", bdecode_node::string_t, 2, 0},
{"q", bdecode_node::string_t, 3, 0},
{"a", bdecode_node::dict_t, 0, key_desc_t::parse_children},
{"id", bdecode_node::string_t, 20, 0},
{"target", bdecode_node::string_t, 20, key_desc_t::last_child},
};
dht::key_desc_t const put_mutable_item_desc[] = {
{"y", bdecode_node::string_t, 1, 0},
{"t", bdecode_node::string_t, 2, 0},
{"q", bdecode_node::string_t, 3, 0},
{"a", bdecode_node::dict_t, 0, key_desc_t::parse_children},
{"id", bdecode_node::string_t, 20, 0},
{"cas", bdecode_node::string_t, 20, key_desc_t::optional},
{"k", bdecode_node::string_t, public_key::len, 0},
{"seq", bdecode_node::int_t, 0, 0},
{"sig", bdecode_node::string_t, signature::len, 0},
{"token", bdecode_node::string_t, 2, 0},
{"v", bdecode_node::none_t, 0, key_desc_t::last_child},
};
dht::key_desc_t const sample_infohashes_desc[] = {
{"y", bdecode_node::string_t, 1, 0},
{"t", bdecode_node::string_t, 2, 0},
{"q", bdecode_node::string_t, 17, 0},
{"a", bdecode_node::dict_t, 0, key_desc_t::parse_children},
{"id", bdecode_node::string_t, 20, 0},
{"target", bdecode_node::string_t, 20, key_desc_t::last_child},
};
void print_state(std::ostream& os, routing_table const& table)
{
os << "kademlia routing table state\n"
"bucket_size: " << table.bucket_size() << "\n"
"global node count: " << table.num_global_nodes() << "\n"
"node_id: " << aux::to_hex(table.id()) << "\n\n"
"number of nodes per bucket:\n";
int idx = 0;
for (auto i = table.buckets().begin(), end(table.buckets().end());
i != end; ++i, ++idx)
{
os << std::setw(2) << idx << ": ";
for (int k = 0; k < int(i->live_nodes.size()); ++k)
os << "#";
for (int k = 0; k < int(i->replacements.size()); ++k)
os << "-";
os << "\n";
}
time_point now = aux::time_now();
os << "\nnodes:";
int bucket_index = 0;
for (auto i = table.buckets().begin(), end(table.buckets().end());
i != end; ++i, ++bucket_index)
{
os << "\n=== BUCKET == " << bucket_index << " == "
<< i->live_nodes.size() << "|"
<< i->replacements.size() << " ==== \n";
bucket_t nodes = i->live_nodes;
std::sort(nodes.begin(), nodes.end()
, [](node_entry const& lhs, node_entry const& rhs)
{ return lhs.id < rhs.id; }
);
for (auto j = nodes.begin(); j != nodes.end(); ++j)
{
int const bucket_size_limit = table.bucket_limit(bucket_index);
TORRENT_ASSERT_VAL(bucket_size_limit <= 256, bucket_size_limit);
TORRENT_ASSERT_VAL(bucket_size_limit > 0, bucket_size_limit);
bool const last_bucket = bucket_index + 1 == int(table.buckets().size());
int const prefix = classify_prefix(bucket_index, last_bucket
, bucket_size_limit, j->id);
os << " prefix: " << std::hex << std::setw(2) << prefix << std::dec
<< " id: " << aux::to_hex(j->id);
if (j->rtt == 0xffff)
os << " rtt: ";
else
os << " rtt: " << std::setw(4) << j->rtt;
os << " fail: " << std::setw(3) << j->fail_count()
<< " ping: " << j->pinged()
<< " dist: " << distance_exp(table.id(), j->id);
if (j->last_queried == min_time())
os << " query: ";
else
os << " query: " << std::setw(3) << total_seconds(now - j->last_queried);
os << " ip: " << print_endpoint(j->ep());
}
}
os << "\nnode spread per bucket:\n";
bucket_index = 0;
for (auto i = table.buckets().begin(), end(table.buckets().end());
i != end; ++i, ++bucket_index)
{
int const bucket_size_limit = table.bucket_limit(bucket_index);
TORRENT_ASSERT_VAL(bucket_size_limit <= 256, bucket_size_limit);
TORRENT_ASSERT_VAL(bucket_size_limit > 0, bucket_size_limit);
std::array<bool, 256> sub_buckets;
sub_buckets.fill(false);
// the last bucket is special, since it hasn't been split yet, it
// includes that top bit as well
bool const last_bucket = bucket_index + 1 == int(table.buckets().size());
for (auto const& e : i->live_nodes)
{
std::size_t const prefix = static_cast<std::size_t>(
classify_prefix(bucket_index, last_bucket, bucket_size_limit, e.id));
sub_buckets[prefix] = true;
}
os << std::setw(2) << bucket_index << ": [";
for (int j = 0; j < bucket_size_limit; ++j)
{
os << (sub_buckets[static_cast<std::size_t>(j)] ? "X" : " ");
}
os << "]\n";
}
}
} // anonymous namespace
TORRENT_TEST(ping)
{
dht_test_setup t(udp::endpoint(rand_v4(), 20));
bdecode_node response;
send_dht_request(t.dht_node, "ping", t.source, &response);
dht::key_desc_t const pong_desc[] = {
{"y", bdecode_node::string_t, 1, 0},
{"t", bdecode_node::string_t, 2, 0},
{"r", bdecode_node::dict_t, 0, key_desc_t::parse_children},
{"id", bdecode_node::string_t, 20, key_desc_t::last_child},
};
bdecode_node pong_keys[4];
std::printf("msg: %s\n", print_entry(response).c_str());
bool ret = dht::verify_message(response, pong_desc, pong_keys, t.error_string);
TEST_CHECK(ret);
if (ret)
{
TEST_CHECK(pong_keys[0].string_value() == "r");
TEST_CHECK(pong_keys[1].string_value() == "10");
}
else
{
std::printf(" invalid ping response: %s\n", t.error_string);
}
}
TORRENT_TEST(invalid_message)
{
dht_test_setup t(udp::endpoint(rand_v4(), 20));
bdecode_node response;
bdecode_node err_keys[2];
send_dht_request(t.dht_node, "find_node", t.source, &response);
std::printf("msg: %s\n", print_entry(response).c_str());
bool ret = dht::verify_message(response, err_desc, err_keys, t.error_string);
TEST_CHECK(ret);
if (ret)
{
TEST_CHECK(err_keys[0].string_value() == "e");
if (err_keys[1].list_at(0).type() == bdecode_node::int_t
&& err_keys[1].list_at(1).type() == bdecode_node::string_t)
{
TEST_CHECK(err_keys[1].list_at(1).string_value() == "missing 'target' key");
}
else
{
TEST_ERROR("invalid error response");
}
}
else
{
std::printf(" invalid error response: %s\n", t.error_string);
}
}
TORRENT_TEST(node_id_testng)
{
node_id rnd = generate_secret_id();
TEST_CHECK(verify_secret_id(rnd));
rnd[19] ^= 0x55;
TEST_CHECK(!verify_secret_id(rnd));
rnd = generate_random_id();
make_id_secret(rnd);
TEST_CHECK(verify_secret_id(rnd));
}
TORRENT_TEST(get_peers_announce)
{
dht_test_setup t(udp::endpoint(rand_v4(), 20));
bdecode_node response;
send_dht_request(t.dht_node, "get_peers", t.source, &response
, msg_args().info_hash("01010101010101010101"));
bdecode_node peer1_keys[4];
std::string token;
std::printf("msg: %s\n", print_entry(response).c_str());
bool ret = dht::verify_message(response, peer1_desc, peer1_keys, t.error_string);
TEST_CHECK(ret);
if (ret)
{
TEST_CHECK(peer1_keys[0].string_value() == "r");
token = peer1_keys[2].string_value().to_string();
// std::printf("got token: %s\n", token.c_str());
}
else
{
std::printf("msg: %s\n", print_entry(response).c_str());
std::printf(" invalid get_peers response: %s\n", t.error_string);
}
send_dht_request(t.dht_node, "announce_peer", t.source, &response
, msg_args()
.info_hash("01010101010101010101")
.name("test")
.token(token)
.port(8080));
dht::key_desc_t const ann_desc[] = {
{"y", bdecode_node::string_t, 1, 0},
{"r", bdecode_node::dict_t, 0, key_desc_t::parse_children},
{"id", bdecode_node::string_t, 20, key_desc_t::last_child},
};
bdecode_node ann_keys[3];
std::printf("msg: %s\n", print_entry(response).c_str());
ret = dht::verify_message(response, ann_desc, ann_keys, t.error_string);
TEST_CHECK(ret);
if (ret)
{
TEST_CHECK(ann_keys[0].string_value() == "r");
}
else
{
std::printf(" invalid announce response:\n");
TEST_ERROR(t.error_string);
}
}
namespace {
void test_scrape(address(&rand_addr)())
{
dht_test_setup t(udp::endpoint(rand_addr(), 20));
bdecode_node response;
init_rand_address();
// announce from 100 random IPs and make sure scrape works
// 50 downloaders and 50 seeds
for (int i = 0; i < 100; ++i)
{
t.source = udp::endpoint(rand_addr(), 6000);
send_dht_request(t.dht_node, "get_peers", t.source, &response
, msg_args().info_hash("01010101010101010101"));
bdecode_node peer1_keys[4];
bool ret = dht::verify_message(response, peer1_desc, peer1_keys, t.error_string);
std::string token;
if (ret)
{
TEST_CHECK(peer1_keys[0].string_value() == "r");
token = peer1_keys[2].string_value().to_string();
}
else
{
std::printf("msg: %s\n", print_entry(response).c_str());
std::printf(" invalid get_peers response: %s\n", t.error_string);
}
response.clear();
send_dht_request(t.dht_node, "announce_peer", t.source, &response
, msg_args()
.info_hash("01010101010101010101")
.name("test")
.token(token)
.port(8080)
.seed(i >= 50));
response.clear();
}
// ====== get_peers ======
send_dht_request(t.dht_node, "get_peers", t.source, &response
, msg_args().info_hash("01010101010101010101").scrape(true));
dht::key_desc_t const peer2_desc[] = {
{"y", bdecode_node::string_t, 1, 0},
{"r", bdecode_node::dict_t, 0, key_desc_t::parse_children},
{"BFpe", bdecode_node::string_t, 256, 0},
{"BFsd", bdecode_node::string_t, 256, 0},
{"id", bdecode_node::string_t, 20, key_desc_t::last_child},
};
bdecode_node peer2_keys[5];
std::printf("msg: %s\n", print_entry(response).c_str());
bool ret = dht::verify_message(response, peer2_desc, peer2_keys, t.error_string);
TEST_CHECK(ret);
if (ret)
{
TEST_CHECK(peer2_keys[0].string_value() == "r");
TEST_EQUAL(peer2_keys[1].dict_find_string_value("n"), "test");
bloom_filter<256> downloaders;
bloom_filter<256> seeds;
downloaders.from_string(peer2_keys[2].string_ptr());
seeds.from_string(peer2_keys[3].string_ptr());
std::printf("seeds: %f\n", double(seeds.size()));
std::printf("downloaders: %f\n", double(downloaders.size()));
TEST_CHECK(std::abs(seeds.size() - 50.f) <= 3.f);
TEST_CHECK(std::abs(downloaders.size() - 50.f) <= 3.f);
}
else
{
std::printf("invalid get_peers response:\n");
TEST_ERROR(t.error_string);
}
}
} // anonymous namespace
TORRENT_TEST(scrape_v4)
{
test_scrape(rand_v4);
}
TORRENT_TEST(scrape_v6)
{
if (supports_ipv6())
test_scrape(rand_v6);
}
namespace {
void test_id_enforcement(address(&rand_addr)())
{
dht_test_setup t(udp::endpoint(rand_addr(), 20));
bdecode_node response;
// enable node_id enforcement
t.sett.set_bool(settings_pack::dht_enforce_node_id, true);
node_id nid;
if (aux::is_v4(t.source))
{
// this is one of the test vectors from:
// http://libtorrent.org/dht_sec.html
t.source = udp::endpoint(addr("124.31.75.21"), 1);
nid = to_hash("5fbfbff10c5d6a4ec8a88e4c6ab4c28b95eee401");
}
else
{
t.source = udp::endpoint(addr("2001:b829:2123:be84:e16c:d6ae:5290:49f1"), 1);