From 9f787c8217f2f3e00142aaa340515bc857a841c6 Mon Sep 17 00:00:00 2001 From: Reynald Bourtembourg <reynald.bourtembourg@esrf.fr> Date: Wed, 22 Jan 2020 10:38:11 +0100 Subject: [PATCH] Fix potential crash in AttributeName::tangoHostWithDomain() Fix crash when getaddrinfo is returning several struct addrinfo (tango-controls-hdbpp/hdbpp-cm#6 (comment)) The second struct addrinfo contains a field ai-canonname which is NULL. This could cause a crash because some code is attempting to create a string from a null pointer. getaddrinfo man page (on Debian Buster) says the following: If hints.ai_flags includes the AI_CANONNAME flag, then the ai_canon- name field of the first of the addrinfo structures in the returned list is set to point to the official name of the host. So there is no need to look at the following addrinfo returned structures. --- CHANGELOG.md | 4 ++++ src/AttributeName.cpp | 20 ++++++++++++++++---- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index aac52f3..e11e165 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. ## [Unreleased] +### Fixed + +- Fix potential crash in AttributeName::tangoHostWithDomain() [#8](https://github.com/tango-controls-hdbpp/libhdbpp-timescale/pull/8) + ## [0.11.0] - 2020-01-21 ### Added diff --git a/src/AttributeName.cpp b/src/AttributeName.cpp index b703ee7..61b276f 100644 --- a/src/AttributeName.cpp +++ b/src/AttributeName.cpp @@ -94,7 +94,7 @@ const string &AttributeName::tangoHostWithDomain() hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_CANONNAME; - struct addrinfo *result, *rp; + struct addrinfo *result; const int status = getaddrinfo(server_name.c_str(), nullptr, &hints, &result); if (status != 0) @@ -104,9 +104,21 @@ const string &AttributeName::tangoHostWithDomain() return tangoHost(); } - - for (rp = result; rp != nullptr; rp = rp->ai_next) - server_name_with_domain = string(rp->ai_canonname) + tango_host.substr(tango_host.find(':', 0)); + + if (result == nullptr) + { + spdlog::error("Error: Unable to add domain to tango host {}: getaddrinfo didn't return the canonical name (result == nullptr)", tango_host); + return tangoHost(); + } + + if (result->ai_canonname == nullptr) + { + spdlog::error("Error: Unable to add domain to tango host {}: getaddrinfo didn't return the canonical name (result->ai_canonname == nullptr)", tango_host); + freeaddrinfo(result); + return tangoHost(); + } + + server_name_with_domain = string(result->ai_canonname) + tango_host.substr(tango_host.find(':', 0)); freeaddrinfo(result); // all done with this structure _tango_host_with_domain_cache = server_name_with_domain; -- GitLab