Skip to content

Commit 5cb5ab0

Browse files
committed
routing table: fix invalid iterator access
When calling findClosestNodes with an key referencing the first bucket, the itp iterator could point to before-begin() and dereference it.
1 parent 42fa09a commit 5cb5ab0

File tree

1 file changed

+4
-7
lines changed

1 file changed

+4
-7
lines changed

src/routing_table.cpp

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,8 @@ RoutingTable::depth(const RoutingTable::const_iterator& it) const
8080
std::vector<Sp<Node>>
8181
RoutingTable::findClosestNodes(const InfoHash id, time_point now, size_t count) const
8282
{
83-
std::vector<Sp<Node>> nodes {};
83+
std::vector<Sp<Node>> nodes;
84+
nodes.reserve(count);
8485
auto bucket = findBucket(id);
8586

8687
if (bucket == end()) { return nodes; }
@@ -100,19 +101,15 @@ RoutingTable::findClosestNodes(const InfoHash id, time_point now, size_t count)
100101
};
101102

102103
auto itn = bucket;
103-
auto itp = std::prev(bucket);
104+
auto itp = (bucket == begin()) ? end() : std::prev(bucket);
104105
while (nodes.size() < count && (itn != end() || itp != end())) {
105106
if (itn != end()) {
106107
sortedBucketInsert(*itn);
107108
itn = std::next(itn);
108109
}
109110
if (itp != end()) {
110111
sortedBucketInsert(*itp);
111-
if (itp == begin()) {
112-
itp = end();
113-
continue;
114-
}
115-
itp = std::prev(itp);
112+
itp = (itp == begin()) ? end() : std::prev(itp);
116113
}
117114
}
118115

0 commit comments

Comments
 (0)