Fix possible trace file leak in PostgreSQL backend

If connecting to the database fails, postgresql_session_backend dtor is
not executed and traceFile_ could be leaked.

Fix this by using a unique_ptr<> with a custom deleter to store the file
pointer: this ensures that it is closed in any case.
This commit is contained in:
Vadim Zeitlin
2025-11-13 17:20:12 +01:00
parent d56932c4e6
commit 136a3ae961
2 changed files with 6 additions and 10 deletions

View File

@@ -20,6 +20,7 @@
#include <soci/soci-backend.h>
#include "soci/connection-parameters.h"
#include <memory>
#include <vector>
#include <unordered_map>
@@ -441,8 +442,9 @@ struct SOCI_POSTGRESQL_DECL postgresql_session_backend : details::session_backen
PGconn * conn_;
connection_parameters connectionParameters_;
// File used for tracing or null if none.
FILE* traceFile_ = nullptr;
// File used for tracing or empty if none.
using FilePtr = std::unique_ptr<FILE, int(*)(FILE*)>;
FilePtr traceFile_{nullptr, nullptr};
};

View File

@@ -316,7 +316,7 @@ void postgresql_session_backend::connect(
mode = "w";
}
traceFile_ = fopen(value.c_str(), mode);
traceFile_ = FilePtr{fopen(value.c_str(), mode), std::fclose};
if (!traceFile_)
{
std::ostringstream oss;
@@ -363,7 +363,7 @@ void postgresql_session_backend::connect(
if (traceFile_)
{
PQtrace(conn, traceFile_);
PQtrace(conn, traceFile_.get());
}
if (!timeoutStr.empty())
@@ -456,12 +456,6 @@ void postgresql_session_backend::clean_up()
PQfinish(conn_);
conn_ = 0;
}
if (traceFile_)
{
std::fclose(traceFile_);
traceFile_ = nullptr;
}
}
std::string postgresql_session_backend::get_next_statement_name()