From 5cb5ab019fcc8c1e93fdeeda1b600df8113f4378 Mon Sep 17 00:00:00 2001 From: Adrien Beraud <adrien.beraud@savoirfairelinux.com> Date: Thu, 29 Jun 2017 13:03:07 +0200 Subject: [PATCH] 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. --- src/routing_table.cpp | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/src/routing_table.cpp b/src/routing_table.cpp index 5c1444c1..495846b2 100644 --- a/src/routing_table.cpp +++ b/src/routing_table.cpp @@ -80,7 +80,8 @@ RoutingTable::depth(const RoutingTable::const_iterator& it) const std::vector<Sp<Node>> RoutingTable::findClosestNodes(const InfoHash id, time_point now, size_t count) const { - std::vector<Sp<Node>> nodes {}; + std::vector<Sp<Node>> nodes; + nodes.reserve(count); auto bucket = findBucket(id); if (bucket == end()) { return nodes; } @@ -100,7 +101,7 @@ RoutingTable::findClosestNodes(const InfoHash id, time_point now, size_t count) }; auto itn = bucket; - auto itp = std::prev(bucket); + auto itp = (bucket == begin()) ? end() : std::prev(bucket); while (nodes.size() < count && (itn != end() || itp != end())) { if (itn != end()) { sortedBucketInsert(*itn); @@ -108,11 +109,7 @@ RoutingTable::findClosestNodes(const InfoHash id, time_point now, size_t count) } if (itp != end()) { sortedBucketInsert(*itp); - if (itp == begin()) { - itp = end(); - continue; - } - itp = std::prev(itp); + itp = (itp == begin()) ? end() : std::prev(itp); } } -- GitLab